branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import React, {Component} from 'react';
import {Container, Row, Col, Table, Button, Form, FormGroup, Input} from 'reactstrap';
import {connect} from 'react-redux';
import {fetchCurriculums, changeCurriculums, deleteCurriculums, postCurriculums} from './actions';
class App extends Component {
constructor(props) {
super(props);
this.state = {
course: '',
faculty: '',
}
}
componentDidMount() {
this.props.fetchCurriculums();
};
handleChange = (event) => {
let name = event.target.name,
value = event.target.value;
this.setState({
[name]: value
})
};
handleDelete = (event) => {
const id = event.target.id;
this.props.deleteCurriculums(id);
};
handleSubmit = () => {
this.props.postCurriculums(this.state);
};
render() {
const {handleChange, handleDelete, handleSubmit} = this;
const {curriculumsList} = this.props.curriculums;
if (!curriculumsList)
return (
<Container>
<Row>
<Col className="text-center text-muted">
<h1 className="display-1 text-muted"><i className="far fa-frown"></i></h1>
</Col>
</Row>
<Row>
<Col className="text-center">
<h1 className="display-2 text-muted">404</h1>
<p className="lead">Page not found</p>
<p className="small">The Page you are looking for doesn't exist or an other error
occured.</p>
<p className="small">Go to my <a href="https://github.com/tickstudiu" className="text-success">Github</a>, or to <a
href="https://www.facebook.com/sliple.ness" className="text-success">facebook.com</a> to ask a question.</p>
</Col>
</Row>
</Container>
);
else
return (
<Container>
<Row>
<Col>
<h1 className="display-4 text-uppercase">College of Computing</h1>
<hr/>
</Col>
</Row>
<Row>
<Col>
<Table borderless>
<thead>
<tr>
<th style={{width: '10px'}}>#</th>
<th style={{width: '40px'}}>Course</th>
<th>Faculty</th>
<th className="mr-auto text-center" style={{width: '100px'}}>option</th>
</tr>
</thead>
<tbody>
{
curriculumsList.map((data, index) => {
return <tr key={index}>
<th scope="row">{data.id}</th>
<td className="text-uppercase">{data.course}</td>
<td className="text-uppercase">{data.faculty}</td>
<td><Button outline color="danger" id={data.id}
onClick={handleDelete}>delete</Button></td>
</tr>
})
}
</tbody>
</Table>
</Col>
</Row>
<Row>
<Col>
<hr/>
<p className="lead text-mute">Add Curriculum</p>
<Form inline>
<FormGroup>
<Input type="text" name="course" placeholder="course..." className="mr-2"
onChange={handleChange}/>
<Input type="text" name="faculty" placeholder="faculty..." className="mr-2"
onChange={handleChange}/>
</FormGroup>
<Button outline color="primary" onClick={handleSubmit}>Submit</Button>
</Form>
</Col>
</Row>
</Container>
)
}
}
const mapStateToProps = ({curriculums}) => {
return {
curriculums,
}
};
export default connect(mapStateToProps, {changeCurriculums, fetchCurriculums, deleteCurriculums, postCurriculums})(App);
|
d6d470b7672dc1f375a83ec8512edcab729c6aa2
|
[
"JavaScript"
] | 1
|
JavaScript
|
tickstudiu/react-redux-client
|
8900d69ea8374fb7e61c761a57b1327c8c872723
|
1a534783ce0e31ffd1f06d55397146f37889050c
|
refs/heads/master
|
<repo_name>rranauro/connect_wrapper<file_sep>/README.md
# connect_wrapper
Simple MongoDB Connnection Wrapper
<file_sep>/index.js
/*jslint newcap: false, node: true, vars: true, white: true, nomen: true */
/*global _: true, Basepath: true, Boxspring: true, start: true, toJSON: true, getRow: true, send: true */
"use strict";
var _ = require('underscore')._
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var pool = {};
var uuidV1 = require('uuid').v1;
var async = require('async');
var ConnectWrapper = function(auth, uri_template, collection_prefix) {
this._arguments = _.toArray( arguments ).slice(0);
auth = auth ? auth.split(' ') : '';
var plain_auth = new Buffer(auth[1], 'base64'); // create a buffer and tell it the data coming in is base64
plain_auth = plain_auth.toString().split(':'); // read it back out as a string
this.url = _.template(uri_template)({
username: plain_auth[0],
password: <PASSWORD>[1]
});
// beware, this is undefined if not already "auth"
this._db = pool[this.url];
// allow multiple logical databases within 1 physical;
this._collection_prefix = collection_prefix ? collection_prefix + ':' : '';
this._connection_id = uuidV1();
// this.url = MONGO_URI
return this;
};
ConnectWrapper.prototype.renew = function(callback) {
exports.connectWrapper.apply(null, this._arguments ).auth(null, null, callback);
};
ConnectWrapper.prototype.noPrefix = function() {
return new ConnectWrapper( this._arguments[0], this._arguments[1] );
};
ConnectWrapper.prototype.auth = function(req, res, next) {
var self = this;
if (!pool[self.url]) {
// initiate new connection
MongoClient.connect( this.url, function(err, db) {
if (err) {
return next(err);
}
pool[self.url] = self._db = db;
setTimeout(next, 50);
});
} else {
self._db = pool[self.url];
setTimeout(next, 50);
}
return this;
};
ConnectWrapper.prototype.createUser = function(req, res, next) {
var password = require('password-hash-and-salt');
var self = this;
// hash the password and store it in the "users" collection
password( req.body.password ).hash(function(err, salted) {
if (err) {
return res.status( 400 ).json({error: err, message: err});
}
self.create( 'users' )({body: {_id: req.body.name || req.body.user, hash: salted, roles: req.body.roles, customData: req.body.customData}}, res, next);
});
};
ConnectWrapper.prototype.updatePassword = function(req, res, next) {
var password = require('password-hash-and-salt');
var self = this;
password( req.body.password ).hash(function(err, salted) {
if (err) {
return res.status( 400 ).json({error: err, message: err});
}
req.body.hash = salted;
self.update( 'users' )({params: {id: req.params.id}, body: req.body}, res, next);
});
};
ConnectWrapper.prototype.authenticateUser = function(req, res, next) {
var password = require('password-hash-and-salt');
var self = this;
this.read( 'users' )({params:{id: req.params.id}}, res, function(err, doc) {
if (err) return res.status( 404 ).json({error: err.name, message: err.message});
if (!doc) return res.status( 404 ).json({error: 'error', message: 'not_found'});
// Verifying a hash
password(req.session.passWord || req.body.password).verifyAgainst(doc.hash, function(err, verified) {
if (err) return res.status( 403 ).json({error: err, message: err});
if (_.isFunction(next)) {
return next(!verified, doc);
}
res.status( !verified ? 403 : 200 ).json(!verified ? {error: 'forbidden', message:'authentication_failed'} : {ok:true});
});
});
};
ConnectWrapper.prototype.createQueue = function( collection, limit, update ) {
let originalCollection = collection;
let self = this;
self._options = {upsert:false}
limit = _.isNumber(limit) ? (limit > 0 ? limit : 10000) : 10000;
collection = this._collection_prefix + collection;
let docs_to_save = [];
let count = 0;
let flush = function(options, next) {
if (_.isFunction(options)) {
next = options;
options = {};
}
next = next || function(){};
options = _.defaults(options || {}, {upsert: false});
let to_save = docs_to_save.slice(0);
docs_to_save.length = 0;
count += to_save.length;
if (to_save.length) {
console.log('[createQueue] info: saving...', to_save.length, count);
return self.create( originalCollection )({body: to_save}, null, next);
}
return next();
};
let queue = async.queue(function(docs, next) {
if (update) {
if (!(count %1000)) console.log('[createQueue] info: updating...', count);
count += 1;
if (!docs.hasOwnProperty('$set')) {
docs['$set'] = _.omit(docs, '_id');
}
return self.collection( originalCollection )
.findOneAndUpdate({_id: docs._id}, {$set: docs['$set']}, self._options, next);
}
if (_.isArray(docs)) {
docs_to_save = docs_to_save.concat( docs )
} else {
docs_to_save.push( docs );
}
if (limit && docs_to_save.length >= limit) {
return process.nextTick(function() {
flush.call(self, {}, next);
});
}
return process.nextTick( next );
}, update ? 4 : 1);
return {
options: function(obj) {
self._options = obj;
return this;
},
drain: function(fN) {
queue.drain = _.bind(fN, self);
return this;
},
push: function(jobs, callback) {
queue.push( jobs, callback );
return this;
},
flush: _.bind(flush, self)
};
};
ConnectWrapper.prototype.create = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
var self = this;
var options;
// We don't want to rely Mong's OID
if (_.isArray(req.body)) {
req.body = req.body.map(function(doc) {
if (!doc._id) {
doc._id = uuidV1();
}
return doc;
});
options = _.defaults(req.options || {}, {ordered: false});
} else if (!req.body._id) {
req.body._id = uuidV1();
options = {};
}
try {
if (_.isArray(req.body)) {
// copy docs 1000 at a time
async.eachLimit(_.range(0, req.body.length, 10000), 1, function(start, go) {
self._db.collection( collection ).insertMany(req.body.slice(start, start+10000), options, function(err) {
if (err) {
console.log('[connect_wrapper/create] warning: error', (err && err.message) || err);
}
go();
});
}, function() {
console.log('[ConnectWrapper] info: saved', collection, req.body.length);
next();
});
} else {
// don't quit on duplicate _id errors
this._db.collection( collection ).insertOne( req.body, options, function(e,r) {
if (e) return next(null, {error: e.name, reason: e.message});
next.apply(null, arguments);
});
}
} catch(e) {
next(null, {error: e.name, reason: e.message});
}
}, this);
};
ConnectWrapper.prototype.update = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
var data;
var select = {_id: req.params && req.params.id};
if (!(req.params && req.params.id)) {
select = req.body.select;
data = req.body.data;
} else if (_.keys(req.query || {}).length){
data = req.query;
} else {
data = req.body;
}
this._db.collection( collection ).updateOne( select, {$set: data || {}}, next);
}, this);
};
ConnectWrapper.prototype.count = function(collection) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
this._db.collection( collection )
.find( req.query || {})
.project( {_id: 1} )
.toArray( function(err, results) {
next(null, results.length);
});
}, this);
}
ConnectWrapper.prototype.collection = function( collection ) {
collection = this._collection_prefix + collection;
return this._db.collection( collection );
};
ConnectWrapper.prototype.collectionName = function( collection ) {
return this._collection_prefix + collection;
};
ConnectWrapper.prototype.collectionPrefix = function() {
return this._collection_prefix;
};
ConnectWrapper.prototype.cursor = function( collection) {
let cursor = this.collection( collection );
return _.bind(function(find, project, Fn, Final) {
let limit = find.limit;
let docs = [];
if (limit) {
delete find.limit;
}
this.collection(collection).count(find, null, function(err, count) {
console.log('[cursor] info: entries', count);
if (!count || count === limit) {
return Final( docs );
}
limit = limit || count;
cursor.find( find ).project( project ).forEach(function(doc) {
count -= 1;
if (limit) {
doc = Fn( doc );
if (doc) {
docs.push( doc );
}
if (!(count % 10000)) {
console.log('[cursor] info: Remaining', count, _.memory());
}
limit -= 1;
}
if (!count) {
return Final( docs );
}
});
});
}, this);
};
ConnectWrapper.prototype.all_ids = function( collection ) {
return _.bind(function(req, res, next) {
this._db.collection(collection)
.find(req.query || {})
.project({_id:1})
.toArray(function(err, results) {
next(err, results ? results.map(function(doc) { return doc._id; }) : []);
})
}, this);
};
ConnectWrapper.prototype.bulkSave = function(collection1, collection2) {
let self = this;
return _.bind(function(req, res, next) {
let size = req.query.size || 1000;
self.all_ids( collection1 )({}, null, function(err, ids) {
if (err) {
console.log('[bulkSave] error: ', err.message);
return next(err);
}
// copy docs 1000 at a time
console.log('[bulkSave] info:', collection2, ids.length);
async.eachLimit(_.range(0, ids.length, size), 1, function(start, next) {
console.log('[bulkSave] info:', start, ids.length);
self._db.collection( collection1 ).find({_id:{$in: ids.slice(start, start+size)}}).toArray(function(err, docs) {
req.query.target._db.collection( collection2 ).insertMany(docs, function(err) {
if (err) {
console.log('[connect_wrapper/bulkSave] warning: error', err.message);
}
next();
});
});
}, next);
});
}, this);
};
ConnectWrapper.prototype.read = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
var query
, limit = (req.query && req.query.limit) || 0
, page = req.query && req.query.page
, pageSize = req.query && req.query.pageSize
, $project = req.$project || {}
if (req.params && req.params.id) {
return this._db.collection( collection ).findOne( {_id: req.params.id}, next )
}
if ((req.method || 'GET').toUpperCase() === 'GET') {
query = req.query;
} else {
query = req.body;
}
if (limit) {
limit = parseInt( query.limit, 10);
delete query.limit;
}
if (page && pageSize) {
page = parseInt(page, 10);
pageSize = parseInt(pageSize, 10);
if (typeof page !== 'number' || typeof pageSize !== 'number') page = undefined;
}
this._db.collection( collection )
.find( query || {}).limit( limit )
.project( $project )
.toArray( function(err, results) {
if (err) return next(err, results);
if (page && pageSize) {
return next(null, results.slice(page, (page * pageSize) + pageSize));
}
next(null, results);
});
}, this);
};
ConnectWrapper.prototype.readAll = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
this._db.collection( collection ).findOne( req.query, next );
}, this);
};
ConnectWrapper.prototype.deleteOne = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
if (req.params && req.params.id) {
return this._db.collection( collection ).deleteOne( {_id: req.params.id}, next )
}
return this._db.collection( collection ).deleteOne( req.query || {}, next )
}, this);
};
ConnectWrapper.prototype.drop = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
if (!this._db) {
return next({error: 'missing database', message: 'database not available'});
}
this._db.collection( collection ).drop( function() { next.apply(null, arguments); } );
}, this);
};
ConnectWrapper.prototype.view = function( collection ) {
collection = this._collection_prefix + collection;
return _.bind(function(req, res, next) {
this._db.collection( collection ).createIndex(req.body, next );
}, this);
};
var connectWrapper = function(auth, URI, prefix) {
return new ConnectWrapper(auth, URI, prefix);
};
exports.connectWrapper = connectWrapper;
|
25805be5407863a01940fa5c0fb0bfe976649a5f
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
rranauro/connect_wrapper
|
0617f4e49b430e3643b7b2bc1081f1bc2642f588
|
8f56a9753f9319051a145ba59e63330d97cdeaf4
|
refs/heads/master
|
<file_sep>fib = [1, 1]
while fib.last.to_s.length < 1000
fib << fib[-1] + fib[-2]
end
puts fib.count
<file_sep>let numbers = (1...999).filter { i in
i % 3 == 0 || i % 5 == 0
}.reduce(0, combine: +)
<file_sep>puts (2**1000).to_s.split(//).map{|n| n.to_i }.inject :+
<file_sep>My [project euler]("http://projecteuler.net") solutions in multiple languages,
organized by number.
<file_sep>puts (1...1000).to_a.keep_if{ |n| n % 3 == 0 or n % 5 == 0 }.inject :+
<file_sep>fib = [1, 1]
while fib.last < 4000000
fib << fib[-1] + fib[-2]
end
puts fib[0...-1].keep_if{ |n| n.even? }.inject :+
<file_sep>require 'Prime'
puts (Prime.prime_division 600851475143).sort.max[0]
|
3bff80605e3744075f8353b92ceccba799c9fb55
|
[
"Swift",
"Ruby",
"Markdown"
] | 7
|
Ruby
|
runkmc/euler
|
1a1bcb23d5894d27b97d4259a8bbb038ccbf5fba
|
3056d05a8318e611dbfe01b2b53a4489c9b224a9
|
refs/heads/master
|
<file_sep># ADXL345 Python example
#
# author: <NAME>
# license: BSD, see LICENSE.txt included in this package
#
# This is an example to show you how to use our ADXL345 Python library
# http://shop.pimoroni.com/products/adafruit-triple-axis-accelerometer
from adxl345p3 import ADXL345
adxl345 = ADXL345()
axes = adxl345.getAxes(True)
print ("ADXL345 on address 0x{:x}:".format(adxl345.address))
print (" x = {:0.3f}G".format( axes['x'] ))
print (" y = {:0.3f}G".format( axes['y'] ))
print (" z = {:0.3f}G".format( axes['z'] ))
|
1a07e7a821980d102041a99299ba19035658e0cc
|
[
"Python"
] | 1
|
Python
|
topshed/PAComp
|
bdef175d57649e44765da6c73fc2f7fdfe209788
|
1b173d869c631015f5b353f4bc97ca86fb501382
|
refs/heads/main
|
<file_sep>import { galleryItems } from './app.js';
const galleryRefersArray = galleryItems.map(item => item.original);
const refs = {
galleryContainer: document.querySelector('.js-gallery'),
lightboxContainer: document.querySelector('.js-lightbox'),
closeButton: document.querySelector('.lightbox__button'),
lightboxImage: document.querySelector('.lightbox__image'),
lightboxOverlay: document.querySelector('.lightbox__overlay')
};
const stringsMarkup = galleryItems.reduce((acc, { preview, original, description }) =>
acc += `<li class="gallery__item">
<a
class="gallery__link"
href="${original}"
>
<img
class="gallery__image"
src="${preview}"
data-source="${original}"
alt="${description}"
/>
</a>
</li>`, ''
);
refs.galleryContainer.insertAdjacentHTML('afterbegin', stringsMarkup);
refs.galleryContainer.addEventListener('click', onClickImage);
function onClickImage(event) {
event.preventDefault();
if (!event.target.classList.contains("gallery__image")) {
return
};
refs.lightboxContainer.classList.add('is-open');
refs.lightboxImage.setAttribute("src", event.target.dataset.source);
refs.lightboxImage.setAttribute("alt", event.target.getAttribute("alt"));
refs.lightboxContainer.addEventListener('click', onClickClose);
window.addEventListener("keydown", onPressKey);
};
function onClickClose(event) {
if (event.target !== refs.lightboxImage) {
refs.lightboxContainer.classList.remove('is-open');
refs.lightboxImage.src = "";
refs.lightboxImage.alt = "";
refs.closeButton.removeEventListener('click', onClickClose);
window.removeEventListener("keydown", onPressKey);
}
};
function onPressKey(event) {
if (event.code === "Escape") {
onClickClose(event)
}
else if
(event.code === "ArrowRight") {
const currentNumber = galleryRefersArray.indexOf(refs.lightboxImage.getAttribute("src"));
if (currentNumber < (galleryRefersArray.length - 1)) {
refs.lightboxImage.src = galleryItems[currentNumber + 1].original;
refs.lightboxImage.setAttribute.alt = [currentNumber + 1].description;
}
}
else if
(event.code === "ArrowLeft") {
const currentNumber = galleryRefersArray.indexOf(refs.lightboxImage.getAttribute("src"));
if (currentNumber > 0) {
refs.lightboxImage.src = galleryItems[currentNumber - 1].original;
refs.lightboxImage.alt = galleryItems[currentNumber - 1].description;
}
}
}
|
b7d9708688a4a999f620bd3f15e6046865c7a4bf
|
[
"JavaScript"
] | 1
|
JavaScript
|
Vitalina-Oleksiienko/goit-js-hw-08-gallery
|
f3473da46dc757a1b8b5a98aa837d852d866e49e
|
99916ae0a3f88f4b3a0d1f8bc168f505613acbce
|
refs/heads/master
|
<repo_name>popov-aa/ShootThemUp<file_sep>/Source/ShootThemUp/Public/Components/STUHealthComponent.h
// ShootThemUp Game. All rights reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "STUHealthComponent.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class SHOOTTHEMUP_API USTUHealthComponent : public UActorComponent
{
GENERATED_BODY()
public:
USTUHealthComponent();
float GetHealth() const;
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category="Health", meta = (ClampMin = "0.0", ClampMax = "1000.0"))
float MaxHealth = 100.0f;
virtual void BeginPlay() override;
private:
float Health = 0.0f;
};
<file_sep>/Source/ShootThemUp/Public/Player/STUBaseCharacter.h
// ShootThemUp Game. All rights reserved.
#pragma once
#include "Components/STUHealthComponent.h"
#include "Components/TextRenderComponent.h"
#include "GameFramework/SpringArmComponent.h"
class UCameraComponent;
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "STUBaseCharacter.generated.h"
UCLASS()
class SHOOTTHEMUP_API ASTUBaseCharacter : public ACharacter
{
GENERATED_BODY()
public:
ASTUBaseCharacter(const FObjectInitializer& ObjectInitializer);
protected:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Components")
UCameraComponent* CameraComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="SpringArmComponent")
USpringArmComponent* SpringArmComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Components")
USTUHealthComponent* HealthComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Components")
UTextRenderComponent* HealthTextComponent;
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UFUNCTION(BlueprintCallable, Category="Movement")
bool IsRunning() const;
UFUNCTION(BlueprintCallable, Category="Movement")
float GetMovementDirection() const;
private:
bool WantsToRun = false;
bool IsMovingForward = false;
void MoveForward(float Amount);
void MoveRight(float Amount);
void OnStartRunning();
void OnStopRunning();
};
<file_sep>/Source/ShootThemUp/Private/Components/STUHealthComponent.cpp
// ShootThemUp Game. All rights reserved.
#include "Components/STUHealthComponent.h"
USTUHealthComponent::USTUHealthComponent()
{
PrimaryComponentTick.bCanEverTick = false;
}
float USTUHealthComponent::GetHealth() const
{
return this->Health;
}
void USTUHealthComponent::BeginPlay()
{
Super::BeginPlay();
this->Health = this->MaxHealth;
}
<file_sep>/Config/DefaultGame.ini
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=FD0C332B495AB50F1FCE5FBABBCA30EE
CopyrightNotice=ShootThemUp Game. All rights reserved.
<file_sep>/Source/ShootThemUp/Private/Player/STUPlayerController.cpp
// ShootThemUp Game. All rights reserved.
#include "Player/STUPlayerController.h"
<file_sep>/Source/ShootThemUp/Private/STUGameModeBase.cpp
// ShootThemUp Game. All rights reserved.
#include "STUGameModeBase.h"
#include "Player/STUBaseCharacter.h"
#include "Player/STUPlayerController.h"
ASTUGameModeBase::ASTUGameModeBase()
{
this->DefaultPawnClass = ASTUBaseCharacter::StaticClass();
this->PlayerControllerClass = ASTUPlayerController::StaticClass();
}
<file_sep>/Source/ShootThemUp/Private/Components/STUCharacterMovementComponent.cpp
// ShootThemUp Game. All rights reserved.
#include "Components/STUCharacterMovementComponent.h"
#include "Player/STUBaseCharacter.h"
float USTUCharacterMovementComponent::GetMaxSpeed() const
{
const float MaxSpeed = Super::GetMaxSpeed();
const ASTUBaseCharacter* Character = Cast<ASTUBaseCharacter>(this->GetPawnOwner());
return Character && Character->IsRunning() ? MaxSpeed * RunModifier : MaxSpeed;
}
<file_sep>/Source/ShootThemUp/Private/Player/STUBaseCharacter.cpp
// ShootThemUp Game. All rights reserved.
#include "Player/STUBaseCharacter.h"
#include "Camera/CameraComponent.h"
#include "Components/STUCharacterMovementComponent.h"
#include "Components/STUHealthComponent.h"
#include "Components/InputComponent.h"
ASTUBaseCharacter::ASTUBaseCharacter(const FObjectInitializer &ObjectInitializer)
: Super(ObjectInitializer.SetDefaultSubobjectClass<USTUCharacterMovementComponent>(ACharacter::CharacterMovementComponentName))
{
PrimaryActorTick.bCanEverTick = true;
this->SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>("SpringArmComponent");
this->SpringArmComponent->SetupAttachment(this->GetRootComponent());
this->SpringArmComponent->bUsePawnControlRotation = true;
this->CameraComponent = CreateDefaultSubobject<UCameraComponent>("CameraComponent");
this->CameraComponent->SetupAttachment(this->SpringArmComponent);
this->HealthComponent = CreateDefaultSubobject<USTUHealthComponent>("HealthComponent");
this->HealthTextComponent = CreateDefaultSubobject<UTextRenderComponent>("HealthTextComponent");
this->HealthTextComponent->SetupAttachment(this->GetRootComponent());
}
void ASTUBaseCharacter::BeginPlay()
{
Super::BeginPlay();
check(this->HealthComponent);
check(this->HealthTextComponent);
}
void ASTUBaseCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
const auto Health = this->HealthComponent->GetHealth();
this->HealthTextComponent->SetText(FText::FromString(FString::Printf(TEXT("%.0f"), Health)));
}
void ASTUBaseCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (PlayerInputComponent)
{
PlayerInputComponent->BindAxis("MoveForward", this, &ASTUBaseCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &ASTUBaseCharacter::MoveRight);
PlayerInputComponent->BindAxis("LookUp", this, &ASTUBaseCharacter::AddControllerPitchInput);
PlayerInputComponent->BindAxis("TurnAround", this, &ASTUBaseCharacter::AddControllerYawInput);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ASTUBaseCharacter::Jump);
PlayerInputComponent->BindAction("Run", IE_Pressed, this, &ASTUBaseCharacter::OnStartRunning);
PlayerInputComponent->BindAction("Run", IE_Released, this, &ASTUBaseCharacter::OnStopRunning);
}
}
bool ASTUBaseCharacter::IsRunning() const
{
return this->WantsToRun && this->IsMovingForward && !this->GetVelocity().IsZero();
}
float ASTUBaseCharacter::GetMovementDirection() const
{
if (GetVelocity().IsZero())
{
return 0;
}
const auto VelocityNormal = GetVelocity().GetSafeNormal();
const auto AngleBetween = FMath::Acos(FVector::DotProduct(GetActorForwardVector(), VelocityNormal));
const auto CrossProduct = FVector::CrossProduct(GetActorForwardVector(), VelocityNormal);
const auto Degrees = FMath::RadiansToDegrees(AngleBetween);
return CrossProduct.IsZero() ? Degrees : Degrees * FMath::Sign(CrossProduct.Z);
}
void ASTUBaseCharacter::MoveForward(float Amount)
{
this->IsMovingForward = Amount > 0.0f;
if (Amount != 0.0f)
{
this->AddMovementInput(this->GetActorForwardVector(), Amount);
}
}
void ASTUBaseCharacter::MoveRight(float Amount)
{
if (Amount != 0.0f)
{
this->AddMovementInput(this->GetActorRightVector(), Amount);
}
}
void ASTUBaseCharacter::OnStartRunning()
{
WantsToRun = true;
}
void ASTUBaseCharacter::OnStopRunning()
{
WantsToRun = false;
}
|
d934769087e2e8f66f55721b77f94ec8f888826c
|
[
"C++",
"INI"
] | 8
|
C++
|
popov-aa/ShootThemUp
|
a2018fc8bc66d34b8ac67adf898a6310546f2317
|
a99d20d605618eeef1205c90e3615b8bbb956d22
|
refs/heads/main
|
<file_sep><?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\LinksTypesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Links';
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="links-index">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
//'long_url:url',
[
'label' => Yii::t('app', 'Short Code'),
'attribute' => 'short_code',
'format' => 'raw',
'value' => function ($model) {
$value = Yii::t('app', $model->short_code);
$url = Url::toRoute(['/links', 'token' => $model->short_code]);
return Html::a($model->short_code, $url,
['target' => '_blank']);
}
],
'limit',
//'hits',
'lifetime',
//'created_dt',
//'updated_dt',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3306
-- Время создания: Сен 09 2021 г., 12:21
-- Версия сервера: 5.7.33-log
-- Версия PHP: 7.4.21
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `short-link-service`
--
-- --------------------------------------------------------
--
-- Структура таблицы `links`
--
CREATE TABLE `links` (
`id` int(11) NOT NULL,
`long_url` varchar(255) NOT NULL,
`short_code` varchar(255) NOT NULL,
`limit` int(11) UNSIGNED NOT NULL,
`hits` int(11) UNSIGNED DEFAULT '0',
`lifetime` int(11) UNSIGNED NOT NULL,
`created_dt` timestamp NOT NULL,
`updated_dt` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `links`
--
INSERT INTO `links` (`id`, `long_url`, `short_code`, `limit`, `hits`, `lifetime`, `created_dt`, `updated_dt`) VALUES
(1, 'https://www.google.com/', 'XLVS6fs2', 3, 0, 5, '2021-09-09 07:55:37', NULL),
(2, 'https://www.youtube.com/', '5p9jpGL4', 5, 1, 10, '2021-09-09 07:56:01', '2021-09-09 08:02:15');
-- --------------------------------------------------------
--
-- Структура таблицы `migration`
--
CREATE TABLE `migration` (
`version` varchar(180) NOT NULL,
`apply_time` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `migration`
--
INSERT INTO `migration` (`version`, `apply_time`) VALUES
('m000000_000000_base', 1631086181),
('m210908_065517_create_links_table', 1631090810);
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `links`
--
ALTER TABLE `links`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `migration`
--
ALTER TABLE `migration`
ADD PRIMARY KEY (`version`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `links`
--
ALTER TABLE `links`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
namespace app\controllers;
use app\models\Links;
use app\models\LinksTypesSearch;
use Exception;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* LinksController implements the CRUD actions for Links model.
*/
class LinksController extends Controller
{
protected static $chars = "abcdfghjkmnpqrstvwxyz|ABCDFGHJKLMNPQRSTVWXYZ|0123456789";
protected static $checkUrlExists = true;
protected static $codeLength = 8;
/**
* @inheritDoc
*/
public function behaviors()
{
return array_merge(
parent::behaviors(),
[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
]
);
}
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Lists all Links models.
* @return mixed
* @throws Exception
*/
public function actionIndex()
{
$model = new Links();
$searchModel = new LinksTypesSearch();
$dataProvider = $searchModel->search($this->request->queryParams);
if ($this->request->isPost) {
if ($model->load($this->request->post())) {
$shortCode = $this->actionCreate($model);
if(!$shortCode) {
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
$model->short_code = $shortCode;
if($model->save()) {
Yii::$app->session->setFlash('success', "Link saved successfully");
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
}
} else {
$model->loadDefaultValues();
}
if ($token = $this->request->get('token')) {
//print_r($token);exit();
$url = $this->shortCodeToUrl($token);
return Yii::$app->getResponse()->redirect($url);
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
/**
* @param $model
* @return bool|string
* @throws Exception
*/
public function actionCreate($model)
{
if($this->validateUrlFormat($model->long_url) == false){
throw new Exception(Yii::$app->params['link_not_valid_format']);
}
if(self::$checkUrlExists){
if (!$this->verifyUrlExists($model->long_url)){
throw new Exception(Yii::$app->params['url_not_exist']);
}
}
$shortCode = $this->urlExistsInDB($model->long_url);
if($shortCode == false){
return $this->createShortCode(self::$codeLength);
}
Yii::$app->session->setFlash('error', "This link already exists in the database");
return false;
}
/**
* @param $url
* @return mixed
*/
protected function validateUrlFormat($url){
return filter_var($url, FILTER_VALIDATE_URL);
}
/**
* @param $url
* @return bool
*/
protected function verifyUrlExists($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (!empty($response) && $response != 404);
}
/**
* @param $url
* @return bool|mixed
*/
protected function urlExistsInDB($url){
$link = Links::find()->where(['long_url' => $url])->one();
return (empty($link->short_code)) ? false : $link->short_code;
}
/**
* @param int $length
* @return string
*/
protected function createShortCode($length = 8){
$sets = explode('|', self::$chars);
$all = '';
$randString = '';
foreach($sets as $set){
$randString .= $set[array_rand(str_split($set))];
$all .= $set;
}
$all = str_split($all);
for($i = 0; $i < $length - count($sets); $i++){
$randString .= $all[array_rand($all)];
}
$randString = str_shuffle($randString);
return $randString;
}
/**
* @param $short_code
* @return bool|mixed
* @throws NotFoundHttpException
*/
public function shortCodeToUrl($short_code){
$model = Links::find()->where(['short_code' => $short_code])->one();
$lifetime = strtotime($model->created_dt) + ($model->lifetime * 60);
if(($model->limit != 0) && (($model->hits + 1) > $model->limit)) throw new NotFoundHttpException(Yii::$app->params['not_valid_link']);
if(time() > $lifetime) throw new NotFoundHttpException(Yii::$app->params['link_expired']);
if(empty($model)) return false;
$model->hits = $model->hits + 1;
$model->save();
return $model->long_url;
}
//
// /**
// * Displays a single Links model.
// * @param int $id ID
// * @return mixed
// * @throws NotFoundHttpException if the model cannot be found
// */
// public function actionView($id)
// {
// return $this->render('view', [
// 'model' => $this->findModel($id),
// ]);
// }
//
//
//
// /**
// * Updates an existing Links model.
// * If update is successful, the browser will be redirected to the 'view' page.
// * @param int $id ID
// * @return mixed
// * @throws NotFoundHttpException if the model cannot be found
// */
// public function actionUpdate($id)
// {
// $model = $this->findModel($id);
//
// if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
// return $this->redirect(['view', 'id' => $model->id]);
// }
//
// return $this->render('update', [
// 'model' => $model,
// ]);
// }
//
// /**
// * Deletes an existing Links model.
// * If deletion is successful, the browser will be redirected to the 'index' page.
// * @param int $id ID
// * @return mixed
// * @throws NotFoundHttpException if the model cannot be found
// */
// public function actionDelete($id)
// {
// $this->findModel($id)->delete();
//
// return $this->redirect(['index']);
// }
//
// /**
// * Finds the Links model based on its primary key value.
// * If the model is not found, a 404 HTTP exception will be thrown.
// * @param int $id ID
// * @return Links the loaded model
// * @throws NotFoundHttpException if the model cannot be found
// */
// protected function findModel($id)
// {
// if (($model = Links::findOne($id)) !== null) {
// return $model;
// }
//
// throw new NotFoundHttpException('The requested page does not exist.');
// }
}
<file_sep><?php
return [
'adminEmail' => '<EMAIL>',
'senderEmail' => '<EMAIL>',
'senderName' => '<NAME>',
'link_not_valid_format' => 'URL does not have a valid format.',
'url_not_exist' => 'URL does not appear to exist.',
'not_valid_link' => 'The above error occurred while processing your link. Your link is no longer valid.',
'link_expired' => 'The above error occurred while processing your link. Link expired.',
];
<file_sep><?php
use yii\db\Migration;
/**
* Handles the creation of table `{{%links}}`.
*/
class m210908_065517_create_links_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('{{%links}}', [
'id' => $this->primaryKey(),
'long_url'=>$this->string()->notNull(),
'short_code'=>$this->string()->notNull(),
'limit'=> $this->integer()->unsigned()->notNull(),
'hits'=> $this->integer()->defaultValue(0)->unsigned(),
'lifetime'=> $this->integer()->unsigned()->notNull(),
'created_dt' => $this->timestamp()->notNull(),
'updated_dt' => $this->timestamp()->null(),
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%links}}');
}
}
<file_sep><?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "links".
*
* @property int $id
* @property string $long_url
* @property string $short_code
* @property int|null $limit
* @property int|null $hits
* @property string $lifetime
* @property string $created_dt
* @property string|null $updated_dt
*/
class Links extends \yii\db\ActiveRecord
{
/**
* @return array
*/
public function behaviors() {
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_dt'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_dt'],
],
'value' => date('Y-m-d H:i:s'),
],
];
}
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'links';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['long_url', 'lifetime', 'limit'], 'required'],
[['limit', 'hits'], 'integer'],
[['lifetime', 'created_dt', 'updated_dt'], 'safe'],
[['short_code'], 'string', 'max' => 255],
[['lifetime'], 'integer', 'min' => 1, 'max' => 24],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'long_url' => 'Long Url',
'short_code' => 'Short Code',
'limit' => 'Limit',
'hits' => 'Hits',
'lifetime' => 'Lifetime',
'created_dt' => 'Created Dt',
'updated_dt' => 'Updated Dt',
];
}
}
|
ad85db309f22474c6385606729078bd6824a7251
|
[
"SQL",
"PHP"
] | 6
|
PHP
|
qazteer/short-link-service
|
54826e81b60d8515d1a0ae78ef234671fc1b9614
|
2f0a2fde5e9992e5e8021ca8599fa9f13040f7b0
|
refs/heads/master
|
<file_sep>/* This code implements a recursive solution to convert a binary
* tree into a "circular (optional) doubly linked list" with the nodes
* in the list appearing as per the "inorder" traversal of the tree.
* Example:
* input tree:
* A
* / \
* B C
* / \ / \
* D E F G
*
* output list:
* head-> D <-> B <-> E <-> A <-> F <-> C <-> G
*
*
*/
#include <stdio.h>
#include <assert.h>
typedef struct node {
int v;
struct node *left;
struct node *right;
}Node ;
Node** convert_tree_to_list(Node *root) {
Node **p = (Node**) malloc(2*sizeof(Node*));
Node **lret;
Node **rret;
if (root->left == NULL)
p[0] = root;
else {
lret = convert_tree_to_list(root->left);
root->left = lret[1];
lret[1]->right = root;
p[0] = lret[0];
free(lret);
}
if (root->right == NULL)
p[1] = root;
else {
rret = convert_tree_to_list(root->right);
root->right = rret[0];
rret[0]->left = root;
p[1] = rret[1];
free(rret);
}
return p;
}
Node* tree_to_list(Node *root) {
if (root == NULL)
return NULL;
Node **ret = convert_tree_to_list(root);
//For a circular linked list, change this
//to
//ret[0]->left = ret[1];
//ret[1]->right = ret[0];
ret[0]->left = NULL;
ret[1]->right = NULL;
return ret[0];
}
Node *getNode(int val, Node *l, Node *r) {
Node *n = (Node*)malloc(sizeof(Node));
assert(n!=NULL);
n->left = l;
n->right = r;
n->v = val;
return n;
}
Node *createTree() {
Node *l5 = getNode(5, NULL, NULL);
Node *l6 = getNode(6, NULL, NULL);
Node *l7 = getNode(7, NULL, NULL);
Node *l8 = getNode(8, NULL, NULL);
Node *l3 = getNode(3, l5, l6);
Node *l4 = getNode(4, l7, l8);
Node *l2 = getNode(2, l3, l4);
Node *l1 = getNode(1, l2, NULL);
return l1;
}
Node *print_forward(Node *head) {
Node *tail = head;
while (head != NULL) {
printf("%d ", head->v);
tail = head;
head=head->right;
}
printf("\n");
return tail;
}
Node *print_reverse(Node *tail) {
Node *head = tail;
while (tail != NULL) {
printf("%d ", tail->v);
head = tail;
tail=tail->left;
}
printf("\n");
return head;
}
void inorder(Node *root) {
if (root == NULL)
return;
inorder(root->left);
printf("%d ", root->v);
inorder(root->right);
}
int main() {
Node *root = createTree();
inorder(root);
printf("\n");
Node *head = tree_to_list(root);
Node *tail = print_forward(head);
print_reverse(tail);
}
<file_sep>/* Given two strings, find the common characters between the two
* strings. For ex, "Hello world" and "woowrd" have "word" as common
* characters.
*
* The solution below has O(n) complexity and is not case sensitive
*/
#include<stdio.h>
int main() {
char a[] = "Hello world";
char b[] = "woowrd";
int x[26] = {0};
int i;
int index;
for (i = 0; a[i] != '\0'; i++) {
index = a[i] - 'a';
if (index > 26) {
//capital char
index = a[i] - 'A';
}
x[index]++;
}
for (i = 0; b[i] != '\0'; i++) {
index = b[i] - 'a';
if (index > 26) {
//capital char
index = b[i] - 'A';
}
if (x[index] > 0)
x[index] = -1;
}
printf("Common characters in '%s' and '%s' are ", a, b);
for (i = 0; i < 26; i++) {
if (x[i] < 0)
printf("%c", 'a'+i);
}
printf("\n");
}
<file_sep>/* This code implements a non-recursive solution to convert a binary
* tree into a "circular (optional) doubly linked list" with the nodes
* in the list appearing as per the "inorder" traversal of the tree.
* Example:
* input tree:
* A
* / \
* B C
* / \ / \
* D E F G
*
* output list:
* head-> D <-> B <-> E <-> A <-> F <-> C <-> G
*
*/
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <string>
#include <vector>
using namespace std;
void Print(const std::vector<int> &v) {
for (auto &i : v) printf("%d ", i);
printf("\n");
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {
}
};
TreeNode *helper(TreeNode *curr, TreeNode *&prev, bool &foundHead) {
if (!curr) {
return NULL;
}
TreeNode *head = helper(curr->left, prev, foundHead);
if (!foundHead && curr->left == NULL) {
head = curr;
foundHead = true;
}
printf("prev:%d curr:%d\n", prev ? prev->val : -1, curr->val);
curr->left = prev;
if (prev) prev->right = curr;
prev = curr;
helper(curr->right, prev, foundHead);
return head;
}
TreeNode *TreeToList1(TreeNode *root) {
bool foundHead = false;
TreeNode *prev = NULL;
return helper(root, prev, foundHead);
}
TreeNode *TreeToList(TreeNode *root) {
stack<TreeNode *> stk;
TreeNode * curr = root;
TreeNode * prev = NULL;
bool foundHead = false;
TreeNode *head = NULL;
while (!stk.empty() || curr != NULL) {
if (curr) {
stk.push(curr);
curr = curr->left;
} else {
curr = stk.top();
stk.pop();
printf("%d\n", curr->val);
curr->left = prev;
if (prev) prev->right = curr;
if (!foundHead) {
foundHead = true;
head = curr;
}
prev = curr;
curr = curr->right;
}
}
return head;
}
TreeNode** TreeToListRecursive(TreeNode *root) {
TreeNode **ret = (TreeNode*)malloc(2*sizeof(TreeNode));
ret[0] = ret[1] = NULL;
if (root->left) {
TreeNode** left = TreeToListRecursive(root->left);
}
if (root->right) {
TreeNode** right = TreeToListRecursive(root->right);
}
}
int main(int argc, char **argv) {
TreeNode *root = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
TreeNode *n6 = new TreeNode(6);
TreeNode *n7 = new TreeNode(7);
TreeNode *n8 = new TreeNode(8);
TreeNode *n9 = new TreeNode(9);
root->left = n2;
root->right = n9;
n2->left = n3;
n2->right = n6;
n3->left = n4;
n3->right = n5;
n6->left=n7;
n6->right=n8;
TreeNode *head = TreeToList1(root);
// forward
printf("forward: ");
TreeNode *tail = head;
while (head) {
printf("%d ", head->val);
tail = head;
head = head->right;
}
printf("\n");
// backward
printf("backward: ");
while (tail) {
printf("%d ", tail->val);
tail = tail->left;
}
printf("\n");
return 0;
}
|
ddcb98c71fb20a526889b86e4d0cd18c8154b528
|
[
"C",
"C++"
] | 3
|
C++
|
ssahukar/coding_exercises
|
4356a29a6097617d9f8879029e5ad0d650ca8579
|
7666507b26158939fad780caf0cc0f5d26081e60
|
refs/heads/master
|
<file_sep>package com.lorne.sds.server.service.impl;
import com.lorne.sds.server.service.EurekaRegistrationService;
import com.lorne.sds.server.service.RedisService;
import com.lorne.sds.server.service.SocketEventService;
import com.lorne.sds.server.service.SocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* create by lorne on 2017/10/10
*/
@Service
public class SocketServiceImpl implements SocketService {
@Autowired
private EurekaRegistrationService eurekaRegistrationService;
@Autowired
private RedisService redisService;
@Autowired
private SocketEventService socketEventService;
@Override
public void create(String uniqueKey) {
String modelName = eurekaRegistrationService.getIpPort();
redisService.add(modelName,uniqueKey);
}
@Override
public void remove(String uniqueKey) {
String modelName = eurekaRegistrationService.getIpPort();
redisService.remove(modelName,uniqueKey);
}
@Override
public SocketEventService getSocketEventService() {
return socketEventService;
}
}
<file_sep>package com.lorne.sds.server.controller;
import com.lorne.core.framework.exception.ServiceException;
import com.lorne.sds.server.service.SocketService;
import com.lorne.sds.server.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
/**
* create by lorne on 2017/10/10
*/
@RestController
@RequestMapping("/delivery")
public class DeliveryController {
@Autowired
private SocketService socketService;
@Autowired
private RedisService redisService;
@RequestMapping("/index")
public Set<String> index(@RequestParam(name = "modelName") String modelName) throws ServiceException {
return redisService.all(modelName);
}
@RequestMapping("/send")
public boolean send(@RequestParam(name = "modelName") String modelName,
@RequestParam(name = "uniqueKey") String uniqueKey,
@RequestParam(name = "cmd") String cmd) throws ServiceException {
return socketService.send(modelName,uniqueKey,cmd);
}
}
<file_sep>package com.lorne.sds.server.service.impl;
import com.lorne.sds.server.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* create by lorne on 2017/10/13
*/
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate<String,String> redisTemplate;
private final static String prefix = "sds_";
@Override
public Set<String> all(String key) {
String mkey = prefix+key;
return redisTemplate.opsForSet().members(mkey);
}
@Override
public void removeAll(String key) {
String mkey = prefix+key;
redisTemplate.delete(mkey);
}
@Override
public void remove(String key, String uniqueKey) {
String mkey = prefix+key;
redisTemplate.opsForSet().remove(mkey,uniqueKey);
}
}
<file_sep># Socket Delivery Server
该框架是提供TCP Socket长连接的高可用方案。核心方案参考 。框架采用的核心技术框架:netty springcloud redis eureka
框架主要是为了提供一个可以负载大量socket tcp长连接的通讯服务。分为两部分delivery分发负载模块、socketServer通讯模块。
模块delivery依赖redis共享数据,提供双服务提高高可用性能;socketServer基于eureka负载可提供无上限的拓展支持,提供海量socket长连接请求业务。
## SDS的架构图:

## 目录介绍
delivery 分发服务库
socket socket通讯服务库
demo 演示案例
框架将delivery与socketServer均以第三方库的方式做的封装。在使用时只需要依赖他们就可以。
````
//分发服务maven
<dependency>
<groupId>com.github.1991wangliang</groupId>
<artifactId>lorne_sds_delivery</artifactId>
<version>1.0.0</version>
</dependency>
//socket服务maven
<dependency>
<groupId>com.github.1991wangliang</groupId>
<artifactId>lorne_sds_socket</artifactId>
<version>1.0.0</version>
</dependency>
````
## demo说明
详细请下载demo文件夹下的代码
主要业务实现
socket-demo 主要实现`SocketEventService`接口
````
@Override
public void onReadListener(ChannelHandlerContext ctx, String uniqueKey, Object msg) {
//读取数据事件
System.out.println(msg);
}
@Override
public void onConnectionListener(ChannelHandlerContext ctx, String uniqueKey) {
//连接服务事件
System.out.println(uniqueKey);
}
@Override
public void onDisConnectionListener(ChannelHandlerContext ctx, String uniqueKey) {
//断开连接事件
}
@Override
public void onHeartNoWriteDataListener(ChannelHandlerContext ctx, String uniqueKey) {
//心跳写入超时监听
}
@Override
public void onHeartNoReadDataListener(ChannelHandlerContext ctx, String uniqueKey) {
//心跳读取超时监听
}
@Override
public boolean hasOpenHeartCheck() {
//是否开启心跳检查
return true;
}
````
delivery-demo 主要实现`DeliveryServerSendEventService`接口
````
@Service
public class DeliveryServerSendEventServiceImpl implements DeliveryServerSendEventService {
@Autowired
private DeliveryServerService deliveryServerService;
@Override
public void onDeliveryListener(ChannelHandlerContext ctx, Object msg) {
//均为演示demo 实际业务还需要自己处理
//todo msg 业务消息处理
//通过SDS获取有效的Socket服务
Server server = deliveryServerService.getOkServer();
//发送分配的负载均衡信息给客户端
SocketUtils.send(ctx.channel(),server.toString().getBytes());
}
}
````
## 启动说明
框架依赖eureka和redis,在启动项目之前要确保这两个服务已开启。
然后在运行两个demo。
demo配置请参看`application.properties`的参数说明
|
1e8bcd48d8967f1106e6511d0d847a6b9305d1b2
|
[
"Markdown",
"Java"
] | 4
|
Java
|
marswon/sds
|
f76c8ad30025965f4f051688082a35d5e734ba69
|
70373843de2d80f748b095f041dd45147cf5012c
|
refs/heads/main
|
<file_sep><html>
<head>
<meta charset="UTF-8" />
<title>Genesis Network | Minigames</title>
<link rel="icon" type="image/png" href="./images/genesislogo.png" sizes="32x32" />
<link href="style/bootstrap.css" rel="stylesheet" />
<link href="style/main.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="description" content="Website of Genesis Network" />
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400" rel="stylesheet">
<link rel="stylesheet" href="icon/css/fontello.css">
<link rel="stylesheet" href="style/main-minigames.css">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<div class="container-menu">
<div class="redes-close">
<label class="icon-youtube-play"></label>
<label class="icon-tumblr-square"></label>
<label class="icon-twitter"></label>
<label class="icon-github-square"></label>
<label class="icon-facebook-square"></label>
<label class="icon-instagrem"></label>
<label class="icon-google-plus-square"></label>
<label class="icon-pinterest-square"></label>
<font class="close">X</font>
</div>
<body>
<div class="container-fluid">
<div class="header">
<nav class="navbar">
<div class="container-fluid">
<ul class="nav navbar-nav">
</div>
</div>
</div> <div class="container-menu">
<ul>
<font class="close">X</font>
<li><a href="register.html"><i class="fa fa-user-plus"></i> Register</a></li>
<li><a href="login.html"><i class="fa fa-user"></i> Login</a></li>
<li><a href="index.html"><i class="fa fa-home"></i> Home</a></li>
<li><a href="https://genesish.cf/discord" target="_blank"><i class="fa fa-users"></i> Community</a></li>
<li><a href="downloads.html"><i class="fa fa-download"></i> Downloads</a></li>
<li><a href="apply.html"><i class="fa fa-code"></i> Appys</a></li>
<li><a href="https://genesishcf.tebex.io/" target="_blank"><i class="fa fa-shopping-cart"></i> Store</a></li>
<li><a href="staff.html"><i class="fa fa-address-card"></i> Staff</a></li>
</ul>
</div>
</ul>
</div>
</nav>
</div>
<div class="row">
<header>
<div class="container-header">
<div class="logo-title">
<img src="images/genesislogo.png" alt="">
<h4>Genesis Network | Minigames </h4>
<label class="icon-menu"></label>
</div>
</div>
</header>
<div class="container-portada">
<div class="capa-gradient"></div>
<div class="container-details">
<div class="details">
<h1> ¿Como jugar BedWars?<h1>
<p>BedWars en Minecraft PC. Después de ver algunos videos divertidos hechos por tu youtuber favorito, finalmente has decidido comprar e instalar Minecraft, el popular título sandbox de Mojang, en tu Pc. Has oído hablar de un modo llamado Bed Wars que te permite jugar junto a otros usuarios. También has visto algunos videos y te ha parecido especialmente divertido, sin embargo, no has encontrado de ninguna manera la opción para poder iniciar un juego de este tipo.</p>
<button>Ver mas detalles</button>
</div>
</div>
</div>
<main>
<article>
<h1>WEB</h1>
<hr>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus quam quibusdam nihil similique et voluptates accusamus debitis quia facilis repellendus?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex, unde alias architecto cupiditate, facilis nisi, incidunt fugiat soluta rerum voluptate, mollitia natus praesentium sunt repellat quidem? Consequatur, nihil. Dolore fuga officiis, similique animi, asperiores quia aspernatur eius. Provident, ipsam, dolores.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate, voluptate dolorum! Eius optio, tempore temporibus, totam qui illum nihil. Earum, rerum quae magni aliquid optio repellat, rem assumenda eius accusantium facilis nam accusamus aperiam at dolorum iure nihil dicta aut modi doloribus excepturi cumque odio! Molestias at dolor ab consectetur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci architecto excepturi enim reprehenderit expedita, mollitia animi autem sed reiciendis laudantium culpa natus ea blanditiis ullam molestias itaque laboriosam sunt quidem.</p>
</article>
</main>
</body>
</div>
</div>
<div class="row block-bg">
<div class="col-md-4 socialmedia">
<h4>VOTE FOR OUR SERVER</h4>
<ul style="list-style: none;">
<li><a href="https://es.namemc.com/server/genesish.cf" target="_blank"><img class="namemc-img" src="https://image.winudf.com/v2/image1/Y29tLm5hbWVtY19pY29uXzE1NjAxNTY1NTBfMDQx/icon.png?w=170&fakeurl=1"></a></li>
</ul>
</div>
<div class="col-md-4 socialmedia oneline">
<h4>Social networks</h4><div>
<ul style="list-style: none;">
<li><a href="https://genesish.cf/discord" target="_blank"><i class="fab fa-discord fa-2x social"aria-hidden="true"></i></a></li>
<li><a href="https://twitter.com/Genesishcfnet" target="_blank"><img class="res-img-sm" src=""><i class="fab fa-twitter fa-2x social" aria-hidden="true"></i></a></li>
<li><a href="https://www.youtube.com/c/iamboy" target="_blank"><i class="fab fa-youtube fa-2x social" aria-hidden="true"></i></a></li>
</ul>
</div>
</div>
<div class="col-md-4 socialmedia">
<h4>Need help?</h4>
<p class="TextTicket">
Open a ticket in our discord <a href="https://genesish.cf/discord" target="_blank"><i class="fab fa-discord fa-1x"aria-hidden="true"></i></a>
</p>
</div>
<div class="col-md-12 socialmedia">
<hr class="bartopindev" />
<p>
<br>Genesis Network © 2020 | Made by <a href="https://twitter.com/Genesishcfnet" target="_blank">Genesis Development Team.</a>
</p>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/js/all.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="js/minigames.js"></script>
</body>
</html><file_sep># Proyecto escolar Genesis
Pagina Pre-Official de Proyecto Genesis
<file_sep>const variables = {
title: "Genesis Network | Status",
favicon: "../images/genesislogo.png",
description: "Status of Genesis Network",
principalText: "Genesis Network",
playerCounterText: "%pl-online% players online",
serverIp: "genesish.cf",
copiedText: "IP has been copied",
style: {
backgroundColor: "#000000db",
backgroundImageName: "../images/genesishcfbg.jpg",
logoImageName: "../images/genesislogo.png",
logoAnimationFloat: true
}
}
|
6313908fd8c1eba79c2e2efcb72dc296b219d4bc
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3
|
HTML
|
sxdico/genesisnetwork
|
3e8a0e5f57558faed7448973eff8e646397968de
|
00f66ea8dbabb4c137b99eaa1687203bb616e5c7
|
refs/heads/master
|
<file_sep>## Unreleased (2020-06-05)
#### :memo: Documentation
* [#101](https://github.com/holistics/dbml/pull/101) Update homepage ([@phuongduyphan](https://github.com/phuongduyphan))
* [#93](https://github.com/holistics/dbml/pull/93) Add golang parser to community contributes ([@duythinht](https://github.com/duythinht))
* [#92](https://github.com/holistics/dbml/pull/92) Add PyDBML to dbml homepage ([@phuongduyphan](https://github.com/phuongduyphan))
* [#91](https://github.com/holistics/dbml/pull/91) Add FloorPlan to community contributions ([@julioz](https://github.com/julioz))
* [#89](https://github.com/holistics/dbml/pull/89) Add PyDBML to Comunity Contributions section of README ([@Vanderhoof](https://github.com/Vanderhoof))
* [#86](https://github.com/holistics/dbml/pull/86) fixes contributing setup section : yarn must be present to run 'lerna bootstrap' ([@sporniket](https://github.com/sporniket))
#### :rocket: New Feature
* `dbml-core`
* [#98](https://github.com/holistics/dbml/pull/98) Add mssql parser ([@phanbaominh](https://github.com/phanbaominh))
* [#99](https://github.com/holistics/dbml/pull/99) Support exporting table's note ([@khanhthuymainguyen](https://github.com/khanhthuymainguyen))
* [#95](https://github.com/holistics/dbml/pull/95) Support field-level charset in MySQL parser ([@Orclyx](https://github.com/Orclyx))
* [#90](https://github.com/holistics/dbml/pull/90) Support composite foreign keys ([@phanbaominh](https://github.com/phanbaominh))
#### Committers: 10
- <NAME> ([@sporniket](https://github.com/sporniket))
- Hamid ([@hamedsj](https://github.com/hamedsj))
- <NAME> ([@julioz](https://github.com/julioz))
- <NAME> ([@khanhthuymainguyen](https://github.com/khanhthuymainguyen))
- <NAME> ([@stepanic](https://github.com/stepanic))
- <NAME> ([@phanbaominh](https://github.com/phanbaominh))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
- <NAME> ([@duythinht](https://github.com/duythinht))
- [@Orclyx](https://github.com/Orclyx)
- [@Vanderhoof](https://github.com/Vanderhoof)
## v2.0.1 (2020-04-16)
#### :bug: Bug Fix
* `dbml-core`
* [#83](https://github.com/holistics/dbml/pull/83) Parse index note for DBML ([@phuongduyphan](https://github.com/phuongduyphan))
* [#80](https://github.com/holistics/dbml/pull/80) Schemarb/support single quote ([@khoahuynhf](https://github.com/khoahuynhf))
#### Committers: 2
- <NAME> ([@khoahuynhf](https://github.com/khoahuynhf))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v2.0.0-alpha.0 (2020-02-27)
#### :boom: Breaking Change
* `dbml-core`
* [#47](https://github.com/holistics/dbml/pull/47) Restructure and normalize models ([@phuongduyphan](https://github.com/phuongduyphan))
#### :rocket: New Feature
* `dbml-core`
* [#47](https://github.com/holistics/dbml/pull/47) Add Project, Note and multi-line string syntax ([@phuongduyphan](https://github.com/phuongduyphan))
#### :memo: Documentation
* [#69](https://github.com/holistics/dbml/pull/69) Fix typo in readme ([@bmitchinson](https://github.com/bmitchinson))
* [#47](https://github.com/holistics/dbml/pull/47) Add Project, Note and multi-line string syntax ([@phuongduyphan](https://github.com/phuongduyphan))
#### :bug: Bug Fix
* [#69](https://github.com/holistics/dbml/pull/69) Fix typo in readme ([@bmitchinson](https://github.com/bmitchinson))
#### Committers: 2
- <NAME> ([@bmitchinson](https://github.com/bmitchinson))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.3.1 (2020-01-22)
#### :bug: Bug Fix
* `dbml-core`
* [#65](https://github.com/holistics/dbml/pull/65) Fix parsing index comment ([@phuongduyphan](https://github.com/phuongduyphan))
* [#64](https://github.com/holistics/dbml/pull/64) Parse array type for dbml ([@phuongduyphan](https://github.com/phuongduyphan))
* [#57](https://github.com/holistics/dbml/pull/57) Fix DBML one-to-one relation exporting bug ([@dawitkk](https://github.com/dawitkk))
#### Committers: 2
- <NAME> ([@dawitkk](https://github.com/dawitkk))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.3.0 (2019-12-24)
#### :rocket: New Feature
* `dbml-core`
* [#54](https://github.com/holistics/dbml/pull/54) Feature: Referential actions for ActiveRecord Rails ([@phuongduyphan](https://github.com/phuongduyphan))
* [#29](https://github.com/holistics/dbml/pull/29) Feature: Referential actions ([@flemeur](https://github.com/flemeur))
#### :house_with_garden: Internal
* `dbml-core`
* [#43](https://github.com/holistics/dbml/pull/43) Indent JSON generated by JsonExporter ([@ilyakharlamov](https://github.com/ilyakharlamov))
#### Committers: 3
- <NAME> ([@flemeur](https://github.com/flemeur))
- <NAME> ([@ilyakharlamov](https://github.com/ilyakharlamov))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.2.1 (2019-10-30)
#### :bug: Bug Fix
* `dbml-core`
* [#41](https://github.com/holistics/dbml/pull/41) Remove defaut header color ([@phuongduyphan](https://github.com/phuongduyphan))
#### Committers: 1
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.2.0 (2019-10-24)
#### :rocket: New Feature
* `dbml-core`
* [#39](https://github.com/holistics/dbml/pull/39) Support import/export comment syntax for dbml, mysql and postgres ([@phuongduyphan](https://github.com/phuongduyphan))
* [#35](https://github.com/holistics/dbml/pull/35) Add composite primary key ([@duynvu](https://github.com/duynvu))
#### Committers: 2
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
- <NAME> ([@duynvu](https://github.com/duynvu))
## v1.1.3 (2019-10-10)
#### :rocket: New Feature
* `dbml-cli`, `dbml-core`
* [#32](https://github.com/holistics/dbml/pull/32) Add SQL Server export ([@duynvu](https://github.com/duynvu))
#### Committers: 1
- <NAME> ([@duynvu](https://github.com/duynvu))
## v1.1.2 (2019-09-04)
#### :bug: Bug Fix
* `dbml-core`
* [#27](https://github.com/holistics/dbml/pull/27) Fix relationship description ([@duynvu](https://github.com/duynvu))
#### :rocket: New Feature
* `dbml-core`
* [#28](https://github.com/holistics/dbml/pull/28) Add supporting TableGroup syntax ([@phuongduyphan](https://github.com/phuongduyphan))
#### Committers: 3
- <NAME> ([@khoahuynhf](https://github.com/khoahuynhf))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
- <NAME> ([@duynvu](https://github.com/duynvu))
## v1.1.1 (2019-09-03)
#### :bug: Bug Fix
* `dbml-cli`, `dbml-core`
* [#26](https://github.com/holistics/dbml/pull/26) Output Syntax Error location to console ([@phuongduyphan](https://github.com/phuongduyphan))
#### Committers: 1
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.1.0 (2019-09-02)
#### :memo: Documentation
* `dbml-homepage`
* [#23](https://github.com/holistics/dbml/pull/23) dbml homepage/change docs ([@phuongduyphan](https://github.com/phuongduyphan))
* [#19](https://github.com/holistics/dbml/pull/19) docs: add cli and tooling docs ([@phuongduyphan](https://github.com/phuongduyphan))
#### :boom: Breaking Change
* `dbml-cli`
* [#24](https://github.com/holistics/dbml/pull/24) Change CLI interface ([@phuongduyphan](https://github.com/phuongduyphan))
#### :house_with_garden: Internal
* `dbml-homepage`
* [#21](https://github.com/holistics/dbml/pull/21) chore: move dbml-homepage outside, add readme ([@phuongduyphan](https://github.com/phuongduyphan))
#### Committers: 1
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))
## v1.0.0 (2019-08-19)
#### :boom: Breaking Change
* `dbml-cli`
* [#16](https://github.com/holistics/dbml/pull/16) feat: add @dbml/cli package ([@phuongduyphan](https://github.com/phuongduyphan))
* `dbml-core`
* [#15](https://github.com/holistics/dbml/pull/15) feat: add @dbml/core package ([@phuongduyphan](https://github.com/phuongduyphan))
#### :house_with_garden: Internal
* `dbml-homepage`
* [#18](https://github.com/holistics/dbml/pull/18) docs: add @dbml/homepage package ([@phuongduyphan](https://github.com/phuongduyphan))
#### Committers: 2
- <NAME> ([@khoa0319](https://github.com/khoa0319))
- <NAME> ([@phuongduyphan](https://github.com/phuongduyphan))<file_sep>import _ from 'lodash';
import { shouldPrintSchema } from './utils';
class MySQLExporter {
static getFieldLines (tableId, model) {
const table = model.tables[tableId];
const lines = table.fieldIds.map((fieldId) => {
const field = model.fields[fieldId];
let line = '';
if (field.enumId) {
const _enum = model.enums[field.enumId];
line = `\`${field.name}\` ENUM (`;
const enumValues = _enum.valueIds.map(valueId => {
return `'${model.enumValues[valueId].name}'`;
});
line += `${enumValues.join(', ')})`;
} else {
line = `\`${field.name}\` ${field.type.type_name !== 'varchar' ? field.type.type_name : 'varchar(255)'}`;
}
if (field.unique) {
line += ' UNIQUE';
}
if (field.pk) {
line += ' PRIMARY KEY';
}
if (field.not_null) {
line += ' NOT NULL';
}
if (field.increment) {
line += ' AUTO_INCREMENT';
}
if (field.dbdefault) {
if (field.dbdefault.type === 'expression') {
line += ` DEFAULT (${field.dbdefault.value})`;
} else if (field.dbdefault.type === 'string') {
line += ` DEFAULT "${field.dbdefault.value}"`;
} else {
line += ` DEFAULT ${field.dbdefault.value}`;
}
}
if (field.note) {
line += ` COMMENT '${field.note}'`;
}
return line;
});
return lines;
}
static getCompositePKs (tableId, model) {
const table = model.tables[tableId];
const compositePkIds = table.indexIds ? table.indexIds.filter(indexId => model.indexes[indexId].pk) : [];
const lines = compositePkIds.map((keyId) => {
const key = model.indexes[keyId];
let line = 'PRIMARY KEY';
const columnArr = [];
key.columnIds.forEach((columnId) => {
const column = model.indexColumns[columnId];
let columnStr = '';
if (column.type === 'expression') {
columnStr = `(${column.value})`;
} else {
columnStr = `\`${column.value}\``;
}
columnArr.push(columnStr);
});
line += ` (${columnArr.join(', ')})`;
return line;
});
return lines;
}
static getTableContentArr (tableIds, model) {
const tableContentArr = tableIds.map((tableId) => {
const fieldContents = MySQLExporter.getFieldLines(tableId, model);
const compositePKs = MySQLExporter.getCompositePKs(tableId, model);
return {
tableId,
fieldContents,
compositePKs,
};
});
return tableContentArr;
}
static exportTables (tableIds, model) {
const tableContentArr = MySQLExporter.getTableContentArr(tableIds, model);
const tableStrs = tableContentArr.map((tableContent) => {
const content = [...tableContent.fieldContents, ...tableContent.compositePKs];
const table = model.tables[tableContent.tableId];
const schema = model.schemas[table.schemaId];
const tableStr = `CREATE TABLE ${shouldPrintSchema(schema, model)
? `\`${schema.name}\`.` : ''}\`${table.name}\` (\n${
content.map(line => ` ${line}`).join(',\n')}\n);\n`;
return tableStr;
});
return tableStrs.length ? tableStrs.join('\n') : '';
}
static buildFieldName (fieldIds, model) {
const fieldNames = fieldIds.map(fieldId => `\`${model.fields[fieldId].name}\``).join(', ');
return `(${fieldNames})`;
}
static exportRefs (refIds, model) {
const strArr = refIds.map((refId) => {
const ref = model.refs[refId];
const refEndpointIndex = ref.endpointIds.findIndex(endpointId => model.endpoints[endpointId].relation === '1');
const foreignEndpointId = ref.endpointIds[1 - refEndpointIndex];
const refEndpointId = ref.endpointIds[refEndpointIndex];
const foreignEndpoint = model.endpoints[foreignEndpointId];
const refEndpoint = model.endpoints[refEndpointId];
const refEndpointField = model.fields[refEndpoint.fieldIds[0]];
const refEndpointTable = model.tables[refEndpointField.tableId];
const refEndpointSchema = model.schemas[refEndpointTable.schemaId];
const refEndpointFieldName = this.buildFieldName(refEndpoint.fieldIds, model, 'mysql');
const foreignEndpointField = model.fields[foreignEndpoint.fieldIds[0]];
const foreignEndpointTable = model.tables[foreignEndpointField.tableId];
const foreignEndpointSchema = model.schemas[foreignEndpointTable.schemaId];
const foreignEndpointFieldName = this.buildFieldName(foreignEndpoint.fieldIds, model, 'mysql');
let line = `ALTER TABLE ${shouldPrintSchema(foreignEndpointSchema, model)
? `\`${foreignEndpointSchema.name}\`.` : ''}\`${foreignEndpointTable.name}\` ADD `;
if (ref.name) {
line += `CONSTRAINT \`${ref.name}\` `;
}
line += `FOREIGN KEY ${foreignEndpointFieldName} REFERENCES ${shouldPrintSchema(refEndpointSchema, model)
? `\`${refEndpointSchema.name}\`.` : ''}\`${refEndpointTable.name}\` ${refEndpointFieldName}`;
if (ref.onDelete) {
line += ` ON DELETE ${ref.onDelete.toUpperCase()}`;
}
if (ref.onUpdate) {
line += ` ON UPDATE ${ref.onUpdate.toUpperCase()}`;
}
line += ';\n';
return line;
});
return strArr.length ? strArr.join('\n') : '';
}
static exportIndexes (indexIds, model) {
// exclude composite pk index
const indexArr = indexIds.filter((indexId) => !model.indexes[indexId].pk).map((indexId, i) => {
const index = model.indexes[indexId];
const table = model.tables[index.tableId];
const schema = model.schemas[table.schemaId];
let line = 'CREATE';
if (index.unique) {
line += ' UNIQUE';
}
const indexName = index.name ? `\`${index.name}\`` : `\`${shouldPrintSchema(schema, model)
? `\`${schema.name}\`.` : ''}${table.name}_index_${i}\``;
line += ` INDEX ${indexName} ON ${shouldPrintSchema(schema, model)
? `\`${schema.name}\`.` : ''}\`${table.name}\``;
const columnArr = [];
index.columnIds.forEach((columnId) => {
const column = model.indexColumns[columnId];
let columnStr = '';
if (column.type === 'expression') {
columnStr = `(${column.value})`;
} else {
columnStr = `\`${column.value}\``;
}
columnArr.push(columnStr);
});
line += ` (${columnArr.join(', ')})`;
if (index.type) {
line += ` USING ${index.type.toUpperCase()}`;
}
line += ';\n';
return line;
});
return indexArr.length ? indexArr.join('\n') : '';
}
static exportComments (comments, model) {
const commentArr = comments.map((comment) => {
let line = '';
if (comment.type === 'table') {
const table = model.tables[comment.tableId];
line += `ALTER TABLE \`${table.name}\` COMMENT = "${table.note.replace(/"/g, "'")}"`;
}
line += ';\n';
return line;
});
return commentArr.length ? commentArr.join('\n') : '';
}
static export (model) {
let res = '';
let hasBlockAbove = false;
const database = model.database['1'];
const indexIds = [];
const comments = [];
database.schemaIds.forEach((schemaId) => {
const schema = model.schemas[schemaId];
const { tableIds, refIds } = schema;
if (shouldPrintSchema(schema, model)) {
if (hasBlockAbove) res += '\n';
res += `CREATE DATABASE \`${schema.name}\`;\n`;
hasBlockAbove = true;
}
if (!_.isEmpty(tableIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportTables(tableIds, model);
hasBlockAbove = true;
}
if (!_.isEmpty(refIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportRefs(refIds, model);
hasBlockAbove = true;
}
indexIds.push(...(_.flatten(tableIds.map((tableId) => model.tables[tableId].indexIds))));
comments.push(...(_.flatten(tableIds.map((tableId) => {
const { note } = model.tables[tableId];
return note ? [{type: 'table', tableId}] : [];
}))));
});
if (!_.isEmpty(indexIds)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportIndexes(indexIds, model);
hasBlockAbove = true;
}
if (!_.isEmpty(comments)) {
if (hasBlockAbove) res += '\n';
res += MySQLExporter.exportComments(comments, model);
hasBlockAbove = true;
}
return res;
}
}
export default MySQLExporter;
|
f632213a718bd553693d7e9d6c12162f79507dfc
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
akash-coded/dbml
|
ead25b9861be5ed5ce23e603470c0359eb48bf8c
|
da1c42f204673ee90b78c5251f7b15dfc62201e5
|
refs/heads/main
|
<repo_name>RKXSuS/XNRYZ-BOT<file_sep>/README.md
##CARA INSTALL MELALUI GIT
> pkg install git
> gitclone https://github.com/RKXSuS/XNRYZ-BOT
> cd XNRYZ-BOT
> bash install.sh
> npm start
> scan qr
##CARA INSTALL
> termux-setup-storage [Y]
> cd /sdcard
> cd -r XNRYZ-BOT /$HOME
> cd XNRYZ-BOT
> bash install.sh
> npm start
> Now scan the QR
<file_sep>/lib/donasi.js
const donasi = () => {
return `
◪ *DONASI*
│
├─ ❏ *GOPAY*
├─ ❏ 082287486762
├─ ❏ *PULSA*
├─ ❏ 082287486762
├─ ❏ DONASI KAK BUAT UPDATE BOT NYA`
}
exports.donasi = donasi
|
19c13ed0071a0103b9ad08612ceef4b6da99dbb8
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
RKXSuS/XNRYZ-BOT
|
ee324d3766b8a3ea5cf3bc4f93196e315b63ad8b
|
e1d9db18ae5d5806865596112b4f9407bd2696d8
|
refs/heads/master
|
<file_sep>var twit = require('twit');
var config = require('./config');
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport. Using gmail can help us out in many things.
var botEmail = '...'; //user name part of email, ie., john for <<EMAIL>> | this must ba a gmail or mailerArgs will be reconstructed
var botPass = '...'; // password for <<EMAIL>>
var toMail = 'user_+name, <EMAIL>'; // to mail address, eg: 'Abraham bran, <EMAIL>'
var mailerArgs = 'smtps://'+botEmail+'%40gmail.com:'+botPass+'@smtp.gmail.com';
var transporter = nodemailer.createTransport(mailerArgs);
var Twitter = twit(config);
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"Email Bot (Twigo)" <'+<EMAIL>+'<EMAIL>>', // sender address
to: toMail // list of receivers
};
//query params to query the tweets. Change the query string of your need
var qparams = {
q: '#emberjs, #emberJs, #emberJS, #EmberJs, #Emberjs, #EMBERJS',
result_type: 'recent',
lang: 'en'
};
// function to retweet tweets that matches my query string..
var retweet = function() {
Twitter.get('search/tweets', qparams, function(err, data) {
if (!err) {
var retweetId = data.statuses[0].id_str;
Twitter.post('statuses/retweet/:id', {
id: retweetId
}, function(err, response) {
if (response) {
console.log('Retweeted :)');
}
if (err) {
console.log('OOPS! Something went wrong while retweeting :( ');
// console.log(err);
// Email Errors
emailErrors(2, err);
}
})
} else {
console.log('[Retweeting] OOPS! Something went wrong while querying tweets :(');
// console.log(err);
// Email Errors
emailErrors(1, err);
}
});
}
//Favoriting a tweet
var favoriteTweet = function(){
// find the tweet
Twitter.get('search/tweets', qparams, function(err,data){
if (!err) {
// find tweets
var tweet = data.statuses;
var randomTweet = selectRandom(tweet); // pick a random tweet
if(typeof randomTweet != 'undefined'){
Twitter.post('favorites/create', {id: randomTweet.id_str}, function(err, response){
if(err){
console.log('OOPS! Something went wrong while Favoriting a tweet :(');
emailErrors(3, err);
}
else{
console.log('Favorited :)');
}
});
}
} else {
console.log('[Favoriting] OOPS! Something went wrong while querying tweets :(');
// console.log(err);
// Email Errors
emailErrors(1, err);
}
});
}
retweet();
setInterval(retweet, 3000000);
favoriteTweet();
setInterval(favoriteTweet, 3600000);
// function to retrun a random tweet from the tweet array
function selectRandom (arr) {
var index = Math.floor(Math.random()*arr.length);
return arr[index];
};
var emailErrors = function(type, err) {
if (type == 1) {
mailOptions.subject = 'Query: Failed';
} else if (type == 2) {
mailOptions.subject = 'Query: Passed | Retweet: Failed';
} else if (type == 3) {
mailOptions.subject = 'Query: Passed | Favorite: Failed';
}
var errorString = 'error msg: '+err.message+' | error code: '+err.code;
mailOptions.text = errorString;
mailOptions.html = '<code style="color: red;">'+errorString+'</code>';
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Error log is mailed to ' +toMail+ ' - Response : ' + info.response);
});
}
<file_sep># twigo
My first, my own twitter bot
- git clone git clone https://github.com/gokatz/twigo.git
- cd twigo
- npm install
- open config.js
- [Edit the file to add the twitter API keys and secrets. Save file]
- [change the q string according to your need]
- node bot.js
Happy retweeting :)
|
a49f21fb966281440c3310dbbb360cc3e1facfe4
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
gokatz/twigo
|
aae0c27950e336569a8d012dfc6db30590d7a1fa
|
9a2966f6947e5e693a65ba2e304a9dc8b7b8a10d
|
refs/heads/master
|
<file_sep>const isEmpty = function(op) {
if (op === null || op === undefined || op === '' || op.length === 0) {
return true;
}
return false;
};
const padDigit = function(digit) {
if (digit < 10) {
return '0' + digit;
}
return digit;
};
const getTimestamp = function(date) {
return (
date.getFullYear() +
'-' +
padDigit(date.getMonth()) +
'-' +
padDigit(date.getDate()) +
' ' +
padDigit(date.getHours()) +
':' +
padDigit(date.getMinutes())
);
};
document.addEventListener('DOMContentLoaded', function() {
const model = {
id: 0,
userName: 'Akashdeep B',
userHandle: '@ab1992',
inputVal: '',
listOfTweets: [],
currentIndex: null
};
var inputElement = document.getElementById('id-tweet-ip');
var formElement = document.getElementById('id-tweet-form');
var tweetContainer = document.getElementById('id-list-of-tweets');
function changeModelInput(value) {
model.inputVal = value;
inputElement.value = value;
}
function editTweet(tweet) {
model.currentIndex = tweet.id;
changeModelInput(tweet.tweet);
}
function deleteTweet(id) {
var index;
if (model.listOfTweets.length === 1) {
index = 0;
} else {
index = model.listOfTweets.length - 1 - id;
}
if (!isEmpty(index)) {
model.listOfTweets.splice(index, 1);
showListOfTweets();
}
}
function prepareTweet(tweet) {
var parent = document.createElement('div');
parent.className = 'cls-tweet';
var userLine = document.createElement('div');
var userName = document.createElement('span');
userName.className = 'cls-tweet-user';
userName.innerHTML = tweet.user;
userLine.appendChild(userName);
var userHandle = document.createElement('span');
userHandle.className = 'cls-tweet-handle';
userHandle.innerHTML = tweet.handle;
userLine.appendChild(userHandle);
var userTimestamp = document.createElement('div');
userTimestamp.className = 'cls-tweet-timestamp';
userTimestamp.innerHTML = tweet.time;
var userTweet = document.createElement('p');
userTweet.className = 'cls-tweet-tweet';
userTweet.innerHTML = tweet.tweet;
var editButton = document.createElement('button');
editButton.type = 'button';
editButton.className = 'cls-primary-button cls-edit';
editButton.id = 'id-edit-' + tweet.id;
editButton.innerHTML = 'Edit';
editButton.addEventListener('click', function() {
editTweet(tweet);
});
var deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.className = 'cls-error-button cls-delete';
deleteButton.id = 'id-delete-' + tweet.id;
deleteButton.innerHTML = 'Delete';
deleteButton.addEventListener('click', function() {
deleteTweet(tweet.id);
});
parent.appendChild(userLine);
parent.appendChild(userTimestamp);
parent.appendChild(userTweet);
parent.appendChild(editButton);
parent.appendChild(deleteButton);
return parent;
}
function showListOfTweets() {
tweetContainer.innerHTML = '';
if (isEmpty(model.listOfTweets)) {
return;
}
model.listOfTweets.forEach(element => {
const tweet = prepareTweet(element);
tweetContainer.appendChild(tweet);
});
}
inputElement.addEventListener('input', function(event) {
model.inputVal = inputElement.value;
});
formElement.addEventListener('submit', function(event) {
event.preventDefault();
var errorElement = document.getElementById('id-error');
var error = false;
var msg = '';
if (isEmpty(model.inputVal)) {
error = true;
msg = 'Please write something to tweet';
} else if (model.inputVal.length > 160) {
error = true;
msg = 'Max characters allowed is 160';
}
if (error) {
errorElement.innerHTML = msg;
return;
} else {
errorElement.innerHTML = '';
}
if (isEmpty(model.currentIndex)) {
model.listOfTweets.unshift({
id: model.id++,
user: model.userName,
handle: model.userHandle,
tweet: model.inputVal,
time: getTimestamp(new Date())
});
} else {
var index;
if (model.listOfTweets.length === 1) {
index = 0;
} else {
index = model.listOfTweets.length - 1 - model.currentIndex;
}
model.listOfTweets[index] = {
id: model.currentIndex,
user: model.userName,
handle: model.userHandle,
tweet: model.inputVal,
time: model.listOfTweets[index].time
};
model.currentIndex = null;
}
changeModelInput('');
showListOfTweets();
});
});
|
3c24254c030c7a7e6de2ab3ae57a7cbe718c8a00
|
[
"JavaScript"
] | 1
|
JavaScript
|
iamruku/ola_test
|
156951943e840ee45e747229302ec4de8afbc584
|
dcf518442e0fc77de598e35870e19b0423e6b7b4
|
refs/heads/master
|
<file_sep>
/*
* GET home page.
*/
var url = require("url");
var i18n = require("i18n");
exports.index = function(req, res){
//Getting privious URL
var refererHeader = req.header('Referer') != undefined ? req.header('Referer') : '/' ;
var refererURL = url.parse(refererHeader, true);
//console.log('Referer Header:'+refererHeader+", RefererURL Query:"+refererURL.query+", Path :"+refererURL.path);
var innerHTML = "<a href='/'>Home</a>";
res.render('index', { page: 'index', title: 'NodeJs with Jade viewer', name: 'NodeJS-JADE', referer: refererURL.path, html: innerHTML });
};
<file_sep>var mongodb = require('mongodb');
if (typeof pTalk == "undefined")
pTalk = {};
pTalk.utils = {
isAlphaNumericWithSpace: function(evt) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
var keyCode = evt.keyCode == 0 ? evt.charCode : evt.keyCode;
return ((keyCode == 32) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(evt.keyCode) != -1 && evt.charCode != evt.keyCode));
},
isZipCode: function(evt) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
var keyCode = evt.keyCode == 0 ? evt.charCode : evt.keyCode;
return ((keyCode == 45) || (keyCode == 32) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(evt.keyCode) != -1 && evt.charCode != evt.keyCode));
},
print: function(node, hideFn, showFn) {
//return function()
{
// Hide
hideFn && hideFn();
var w = window.open();
w.document.write(node.innerHTML);
// Show
showFn && showFn();
w.print();
//w.close();
}
},
isNumberKey: function(evt) {
if (!evt)
evt = window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
},
isDecimalKey: function(evt) {
if (!evt)
evt = window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
var srcElement = evt.srcElement || evt.target;
if (charCode == 46 && srcElement.value.split('.').length > 1)
return false;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
},
// zip code TODO: Revisit
isAlphaNumeric: function(evt) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
specialKeys.push(46); //DOT
specialKeys.push(95); //UNDER SCORE
var keyCode = evt.keyCode == 0 ? evt.charCode : evt.keyCode;
return ((keyCode >= 48 && keyCode <= 57) || (keyCode == 46) || (keyCode == 95) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(evt.keyCode) != -1 && evt.charCode != evt.keyCode));
},
scrollDiv: function(divid) {
//alert(divid);
// when the DOM is ready...
// Move the window's scrollTop to the offset position of #now
try {
$(window).scrollTop($('#' + divid).offset().top);
} catch (e) {
// TODO: handle exception
//alert(e);
}
}
};
pTalk.mongo = {
};
//Poly Fill for String.trim()
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
<file_sep>#Here am going to explain NodeJS with JADE viewer application configuration, deployment & testing API[s]
# npm & NodeJS installation guide.
If you found the old node package installed, run this command to completely remove it
> sudo apt-get remove --purge node
Install Node.js with Ubuntu Package Manager
To install Node.js, open a terminal and type the following command:
> sudo apt-get install nodejs
Then install the node package manager, npm:
> sudo apt-get install npm
Now we should have both the node and npm commands working
> node -v
v0.10.25
> npm -v
1.3.10
# We can install node module[s] in two ways.
1. Permanent Way
> npm install body-parser -- save
2. Temporary Way
> npm install body-parser
# To deploy your application
1. If application not exists. Download the application.
2. Go to the folder where app.js exists through terminal, start the npm server by uising below command.
> npm start
# Testing your application by using HTTP-Client like Chrome / Mozila / IE.
Here is the some URL[s],
1. Home Page GET http://127.0.0.1:3000/
<file_sep>// BASE SETUP
// ==============================================
var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
var http = require('http');
var i18n = require("i18n");
var url = require("url");
var mongodb = require('mongodb');
var assert = require('assert');
var socket = require('socket.io');
var app = express();
var port = process.env.PORT || 3000;
var io = socket.listen(server);
var routes = require('./routes');
// configure stuff here
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/node_modules'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'uwotm8'
}));
var env = app.settings.env;
// Configuration
if(env == 'production'){
app.use(errorHandler());
}else{
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
}
// ROUTES
// ==============================================
// root page
app.get('/', routes.index);
// we'll create our routes here
// START THE SERVER
// ==============================================
var server = app.listen(port, function() {
console.log("Express server listening on port %d in %s mode", port, app.settings.env);
});
|
c54120f37a4210c196570f366311ef4736863e59
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
govardhanraoganji/NodeJS-with-JADE-viewer
|
1f36ac7d6a5bdc684e2ae529c9915ddd35133bed
|
0d9925370bc40d4cc5c03a73ee6435dd4b9968e0
|
refs/heads/main
|
<repo_name>cebilon123/monolith-boilerplate<file_sep>/README.md
# monolith-boilerplate
Memory CQRS, Exception handling, DDD project boilerplate
<file_sep>/Api/Api.Infrastructure/Initialize/CQRSExtensions.cs
using System;
using Api.Application.Handlers;
using Api.Infrastructure.Cqrs;
using Microsoft.Extensions.DependencyInjection;
namespace Api.Infrastructure.Initialize
{
public static class CqrsExtensions
{
public static IServiceCollection AddCommandHandlers(this IServiceCollection services)
{
services.Scan(s => s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
.AddClasses(c => c.AssignableTo(typeof(ICommandHandler<>)))
.AsImplementedInterfaces()
.WithTransientLifetime());
return services;
}
public static IServiceCollection AddQueryHandlers(this IServiceCollection services)
{
services.Scan(s => s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
.AddClasses(c => c.AssignableTo(typeof(IQueryHandler<,>)))
.AsImplementedInterfaces()
.WithTransientLifetime());
return services;
}
public static IServiceCollection AddCommandDispatcher(this IServiceCollection services)
{
services.AddSingleton<ICommandDispatcher, CommandDispatcher>();
return services;
}
public static IServiceCollection AddQueryDispatcher(this IServiceCollection services)
{
services.AddSingleton<IQueryDispatcher, QueryDispatcher>();
return services;
}
}
}<file_sep>/Api/Api.Infrastructure/Errors/ExceptionMiddleware.cs
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Api.Infrastructure.Errors
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IExceptionToResponseMapper _exceptionToResponseMapper;
public ExceptionMiddleware(RequestDelegate next, IExceptionToResponseMapper exceptionToResponseMapper)
{
_next = next;
_exceptionToResponseMapper = exceptionToResponseMapper;
}
public async Task InvokeAsync(HttpContext ctx)
{
try
{
await _next.Invoke(ctx);
}
catch (Exception e)
{
var response = ctx.Response;
response.ContentType = "application/json";
var result = JsonSerializer.Serialize(_exceptionToResponseMapper.GetErrorBasedOnException(e));
await response.WriteAsync(result);
}
}
}
}<file_sep>/Api/Api.Core/Domain/User.cs
using System;
using Api.Domain.Helpers;
namespace Api.Domain.Domain
{
public class User : IAggregateRoot
{
public Guid Id { get; }
public string Email { get; }
public string Password { get; }
public User(Guid id, string email, string password)
{
Id = id;
Email = email;
Password = <PASSWORD>;
}
public static User Create(string email, string password)
=> Create(Guid.NewGuid(), email, password);
public static User Create(Guid id, string email, string password)
=> new User(id, email, password);
}
}<file_sep>/Api/Api.Application/Messages/IEventHandler.cs
using System.Threading.Tasks;
namespace Api.Application.Messages
{
public interface IEventHandler<in TEvent> where TEvent: class, IEvent
{
Task HandleAsync(TEvent @event);
}
}<file_sep>/Api/Api.Infrastructure/Messages/EventBroker.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Api.Application.Messages;
using Microsoft.Extensions.DependencyInjection;
namespace Api.Infrastructure.Messages
{
public class EventBroker : IEventBroker
{
private readonly IServiceScopeFactory _serviceFactory;
public EventBroker(IServiceScopeFactory serviceFactory) => _serviceFactory = serviceFactory;
public async Task PublishAsync<TEvent>(TEvent @event) where TEvent : class, IEvent
{
using IServiceScope scope = _serviceFactory.CreateScope();
var eventHandlers = scope.ServiceProvider.GetServices<IEventHandler<TEvent>>();
foreach (var eventHandler in eventHandlers)
{
await eventHandler.HandleAsync(@event);
}
}
}
}<file_sep>/Api/Api.Infrastructure/Errors/ExceptionToResponseMapper.cs
using System;
using System.Diagnostics;
using System.Net;
using Api.Domain.Exceptions;
using ApplicationException = Api.Application.Exceptions.ApplicationException;
namespace Api.Infrastructure.Errors
{
public class ExceptionToResponseMapper : IExceptionToResponseMapper
{
public Error GetErrorBasedOnException(Exception exception) =>
exception switch
{
ApplicationException ex => HandleApplicationException(ex),
DomainException ex => HandleDomainException(ex),
_ => new Error("Error", "Generic error", HttpStatusCode.InternalServerError)
};
private Error HandleApplicationException(ApplicationException exception)
=> exception switch
{
_ => new Error("Domain_exception", "Error occured while parsing domain object",
HttpStatusCode.InternalServerError)
};
private Error HandleDomainException(DomainException exception)
=> exception switch
{
_ => new Error("Application_exception", "Error occured while making request",
HttpStatusCode.BadRequest)
};
}
}<file_sep>/Api/Api.Infrastructure/Errors/Extensions.cs
using Microsoft.Extensions.DependencyInjection;
namespace Api.Infrastructure.Errors
{
public static class Extensions
{
public static IServiceCollection AddExceptionToErrorMapper<TImplementation>(this IServiceCollection services) where TImplementation: class, IExceptionToResponseMapper
=> services.AddSingleton<IExceptionToResponseMapper, TImplementation>();
}
}<file_sep>/Api/Api.Infrastructure/Initialize/MessagesExtensions.cs
using System;
using Api.Application.Messages;
using Api.Infrastructure.Messages;
using Microsoft.Extensions.DependencyInjection;
namespace Api.Infrastructure.Initialize
{
public static class MessagesExtensions
{
public static IServiceCollection AddEventBroker(this IServiceCollection services)
{
services.AddSingleton<IEventBroker, EventBroker>();
return services;
}
public static IServiceCollection AddEventHandlers(this IServiceCollection services)
{
services.Scan(s => s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
.AddClasses(c => c.AssignableTo(typeof(IEventHandler<>)))
.AsImplementedInterfaces()
.WithTransientLifetime());
return services;
}
}
}<file_sep>/Api/Api/Controllers/AuthController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Api.Application.Handlers;
using Api.Application.Messages;
using Api.Attributes;
using Api.Infrastructure.Cqrs;
using Api.Infrastructure.Messages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly IQueryDispatcher _queryDispatcher;
private readonly ICommandDispatcher _commandDispatcher;
public AuthController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher)
{
_queryDispatcher = queryDispatcher;
_commandDispatcher = commandDispatcher;
}
[HttpPost]
[Route("Register")]
[SwaggerDescription("Register user.")]
public async Task<ActionResult> Register()
{
return Ok();
}
[HttpGet]
[Route("Login")]
[SwaggerDescription("Login to application.")]
public async Task<ActionResult> Login()
{
return Ok();
}
[HttpGet]
[Route("Refresh")]
[SwaggerDescription("Refresh token pair based on refresh token being send.")]
public async Task<ActionResult> Refresh()
{
return Ok();
}
}
}<file_sep>/Api/Api.Infrastructure/Cqrs/QueryDispatcher.cs
using System;
using System.Reflection;
using System.Threading.Tasks;
using Api.Application.Handlers;
using Microsoft.Extensions.DependencyInjection;
#pragma warning disable 8600
namespace Api.Infrastructure.Cqrs
{
public class QueryDispatcher : IQueryDispatcher
{
private readonly IServiceScopeFactory _serviceFactory;
public QueryDispatcher(IServiceScopeFactory serviceFactory) => this._serviceFactory = serviceFactory;
public async Task<TResult> QueryAsync<TResult>(IQuery<TResult> query)
{
TResult result;
using (IServiceScope scope = this._serviceFactory.CreateScope())
{
Type serviceType = typeof (IQueryHandler<,>).MakeGenericType(query.GetType(), typeof (TResult));
object requiredService = scope.ServiceProvider.GetRequiredService(serviceType);
MethodInfo method = serviceType.GetMethod("HandleAsync");
object obj;
if ((object) method == null)
obj = (object) null;
else
obj = method.Invoke(requiredService, new object[1]
{
(object) query
});
result = await (Task<TResult>) obj!;
}
return result;
}
public async Task<TResult> QueryAsync<TQuery, TResult>(TQuery query) where TQuery : class, IQuery<TResult>
{
TResult result;
using (IServiceScope scope = _serviceFactory.CreateScope())
result = await scope.ServiceProvider.GetRequiredService<IQueryHandler<TQuery, TResult>>().HandleAsync(query);
return result;
}
}
}
#pragma warning restore 8600<file_sep>/Api/Api/Attributes/SwaggerDescriptionAttribute.cs
using System;
namespace Api.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public class SwaggerDescriptionAttribute : Attribute
{
public string Description { get; }
public SwaggerDescriptionAttribute(string description)
{
Description = description;
}
}
}<file_sep>/Api/Api.Infrastructure/Errors/IExceptionToResponseMapper.cs
using System;
using Api.Application.Exceptions;
namespace Api.Infrastructure.Errors
{
public interface IExceptionToResponseMapper
{
Error GetErrorBasedOnException(Exception exception);
}
}<file_sep>/Api/Api/Helpers/Swagger/ApplySwaggerDescriptionFilter.cs
using System.Linq;
using Api.Attributes;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Api.Helpers.Swagger
{
public class ApplySwaggerDescriptionFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.ApiDescription.CustomAttributes()
.FirstOrDefault(a => a.GetType() == typeof(SwaggerDescriptionAttribute)) is SwaggerDescriptionAttribute attr)
{
operation.Description = attr.Description;
}
}
}
}<file_sep>/Api/Api.Application/Messages/IEvent.cs
namespace Api.Application.Messages
{
public interface IEvent
{
}
}<file_sep>/Api/Api.Infrastructure/Errors/Error.cs
using System.Net;
namespace Api.Infrastructure.Errors
{
public class Error
{
public string Code { get; }
public string Message { get; }
public HttpStatusCode StatusCode { get; }
public Error(string code, string message, HttpStatusCode statusCode)
{
Code = code;
Message = message;
StatusCode = statusCode;
}
}
}<file_sep>/Api/Api.Application/Handlers/ICommand.cs
namespace Api.Application.Handlers
{
public interface ICommand
{
}
}<file_sep>/Api/Api.Infrastructure/Messages/IEventBroker.cs
using System.Threading.Tasks;
using Api.Application.Messages;
namespace Api.Infrastructure.Messages
{
public interface IEventBroker
{
Task PublishAsync<TEvent>(TEvent @event) where TEvent : class, IEvent;
}
}<file_sep>/Api/Api.Infrastructure/Cqrs/ICommandDispatcher.cs
using System.Threading.Tasks;
using Api.Application.Handlers;
namespace Api.Infrastructure.Cqrs
{
public interface ICommandDispatcher
{
Task SendAsync<T>(T command) where T : class, ICommand;
}
}
|
cfaf842a283c8dd15ec41bbd718dd6d2481c84d4
|
[
"Markdown",
"C#"
] | 19
|
Markdown
|
cebilon123/monolith-boilerplate
|
6486c8eaa72127931f4b0a742c9a9f93b628e82c
|
919197aa4f285364cce93dd5299d8798745e1c4b
|
refs/heads/master
|
<repo_name>hanshvidberg/tingfinderen<file_sep>/src/app/index.module.js
(function() {
'use strict';
angular
.module('tingfinderen', ['ngAnimate', 'ngSanitize', 'ui.router', 'ui.bootstrap','angularUtils.directives.dirPagination','ct.ui.router.extras.previous','duScroll']);
})();
<file_sep>/src/inc/latest.php
<?php
require_once('link.php');
$sql = 'SELECT * FROM product ORDER BY pid DESC LIMiT 12';
$q = $dbh->query($sql);
echo json_encode($q->fetchAll(PDO::FETCH_ASSOC));
<file_sep>/src/inc/link.php
<?php
$database = 'hanshost_tingfinderen';
$hostname = 'localhost';
$username = 'admin';
$password = '<PASSWORD>';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database;",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
<file_sep>/src/app/templates/process.html
<section id='video' class=''>
<div class='video-intro'>
<div id="play-btn">
<div id="cirle" class='vertical-center'> play</div>
</div>
</div>
</section>
<section class=''>
<div id='brand-description' class="container-fluid no-pad">
<div class="section-1">
<div class="container">
<div class="row ">
<div class="col-sm-5 col-xs-10 col-sm-offset-1">
<div class="text-wrap">
<h2>We are not only about interior design.</h2>
<p>At www.tyskenhavn.dk you can get great wines at a very affordable prize. Like with lamps and furniture we have some great friends that imports wine, that makes it possible for us to deliver these products.</p>
<h2>Wine for any occasion.</h2>
<p>It is not only a about special wine for special occasions. You have the possibility to order several cases at a time, if you have found your favourite you always want to have on hand.</p>
<a href='assets/images/desktop-tysk.jpg' target='_blank' class='btn btn-ghost btn-ghost-light btn-default'>TYSKENHAVN</a>
</div>
</div>
</div>
</div>
</div>
<div class="section-2">
<div class="container">
<div class="row ">
<div class="col-sm-5 col-xs-10 col-xs-offset-2 col-sm-offset-6">
<div class="text-wrap">
<h2>We also bring people together.</h2>
<p>The best idea we have come up with so far is to combine our three favourite things. Great wine, great design and people!</p>
<p>So come down to our combined wineshop and design shop where you can sit a drink very good and affordable wine buy the chair you have been sitting on when you leave.</p>
<a href='https://www.google.dk/maps/place/Knabrostr%C3%A6de+25,+1210+K%C3%B8benhavn+K/@55.6768344,12.5747888,17.62z/data=!4m2!3m1!1s0x46525311421595ef:0x987370a132434d6?hl=en' target='_blank' class='btn btn-ghost btn-ghost-light btn-default'>TYSKENHAVN & TINGFINDEREN</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class='full-width'>
</section>
<file_sep>/src/app/services/InstaService.js
'use strict()';
angular.module('tingfinderen').factory('InstaService',InstaService);
function InstaService($http, $q) {
return {
getFeed: function () {
var clientId = '<KEY>';
var userId = '2157283223';
var hansId = '178209582';
var token = '178209582.5fbe931.5b2fa74d6b274eea9718723ea9f3f8e1';
var token2 = '<KEY>';
var url = 'https://api.instagram.com/v1/users/' + hansId + '/media/recent/?access_token=' + token;
var url2 = 'https://api.instagram.com/v1/users/' + userId + '/media/recent/?client_id=' + clientId;
var deferred = $q.defer();
// $http.get('/insta').then(function (res) {
// console.log(res);
// deferred.resolve(res.data);
// });
$http.get('data/ting.json').then(function (res) {
console.log(res.data);
deferred.resolve(res.data);
});
return deferred.promise;
}
};
}
<file_sep>/src/app/index.route.js
(function() {
'use strict';
angular
.module('tingfinderen')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
params: {
target: null
},
resolve : {
allProducts: function(ShopService) {
// return $http.get('/all');
return ShopService.getAll();
}
},
controller: 'HomeController',
controllerAs: 'home',
views: {
'header':{
templateUrl: 'app/templates/header.html',
controller: 'HomeController',
controllerAs: 'home'
},
'shop' : {
controller: 'ShopController',
controllerAs: 'shop',
templateUrl: 'app/templates/shop.html',
},
'brand' : {
templateUrl: 'app/templates/brand.html'
},
'gallery': {
template: 'gallery'
},
'instafeed': {
templateUrl: 'app/templates/instafeed.html',
controller: 'InstaController',
controllerAs: 'insta',
resolve: {
feed: function (InstaService) {
return InstaService.getFeed();
}
}
},
'footer' : {
templateUrl: 'app/templates/footer.html'
}
}
})
.state('process', {
url: '/about',
templateUrl: 'app/templates/process.html',
views: {
'@': {
templateUrl: 'app/templates/process.html'
},
'instafeed': {
templateUrl: 'app/templates/instafeed.html',
controller: InstaController,
controllerAs: 'insta',
resolve: {
feed: function (InstaService) {
return InstaService.getFeed();
}
}
},
'footer@': {
templateUrl: 'app/templates/footer.html'
}
}
})
.state('home.category', {
url: 'category/:cat_id',
templateUrl: 'app/templates/category.html',
controller: 'CategoryController',
controllerAs: 'cat',
resolve : {
products: function (ShopService, $stateParams) {
return ShopService.getCat($stateParams.cat_id);
}
}
})
.state('home.category.product', {
url: '/:pid',
templateUrl: 'app/templates/product.html',
controller: ProductController,
controllerAs: 'prod',
resolve: {
product: function (ShopService, $stateParams) {
return ShopService.getItem($stateParams.pid);
}
}
});
$urlRouterProvider.otherwise('/');
}
})();
<file_sep>/src/app/controllers/ShopController.js
'use strict()';
angular.module('tingfinderen').controller('ShopController', ShopController);
function ShopController($rootScope,$stateParams,$state, ShopService, allProducts ){
var vm = this;
vm.products = allProducts;
// console.log('shop prod: ',vm.products);
// console.log('shop root: ', $stateParams);
}
<file_sep>/src/inc/kbh.php
<?php
require_once 'link.php';
$sql = "SELECT * FROM kbhlamp WHERE orderstatus = available"
$query = $dbh->query($sql);
echo json_encode($query->fetchAll(PDO::FETCH_ASSOC));
<file_sep>/src/app/controllers/InstaController.js
'use strict()';
angular.module('tingfinderen').controller('InstaController', InstaController);
function InstaController(feed){
var vm = this;
vm.feed = feed.data;
// console.log(vm.feed);
}
<file_sep>/src/app/controllers/CategoryController.js
'use strict()';
angular.module('tingfinderen').controller('CategoryController',CategoryController);
function CategoryController(ShopService, $stateParams, products, $scope,$document, $state,$timeout) {
var vm = this;
vm.category = $stateParams.cat_id;
// console.log('cat is: ', vm.category);
// $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
// el = angular.element(document.getElementById('shop'));
// // if (fromState.name != "home.category.product") {
// $timeout(function() {
// $document.scrollToElement(el, 0, 550);
// });
// // }
// // console.log(fromState);
// });
vm.products = products;
vm.cat_description = products[0].cat_desc;
// console.log('cat prod: ', vm.products);
}
<file_sep>/src/inc/test.php
<?php
require_once('link.php');
/* $sql = "SELECT * FROM lamp"; */
/* while ($r = $sql->fetch()) { */
/* echo $r['name']; */
/* } */
/* $stmt = $dbh->prepare($sql); */
/* $stmt->execute(); */
/* $result = $stmt->fetchAll( PDO::FETCH_ASSOC ); */
/* /1* $json = json_decode( $result ); *1/ */
/* print_r $result; */
class Product {
public $id,$name, $price, $description;
}
$name = '<NAME>';
$price = '600';
$description = "It is a very rare and expensive lamp";
$cat = 'lamp';
$sql = "INSERT INTO product (name, price, description, cat) VALUES (?, ?, ?,?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($name, $price,$description, $cat));
/* $query = $dbh->query("SELECT * FROM lamp"); */
/* echo '<pre>', print_r($query->fetchAll(PDO::FETCH_ASSOC)), '</pre>'; */
// set fetch mode
/* $query->setFetchMode(PDO::FETCH_CLASS,'Product'); */
/* while ($r = $query->fetch()) { */
/* /1* echo '<pre>',print_r($r),'</pre>'; *1/ */
/* echo json_encode($r); */
/* } */
/* while($r = $query->fetch(PDO::FETCH_OBJ)) { */
/* echo $r->name, ', '; */
/* echo $r->price, '<br>'; */
/* } */
/* echo '<pre>',print_r($r), '</pre>'; */
<file_sep>/src/app/controllers/HomeController.js
'use strict()';
angular.module('tingfinderen').controller('HomeController',HomeController);
function HomeController($scope, $state,$stateParams) {
var vm = this;
vm.homestate = null;
vm.state = $state;
vm.test = 'i am test';
// console.log('params: ', $stateParams);
// console.log('state: ', $state);
}
<file_sep>/src/app/directives/navbar-directive.js
'use strict';
angular.module('tingfinderen').directive('navBar', navBar);
function navBar(){
return {
restrict: 'EA',
replace: false,
templateUrl: 'app/templates/navbar.html',
};
}
<file_sep>/src/app/index.config.js
(function() {
'use strict';
angular
.module('tingfinderen')
.config(config);
/** @ngInject */
function config($logProvider, paginationTemplateProvider) {
// Enable log
$logProvider.debugEnabled(true);
paginationTemplateProvider.setPath('app/templates/pagination.tpl.html');
// Set options third-party lib
}
})();
<file_sep>/src/app/controllers/ProductController.js
'use strict()';
angular.module('tingfinderen').controller('ProductController',ProductController);
function ProductController(ShopService, $stateParams, product,$previousState, $scope, $document, $timeout) {
var vm = this;
vm.category = $stateParams.cat_id;
// console.log(vm.category);
vm.prev = $previousState.get();
vm.product = product[0];
// console.log('prev state is: ',vm.prev);
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
el = angular.element(document.getElementById('shop'));
console.log(el);
// if (fromState.name != "home.category.product") {
$timeout(function() {
$document.scrollToElement(el, -2, 550);
},300);
// }
// console.log(fromState);
});
}
|
f1cda490b85bf1eea15563d8184605b412ca64e9
|
[
"JavaScript",
"HTML",
"PHP"
] | 15
|
JavaScript
|
hanshvidberg/tingfinderen
|
61ac5b25c53f2f4d696c9c2b328a44686abd7442
|
3d117a26e47ca57c9e0c5b9e196f4452f4e85723
|
refs/heads/master
|
<file_sep>
import Basic
import Foundation
public struct Shell {
private init() {}
public static var isDryRun: Bool = false
public static func run(_ command: String..., exitOnFailure: Bool = true) {
let cmd = command.joined(separator: " ")
Logger.info(cmd)
guard !isDryRun else { return }
let process = Foundation.Process()
process.launchPath = "/bin/sh"
process.arguments = ["-c", cmd]
process.standardOutput = FileHandle.standardOutput
let errorPipe = Pipe()
process.standardError = errorPipe
process.launch()
process.waitUntilExit()
let status = process.terminationStatus
if status != 0 {
Logger.error("Error running the following command:")
Logger.info("\t" + cmd)
let data = errorPipe.fileHandleForReading.readDataToEndOfFile()
if let error = String(data: data, encoding: .utf8) {
Logger.error(error)
}
if exitOnFailure {
exit(status)
}
}
}
}
public enum Logger {
private static let terminal: TerminalController? = {
guard let stdout = stdoutStream as? LocalFileOutputByteStream else { return nil }
return TerminalController(stream: stdout)
}()
public static func status(_ message: String) {
terminal?.write("➜ " + message, inColor: .cyan, bold: true)
terminal?.endLine()
}
public static func info(_ message: String) {
terminal?.write("➜ " + message, inColor: .green, bold: true)
terminal?.endLine()
}
public static func error(_ message: String) {
terminal?.write("➜ " + message, inColor: .red, bold: true)
terminal?.endLine()
}
}
|
4d52a1002e0bfdb85a8479617b72493d98bd52f1
|
[
"Swift"
] | 1
|
Swift
|
AlTavares/SwiftyShell
|
096b1661ff1190854a1068c1dcd06f5ef57b2563
|
7f9525174f6f4bdc6d5088c51588b00798db0d73
|
refs/heads/master
|
<file_sep>{
init: async function(elevators, floors) {
// console.log(localStorage.getItem('elevatorCrushCode_v5'))
// doFitnessSuite(localStorage.getItem('elevatorCrushCode_v5'), 10)
if (typeof tf == 'undefined') {
await fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2')
.then(response => response.text())
.then(body => (0, eval)(body))
console.log('TF fetched')
}
console.log('TensorFlow ready!', tf)
//Upsy, your lifting friend
//takes combination of elevatorState and floorState to give confidence of visiting floor
const elevatorBrain = tf.sequential({
layers: [tf.layers.dense({units: 10, inputShape: [13], activation: 'sigmoid', kernalInitializer: 'randomNormal', biasInitializer: 'randomNormal'}),
tf.layers.dense({units: 1, kernalInitializer: 'randomNormal', biasInitializer: 'randomNormal'})
]
})
for (let elevator of elevators) {
elevator.on("idle", () => {
tf.tidy(() => {
let floorWeights = floors.map((floor) => {
let inputs = tf.tensor2d([this.getInputs(elevator, floor)])
const result = elevatorBrain.predict(inputs)
console.log('i', floor.floorNum(), result.dataSync())
return result.dataSync()[0]
})
let floorOfMaxValue = floorWeights.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0)
elevator.goToFloor(floorOfMaxValue)
})
})
elevator.on('passing_floor', (floorNum, direction) => {
tf.tidy(() => {
let inputs = tf.tensor2d([this.getInputs(elevator, floors[floorNum])])
const result = elevatorBrain.predict(inputs)
console.log('p', floorNum, result.dataSync())
if(result.dataSync()[0] > 0.5) {
elevator.goToFloor(floorNum, true)
}
})
})
}
},
getInputs(elevator, floor) {
let e = this.getElevatorState(elevator)
let f = this.getFloorState(floor)
return [
e.currentFloor == f.floorNum ? 1:0, //is floor we're at?
1 / (Math.abs(e.currentFloor - f.floorNum) + 1), //how close are we
f.currentFloor == e.nextDestination ? 1:0, //is next destination floor?
1 / (Math.abs(e.nextDestination - f.floorNum) + 1) || 0, //how close to destination
e.destinationQueue.includes(f.floorNum)? 1:0, //is in destination queue
e.loadFactor,
e.goingUpIndicator? 1:0,
e.goingDownIndicator? 1:0,
e.destinationDirectionIsUp? 1:0,
e.destinationDirectionIsDown? 1:0,
e.destinationDirectionIsStopped? 1:0,
f.buttonStateUp? 1:0,
f.buttonStateDown? 1:0
]
},
getElevatorState(elevator) {
return {
currentFloor: elevator.currentFloor(),
loadFactor: elevator.loadFactor(),
goingUpIndicator: elevator.goingUpIndicator(),
goingDownIndicator: elevator.goingDownIndicator(),
destinationDirectionIsUp: elevator.destinationDirection() == 'up',
destinationDirectionIsDown: elevator.destinationDirection() == 'down',
destinationDirectionIsStopped: elevator.destinationDirection() == 'stopped',
destinationQueue: elevator.destinationQueue,
nextDestination: elevator.destinationQueue[0]
}
},
getFloorState(floor) {
return {
floorNum: floor.floorNum(),
buttonStateUp: floor.buttonStates.up == 'activated',
buttonStateDown: floor.buttonStates.down == 'activated'
}
},
update: function(dt, elevators, floors) {
// console.log(tf.memory().numTensors)
}
}
<file_sep>{
init: function(elevators, floors) {},
goToBestFloor(elevator, floors, isUp, eAlreadyGoing=[]) {
let destinations = elevator.getPressedFloors()
for(let floor of floors){
let loadLimit = (isUp && floor.floorNum() == 0)? .1 : .6
if(elevator.loadFactor() < loadLimit){
if(floor.buttonStates[isUp? 'up':'down'] == 'activated' && (!eAlreadyGoing[(isUp?'u':'d')+String(floor.floorNum())] || floor.floorNum() == 0 )) {
destinations.push(floor.floorNum())
}
}
}
if(destinations.length == 0) {
destinations.push(0)// hangout in lobby //isUp? 0 : floors.length-1) // add loby or top floor as neutral positions
}
destinations.sort((a,b) => (isUp)? a-b:b-a)
elevator.destinationQueue = [destinations[0]]
elevator.checkDestinationQueue()
return destinations[0]
},
switchTime: 0,
swap: false,
update: function(dt, elevators, floors) {
this.switchTime += dt
if(elevators.length % 2 == 1 && this.switchTime > 10) {
this.swap = !this.swap
this.switchTime = 0
}
let eAlreadyGoing = []
for(let eIndex = 0; eIndex < elevators.length; eIndex++){
let elevator = elevators[eIndex]
let isUp = eIndex % 2 == 0
if(eIndex == elevators.length-1){
isUp = isUp != this.swap
}
elevator.goingUpIndicator(isUp || elevator.currentFloor() < (floors.length-1)*.3)
elevator.goingDownIndicator(!isUp || elevator.currentFloor() > (floors.length-1)*.8)
let d = this.goToBestFloor(elevator, floors, isUp, eAlreadyGoing)
eAlreadyGoing[(isUp?'u':'d')+String(d)] = true
}
}
}
<file_sep>Upsy, your lifting friend!
TensorFlow.js implementation for [Elevator Saga](https://play.elevatorsaga.com/)
Name borrowed from Mr. Upsy of The Adventure Zone
|
50b91ffd76ece77e9773783b00078a9796185405
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Zoey4560/upsy
|
d8c698c7d7eb81567c561bc99f5ab05296cc4c88
|
a20aa983570069b052f3f1f769c5173c344fdf3c
|
refs/heads/master
|
<file_sep>package com.ingjmcaicedo.spring.model;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("qa")
public class DarkSideOfTheMoon implements CompacDisc {
private static final String NAME = "DarkSideOfTheMoon";
public void play() {
System.out.println("Playing "+NAME);
}
}
<file_sep>package org.example.service.impl;
import org.example.service.CustomerService;
import org.springframework.stereotype.Service;
@Service
public class CustomerServiceImpl implements CustomerService{
@Override
public void save(int id, String name, int age) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Customer saved!!");
}
@Override
public void update(int id, String name, int age) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Customer updated!!");
}
@Override
public String getName(int id) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Dummy";
}
}
<file_sep>package com.ingjmcaicedo.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.ingjmcaicedo.spring.model.CompacDisc;
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
<file_sep>package com.ingjmcaicedo.spring.model;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("dev")
public class SgtPepper implements CompacDisc {
private static final String NAME = "Sargent Pepper Disc";
public void play() {
System.out.println("Playing "+NAME);
}
}
<file_sep>package org.example.service;
public interface CustomerService {
void save(int id, String name, int age);
void update(int id, String name, int age);
String getName(int id);
}
<file_sep>package org.example;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
@Configurable
@Import(AspectConfig.class)
@ComponentScan("org.example.service")
public class AppConfig {
}
<file_sep>package org.example;
import org.example.service.PrintService;
import org.example.service.impl.ConsolePrinting;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PrintConfig {
@Bean
public PrintService printService(){
return new ConsolePrinting();
}
}
<file_sep>package org.example.service.impl;
import org.example.service.MathService;
public class Calculator implements MathService {
public int addInts(int firstValue, int secondValue) {
return firstValue + secondValue;
}
}
<file_sep>package org.example.test.service;
import org.example.AppConfig;
import org.example.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
@ActiveProfiles({"PROD"})
public class ProdCustomerServiceTest {
@Autowired
private CustomerService customerService;
@Test
public void save_customer_test(){
customerService.save(0, null, 0);
}
@Test
public void update_customer_test(){
customerService.update(0, null, 0);
}
@Test
public void get_name_customer_test(){
customerService.getName(0);
}
}
<file_sep>package com.ingjmcaicedo.spring.knight.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.ingjmcaicedo.spring.knight.Knight;
import com.ingjmcaicedo.spring.knight.Quest;
public class BraveKnight implements Knight {
@Autowired
private Quest quest;
public void startQuest() {
System.out.println(quest.getQuestDescription());
}
}
<file_sep>package com.ingjmcaicedo.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.ingjmcaicedo.spring.model.CompacDisc;
public class CDPlayerMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
CompacDisc disc = context.getBean(CompacDisc.class);
disc.play();
}
}
|
332d21a5bdf8c630d77f17ac5f1f64ed3f51912b
|
[
"Java"
] | 11
|
Java
|
jcaicedo-dev/emars_spring_workspace
|
7e01f2308f6c9fe9e55fe9bf4378a83e12d1c9f4
|
d94f44666dbd098d310cb89a76a412bac8292301
|
refs/heads/master
|
<repo_name>jaspervanmegroot/CardView<file_sep>/PanCardView/Enums/InteractionType.cs
using System;
using Xamarin.Forms;
namespace PanCardView.Enums
{
[Flags]
public enum InteractionType
{
Gesture = -1,
Animation = 1
}
}
|
6e38ad686a61a4a93ad8d726dfdece62220edf87
|
[
"C#"
] | 1
|
C#
|
jaspervanmegroot/CardView
|
5bb0eecac0e5162659cd3f94cd965dbd0ee351de
|
dd17b399b2a4554fa94371c44239bd3a31951231
|
refs/heads/develop
|
<file_sep>#!/usr/bin/env python3
"""
Created on 2 Jul 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth and SystemID documents.
command line examples:
./device_topics.py 5926 -v
"""
import sys
from scs_core.data.datetime import LocalizedDatetime
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.manager.device_manager import DeviceManager
from scs_core.osio.manager.topic_manager import TopicManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_device_topics import CmdDeviceTopics
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdDeviceTopics()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("device_topics: %s" % cmd, file=sys.stderr)
try:
# ------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("device_topics: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("device_topics: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# managers...
device_manager = DeviceManager(api_auth.api_key)
# check for existing registration...
device = device_manager.find(api_auth.org_id, cmd.client_id)
if device is None:
print("device_topics: Device not found.", file=sys.stderr)
exit(1)
topic_manager = TopicManager(api_auth.api_key)
# ------------------------------------------------------------------------------------------------------------
# run...
# time...
if cmd.use_offset():
end = LocalizedDatetime.now()
start = end.timedelta(minutes=-cmd.minutes)
else:
end = LocalizedDatetime.now() if cmd.end is None else cmd.end
start = cmd.start
if cmd.verbose:
print("device_topics: start: %s" % start, file=sys.stderr)
print("device_topics: end: %s" % end, file=sys.stderr)
sys.stderr.flush()
# topics...
topics = topic_manager.find_for_device(cmd.client_id, start, end)
for topic in topics:
print(JSONify.dumps(topic))
if cmd.verbose:
print("device_topics: total: %d" % len(topics), file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# end...
except KeyboardInterrupt:
print(file=sys.stderr)
<file_sep>#!/usr/bin/env python3
"""
Created on 2 Jul 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
command line example:
./user_topics.py southcoastscience-dev -v
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.manager.topic_manager import TopicManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_user_topics import CmdUserTopics
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdUserTopics()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("user_topics: %s" % cmd, file=sys.stderr)
try:
# ------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("user_topics: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("user_topics: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = TopicManager(api_auth.api_key)
# ------------------------------------------------------------------------------------------------------------
# run...
# find...
topics = manager.find_for_user(cmd.user_id)
for topic in topics:
print(JSONify.dumps(topic))
if cmd.verbose:
print("user_topics: total: %d" % len(topics), file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# end...
except KeyboardInterrupt:
print(file=sys.stderr)
<file_sep>#!/usr/bin/env python3
"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth and SystemID documents.
Note: this script currently does not update device tags.
command line examples:
./device.py -v -u south-coast-science-test-user -l 50.823130 -0.122922 "BN2 0DF" -d "test 1"
./device.py -v -u south-coast-science-test-user -l 50.819456 -0.128336 "BN2 1AF" -d "BB dev platform"
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.config.project_source import ProjectSource
from scs_core.osio.manager.device_manager import DeviceManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_device import CmdDevice
# TODO: ability to delete devices
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdDevice()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("device: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("device: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("device: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = DeviceManager(api_auth.api_key)
# check for existing registration...
device = manager.find(api_auth.org_id, cmd.client_id)
if device is None:
print("device: Device not found.", file=sys.stderr)
exit(1)
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
# update Device...
updated = ProjectSource.update(device, cmd.lat, cmd.lng, cmd.postcode, cmd.description)
manager.update(api_auth.org_id, device.client_id, updated)
# find updated device...
device = manager.find(api_auth.org_id, device.client_id)
print(JSONify.dumps(device))
<file_sep>#!/usr/bin/env python3
"""
Created on 14 May 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
command line examples:
./organisation.py -v -o test-org-1 -n "Test Org 1" -w www.southcoastscience.com \
-d "a test organisation" -e <EMAIL>
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.data.organisation import Organisation
from scs_core.osio.manager.organisation_manager import OrganisationManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_organisation import CmdOrganisation
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdOrganisation()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("organisation: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("organisation: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("organisation: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = OrganisationManager(api_auth.api_key)
# check for existing registration...
org = manager.find(cmd.org_id)
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
if org:
name = org.name if cmd.name is None else cmd.name
website = org.website if cmd.website is None else cmd.website
description = org.description if cmd.description is None else cmd.description
email = org.email if cmd.email is None else cmd.email
# update Organisation...
updated = Organisation(None, name, website, description, email)
manager.update(org.id, updated)
else:
if not cmd.is_complete():
print("organisation: The organisation does not exist - you must therefore set all fields.",
file=sys.stderr)
cmd.print_help(sys.stderr)
exit(2)
# create Organisation...
org = Organisation(None, cmd.name, cmd.website, cmd.description, cmd.email)
manager.create(org)
org = manager.find(org.id)
print(JSONify.dumps(org))
<file_sep>"""
Created on 14 May 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdOrganisation(object):
"""
unix command line handler
"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog ORG_ID [-n NAME] [-w WEB] [-d DESCRIPTION] [-e EMAIL] [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--name", "-n", type="string", nargs=1, action="store", dest="name",
help="set name (required if organisation has not yet been registered)")
self.__parser.add_option("--web", "-w", type="string", nargs=1, action="store", dest="website",
help="set website URL (required if organisation has not yet been registered)")
self.__parser.add_option("--desc", "-d", type="string", nargs=1, action="store", dest="description",
help="set description (required if organisation has not yet been registered)")
self.__parser.add_option("--email", "-e", type="string", nargs=1, action="store", dest="email",
help="set email address (required if organisation has not yet been registered)")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.org_id is None:
return False
return True
def is_complete(self):
if self.name is None or self.website is None or self.description is None or self.email is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
def set(self):
if self.name is None and self.website is None and self.description is None and self.email is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
@property
def org_id(self):
return self.__args[0] if len(self.__args) > 0 else None
@property
def name(self):
return self.__opts.name
@property
def website(self):
return self.__opts.website
@property
def description(self):
return self.__opts.description
@property
def email(self):
return self.__opts.email
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdOrganisation:{org_id:%s, name:%s, website:%s, description:%s, email:%s, verbose:%s}" % \
(self.org_id, self.name, self.website, self.description, self.email, self.verbose)
<file_sep>"""
Created on 21 Mar 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdUser(object):
"""
unix command line handler
"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog -p PASSWORD [-n NAME] [-e EMAIL] [-v]",
version="%prog 1.0")
# compulsory...
self.__parser.add_option("--password", "-p", type="string", nargs=1, action="store", dest="password",
help="password (compulsory)")
# optional...
self.__parser.add_option("--name", "-n", type="string", nargs=1, action="store", dest="name",
help="set name")
self.__parser.add_option("--email", "-e", type="string", nargs=1, action="store", dest="email",
help="set email address")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.password is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
def set(self):
return self.name is not None or self.email is not None or self.password is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def password(self):
return self.__opts.password
@property
def name(self):
return self.__opts.name
@property
def email(self):
return self.__opts.email
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdUser:{password:%s, name:%s, email:%s, verbose:%s}" % \
(self.password, self.name, self.email, self.verbose)
<file_sep>"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
example document:
{"user-id": "southcoastscience-dev", "client-id": "5873", "client-password": "<PASSWORD>"}
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdClientAuth(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog [-s USER_ID CLIENT_ID CLIENT_PASSWORD] [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--set", "-s", type="string", nargs=3, action="store", dest="user_client_password",
help="user ID, client ID and client password")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def set(self):
return self.__opts.user_client_password is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def user_id(self):
return None if self.__opts.user_client_password is None else self.__opts.user_client_password[0]
@property
def client_id(self):
return None if self.__opts.user_client_password is None else self.__opts.user_client_password[1]
@property
def client_password(self):
return None if self.__opts.user_client_password is None else self.__opts.user_client_password[2]
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
return "CmdClientAuth:{user_id:%s, client_id:%s, client_password:%s, verbose:%s}" % \
(self.user_id, self.client_id, self.client_password, self.verbose)
<file_sep>"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdDeviceList(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog {-u | -o} [-v]", version="%prog 1.0")
# compulsory...
self.__parser.add_option("--user", "-u", action="store_true", dest="user", default=False,
help="list for user ID of client auth")
self.__parser.add_option("--org", "-o", action="store_true", dest="org", default=False,
help="list for org ID of API auth")
# optional...
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.user or self.org:
return True
return False
# ----------------------------------------------------------------------------------------------------------------
@property
def user(self):
return self.__opts.user
@property
def org(self):
return self.__opts.org
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdDeviceList:{user:%s, org:%s, verbose:%s}" % (self.user, self.org, self.verbose)
<file_sep>#!/usr/bin/env python3
"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth and ClientAuth documents.
command line example:
./device_list.py -u -v
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.manager.device_manager import DeviceManager
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.client.client_auth import ClientAuth
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_device_list import CmdDeviceList
# TODO: add ability to specify the used ID
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdDeviceList()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("device_list: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("device_list: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("device_list: %s" % api_auth, file=sys.stderr)
# ClientAuth...
client_auth = ClientAuth.load(Host)
if client_auth is None:
print("device_list: ClientAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("device_list: %s" % client_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = DeviceManager(api_auth.api_key)
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.org:
devices = manager.find_all_for_org(api_auth.org_id)
else:
devices = manager.find_all_for_user(client_auth.user_id)
for device in devices:
print(JSONify.dumps(device))
if cmd.verbose:
print("device_list: total: %d" % len(devices), file=sys.stderr)
<file_sep>"""
Created on 19 Feb 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdDevice(object):
"""
unix command line handler
"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog CLIENT_ID [-l LAT LNG POSTCODE] [-d DESCRIPTION] [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--loc", "-l", type="string", nargs=3, action="store", dest="lat_lng_postcode",
help="set device location")
self.__parser.add_option("--desc", "-d", type="string", nargs=1, action="store", dest="description",
help="set device description")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.client_id is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
def set(self):
return self.__opts.lat_lng_postcode is not None or self.description is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def client_id(self):
return self.__args[0] if len(self.__args) > 0 else None
@property
def lat(self):
return None if self.__opts.lat_lng_postcode is None else self.__opts.lat_lng_postcode[0]
@property
def lng(self):
return None if self.__opts.lat_lng_postcode is None else self.__opts.lat_lng_postcode[1]
@property
def postcode(self):
return None if self.__opts.lat_lng_postcode is None else self.__opts.lat_lng_postcode[2]
@property
def description(self):
return self.__opts.description
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdDevice:{client_id:%s, lat:%s, lng:%s, postcode:%s, description:%s, verbose:%s}" % \
(self.client_id, self.lat, self.lng, self.postcode, self.description, self.verbose)
<file_sep>#!/usr/bin/env python3
"""
Created on 2 Apr 2017
@author: <NAME> (<EMAIL>)
"""
import sys
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.client.client_auth import ClientAuth
from scs_core.osio.manager.device_manager import DeviceManager
from scs_host.sys.host import Host
# --------------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("APIAuth not available.", file=sys.stderr)
exit(1)
print(api_auth)
# ClientAuth...
client_auth = ClientAuth.load(Host)
if client_auth is None:
print("ClientAuth not available.", file=sys.stderr)
exit(1)
print(client_auth)
# manager...
manager = DeviceManager(api_auth.api_key)
print(manager)
print("-")
# --------------------------------------------------------------------------------------------------------------------
# run...
print("find:")
device = manager.find(api_auth.org_id, client_auth.client_id)
print(device)
print("-")
print("find for name:")
device = manager.find_for_name(api_auth.org_id, device.name)
print(device)
print("-")
print("find for user:")
devices = manager.find_all_for_user(client_auth.user_id)
for device in devices:
print(device)
print("-")
print("find for org:")
devices = manager.find_all_for_org(api_auth.org_id)
for device in devices:
print(device)
print("-")
<file_sep>#!/usr/bin/env python3
"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
workflow:
Use host_device instead.
command line example:
./client_auth.py -v -s southcoastscience-dev 5406 jtxSrK2e
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.client_auth import ClientAuth
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_client_auth import CmdClientAuth
# TODO: upgrade this, to take client_id explicitly
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdClientAuth()
if cmd.verbose:
print("client_auth: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
auth = ClientAuth(cmd.user_id, cmd.client_id, cmd.client_password)
auth.save(Host)
else:
# find self...
auth = ClientAuth.load(Host)
print(JSONify.dumps(auth))
<file_sep>#!/usr/bin/env python3
"""
Created on 14 Feb 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
command line example:
./topic_list.py -p /orgs/south-coast-science-dev/uk -v
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.manager.topic_manager import TopicManager
from scs_core.osio.client.api_auth import APIAuth
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_topic_list import CmdTopicList
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdTopicList()
if cmd.verbose:
print("topic_list: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("topic_list: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("topic_list: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = TopicManager(api_auth.api_key)
# ----------------------------------------------------------------------------------------------------------------
# run...
topics = manager.find_for_org(api_auth.org_id, cmd.partial_path, cmd.schema_id)
for topic in topics:
print(JSONify.dumps(topic))
if cmd.verbose:
print("topic_list: total: %d" % len(topics), file=sys.stderr)
<file_sep>"""
Created on 16 Feb 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdTopic(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog PATH [-n NAME -d DESCRIPTION [-s SCHEMA_ID]] [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--name", "-n", type="string", nargs=1, action="store", dest="name",
help="set name (required if topic has not yet been registered)")
self.__parser.add_option("--desc", "-d", type="string", nargs=1, action="store", dest="description",
help="set description (required if topic has not yet been registered)")
self.__parser.add_option("--schema", "-s", type="int", nargs=1, action="store", dest="schema_id",
help="set schema ID (only if topic has not yet been registered)")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.path is None:
return False
return True
def is_complete(self):
if self.name is None or self.description is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
def set(self):
return self.name is not None or self.description is not None or self.schema_id is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def path(self):
return self.__args[0] if len(self.__args) > 0 else None
@property
def name(self):
return self.__opts.name
@property
def description(self):
return self.__opts.description
@property
def schema_id(self):
return self.__opts.schema_id
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdTopic:{path:%s, name:%s, description:%s, schema_id:%s, verbose:%s}" % \
(self.path, self.name, self.description, self.schema_id, self.verbose)
<file_sep>#!/usr/bin/env python3
"""
Created on 21 Mar 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth and ClientAuth documents.
command line example:
./user.py -v -n "Mickey Mouse"
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.client.client_auth import ClientAuth
from scs_core.osio.data.user import User
from scs_core.osio.manager.user_manager import UserManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_user import CmdUser
# TODO: upgrade this, to take user_id explicitly
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdUser()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("user: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("user: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("user: %s" % api_auth, file=sys.stderr)
# ClientAuth...
client_auth = ClientAuth.load(Host)
if client_auth is None:
print("user: ClientAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("user: %s" % client_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = UserManager(api_auth.api_key)
# ----------------------------------------------------------------------------------------------------------------
# run...
# find self...
user = manager.find(client_auth.user_id)
if user is None:
print("user: User not found.", file=sys.stderr)
exit(1)
if cmd.set():
name = user.name if cmd.name is None else cmd.name
email = user.email if cmd.email is None else cmd.email
password = <PASSWORD> if cmd.password is None else cmd.password
updated = User(None, name, email, password, None)
manager.update(user.id, updated)
user = manager.find(client_auth.user_id)
print(JSONify.dumps(user))
<file_sep>#!/usr/bin/env python3
"""
Created on 14 Feb 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
command line example:
./topic_list.py -p /orgs/south-coast-science-dev/uk -v
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.manager.schema_manager import SchemaManager
from scs_core.osio.client.api_auth import APIAuth
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_schema_list import CmdSchemaList
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdSchemaList()
if cmd.verbose:
print("schema_list: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
auth = APIAuth.load(Host)
if auth is None:
print("schema_list: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("schema_list: %s" % auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = SchemaManager(auth.api_key)
# ----------------------------------------------------------------------------------------------------------------
# run...
schemas = manager.find_all()
for schema in schemas:
print(JSONify.dumps(schema))
if cmd.verbose:
print("schema_list: total: %d" % len(schemas), file=sys.stderr)
<file_sep>#!/usr/bin/env python3
"""
Created on 16 Feb 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
workflow:
Use osio_publication instead.
command line example:
./topic.py /orgs/south-coast-science-dev/test/1/status -n "test" -d "test of status" -s 28 -v
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.data.topic import Topic
from scs_core.osio.data.topic_info import TopicInfo
from scs_core.osio.manager.topic_manager import TopicManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_topic import CmdTopic
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdTopic()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("topic: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("topic: APIAuth not available.", file=sys.stderr)
exit(1)
# manager...
manager = TopicManager(api_auth.api_key)
# check for existing registration...
topic = manager.find(cmd.path)
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
if topic:
if cmd.schema_id is not None:
print("topic: It is not possible to change the schema ID of an existing topic.", file=sys.stderr)
cmd.print_help(sys.stderr)
exit(1)
name = topic.name if cmd.name is None else cmd.name
description = topic.description if cmd.description is None else cmd.description
info = TopicInfo(TopicInfo.FORMAT_JSON) if topic.info is None else topic.info
# update Topic...
updated = Topic(None, name, description, topic.is_public, info, None, None)
manager.update(topic.path, updated)
topic = manager.find(topic.path)
else:
if not cmd.is_complete():
print("topic: All fields required for topic creation must be provided.", file=sys.stderr)
cmd.print_help(sys.stderr)
exit(1)
info = TopicInfo(TopicInfo.FORMAT_JSON)
# create Topic...
topic = Topic(cmd.path, cmd.name, cmd.description, True, info, True, cmd.schema_id)
manager.create(topic)
print(JSONify.dumps(topic))
<file_sep>#!/usr/bin/env python3
"""
Created on 30 Mar 2017
@author: <NAME> (<EMAIL>)
example:
{"error": {"body-params": {"client-id": "disallowed-key", "org-id": "disallowed-key", "owner-id": "disallowed-key"}}}
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.client.client_auth import ClientAuth
from scs_core.osio.client.client_exception import ClientException
from scs_core.osio.manager.device_manager import DeviceManager
from scs_host.sys.host import Host
# --------------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("APIAuth not available.", file=sys.stderr)
exit(1)
print(api_auth)
# ClientAuth...
client_auth = ClientAuth.load(Host)
if client_auth is None:
print("ClientAuth not available.", file=sys.stderr)
exit(1)
print(client_auth)
# manager...
manager = DeviceManager(api_auth.api_key)
print(manager)
# --------------------------------------------------------------------------------------------------------------------
# run...
device = manager.find(api_auth.org_id, client_auth.client_id)
print(device)
print("-")
try:
manager.update(api_auth.org_id, client_auth.client_id, device)
except ClientException as exc:
print(JSONify.dumps(exc))
<file_sep>"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
example document:
{"org-id": "south-coast-science-test-user", "api-key": "<KEY>"}
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdAPIAuth(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog [-s ORG_ID API_KEY] [-v]", version="%prog 1.0")
# optional...
self.__parser.add_option("--set", "-s", type="string", nargs=2, action="store", dest="org_key",
help="set org ID and API key")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def set(self):
return self.__opts.org_key is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def org_id(self):
return None if self.__opts.org_key is None else self.__opts.org_key[0]
@property
def api_key(self):
return None if self.__opts.org_key is None else self.__opts.org_key[1]
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
return "CmdAPIAuth:{org_id:%s, api_key:%s, verbose:%s}" % (self.org_id, self.api_key, self.verbose)
<file_sep>#!/usr/bin/env python3
"""
Created on 30 Apr 2017
@author: <NAME> (<EMAIL>)
Requires APIAuth document.
command line example:
./public_user.py -v south-coast-science-test-user
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_core.osio.manager.user_manager import UserManager
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_public_user import CmdPublicUser
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdPublicUser()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("public_user: %s" % cmd, file=sys.stderr)
# ----------------------------------------------------------------------------------------------------------------
# resources...
# APIAuth...
api_auth = APIAuth.load(Host)
if api_auth is None:
print("public_user: APIAuth not available.", file=sys.stderr)
exit(1)
if cmd.verbose:
print("public_user: %s" % api_auth, file=sys.stderr)
sys.stderr.flush()
# manager...
manager = UserManager(api_auth.api_key)
# ----------------------------------------------------------------------------------------------------------------
# run...
# find self...
user = manager.find_public(cmd.user_id)
if user:
print(JSONify.dumps(user))
<file_sep>#!/usr/bin/env python3
"""
Created on 18 Feb 2017
@author: <NAME> (<EMAIL>)
Creates APIAuth document.
command line example:
./api_auth.py -v -s south-coast-science-test 9fdfb841-3433-45b8-b223-3f5a283ceb8e
"""
import sys
from scs_core.data.json import JSONify
from scs_core.osio.client.api_auth import APIAuth
from scs_host.sys.host import Host
from scs_osio.cmd.cmd_api_auth import CmdAPIAuth
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdAPIAuth()
if cmd.verbose:
print("api_auth: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
auth = APIAuth(cmd.org_id, cmd.api_key)
auth.save(Host)
else:
# find self...
auth = APIAuth.load(Host)
print(JSONify.dumps(auth))
<file_sep>#!/usr/bin/env python3
"""
Created on 11 Apr 2017
@author: <NAME> (<EMAIL>)
DESCRIPTION
The node utility is used to extract a node from within a JSON document. Data is presented as a sequence of documents on
stdin, and the extracted node is passed to stdout. The extracted node may be a leaf node or an internal node. If no
node path is specified, the whole input document is passed to stdout.
The node utility may be set to either ignore documents that do not contain the specified node, or to terminate if the
node is not present.
By default, output is in the form of a sequence of JSON documents, separated by newlines. If the array (-a) option is
selected, output is in the form of a JSON array - the output opens with a '[' character, documents are separated by
the ',' character, and the output is terminated by a ']' character.
Alternatively, if the node is an array or other iterable type, then it may be output as a sequence (a list of items
separated by newline characters) according to the -s flag.
SYNOPSIS
node.py [-i] [{ -a | -s }] [-v] [PATH]
EXAMPLES
climate_sampler.py -i5 | node.py val
DOCUMENT EXAMPLE - INPUT
{"tag": "scs-ap1-6", "rec": "2018-04-04T14:50:38.394+00:00", "val": {"hmd": 59.7, "tmp": 23.8}}
{"tag": "scs-ap1-6", "rec": "2018-04-04T14:55:38.394+00:00", "val": {"hmd": 59.8, "tmp": 23.9}}
DOCUMENT EXAMPLE - OUTPUT
Default mode:
{"hmd": 59.7, "tmp": 23.8}
{"hmd": 59.8, "tmp": 23.9}
Array mode:
[{"hmd": 59.7, "tmp": 23.8}, {"hmd": 59.8, "tmp": 23.9}]
"""
import sys
from scs_core.data.json import JSONify
from scs_core.data.path_dict import PathDict
from scs_osio.cmd.cmd_node import CmdNode
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdNode()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("node: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
try:
# ------------------------------------------------------------------------------------------------------------
# run...
if cmd.array:
print('[', end='')
node = None
first = True
for line in sys.stdin:
datum = PathDict.construct_from_jstr(line)
if datum is None:
continue
if cmd.ignore and not datum.has_path(cmd.path):
continue
try:
node = datum.node(cmd.path)
except KeyError as ex:
print("node: %s" % repr(ex), file=sys.stderr)
exit(1)
document = JSONify.dumps(node)
if cmd.sequence:
try:
for item in node:
print(JSONify.dumps(item))
except TypeError:
print(document)
else:
if cmd.array:
if first:
print(document, end='')
first = False
else:
print(", %s" % document, end='')
else:
print(document)
sys.stdout.flush()
# ----------------------------------------------------------------------------------------------------------------
# end...
except KeyboardInterrupt:
print(file=sys.stderr)
finally:
if cmd.array:
print(']')
<file_sep># scs_osio
OpenSensors.io - device, organisation, topic and schema management tools for South Coast Science air quality
monitoring projects.
_Contains command line utilities only._
**Required libraries:**
* Third party: paho-mqtt
* SCS root: scs_core
* SCS host: scs_host_bbe, scs_host_bbe_southern, scs_host_posix or scs_host_rpi
**Branches:**
The stable branch of this repository is master. For deployment purposes, use:
git clone --branch=master https://github.com/south-coast-science/scs_osio.git
**Example PYTHONPATH:**
macOS, in ~/.bash_profile:
PYTHONPATH="{$HOME}/SCS/scs_analysis/src:{$HOME}/SCS/scs_osio/src:{$HOME}/SCS/scs_host_posix/src:{$HOME}/SCS/scs_core/src:${PYTHONPATH}"
export PYTHONPATH
Raspberry Pi, in /home/pi/.bashrc:
export PYTHONPATH=$HOME/SCS/scs_analysis/src:$HOME/SCS/scs_dev/src:$HOME/SCS/scs_osio/src:$HOME/SCS/scs_mfr/src:$HOME/SCS/scs_dfe_eng/src:$HOME/SCS/scs_host_rpi/src:$HOME/SCS/scs_core/src:$PYTHONPATH
BeagleBone, in /root/.bashrc:
export PYTHONPATH=/home/debian/SCS/scs_dev/src:/home/debian/SCS/scs_osio/src:/home/debian/SCS/scs_mfr/src:/home/debian/SCS/scs_psu/src:/home/debian/SCS/scs_comms_ge910/src:/home/debian/SCS/scs_dfe_eng/src:/home/debian/SCS/scs_host_bbe/src:/home/debian/SCS/scs_core/src:$PYTHONPATH
BeagleBone, in /home/debian/.bashrc:
export PYTHONPATH=~/SCS/scs_dev/src:~/SCS/scs_osio/src:~/SCS/scs_mfr/src:~/SCS/scs_psu/src:~/SCS/scs_comms_ge910/src:~/SCS/scs_dfe_eng/src:~/SCS/scs_host_bbe/src:~/SCS/scs_core/src:$PYTHONPATH
<file_sep>"""
Created on 2 Jul 2017
@author: <NAME> (<EMAIL>)
"""
import optparse
from scs_core.data.datetime import LocalizedDatetime
# --------------------------------------------------------------------------------------------------------------------
class CmdDeviceTopics(object):
"""
unix command line handler
"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog CLIENT_ID { -m MINUTES | -s START [-e END] } [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--minutes", "-m", type="int", nargs=1, action="store", dest="minutes",
help="starting minutes ago")
self.__parser.add_option("--start", "-s", type="string", nargs=1, action="store", dest="start",
help="localised datetime start")
self.__parser.add_option("--end", "-e", type="string", nargs=1, action="store", dest="end",
help="localised datetime end")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.client_id is None or (self.__opts.start is None and self.minutes is None):
return False
if self.__opts.start is not None and LocalizedDatetime.construct_from_iso8601(self.__opts.start) is None:
return False
if self.__opts.end is not None and LocalizedDatetime.construct_from_iso8601(self.__opts.end) is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
def use_offset(self):
return self.minutes is not None
# ----------------------------------------------------------------------------------------------------------------
@property
def client_id(self):
return self.__args[0] if len(self.__args) > 0 else None
@property
def minutes(self):
return self.__opts.minutes
@property
def start(self):
return None if self.__opts.start is None else LocalizedDatetime.construct_from_iso8601(self.__opts.start)
@property
def end(self):
return None if self.__opts.end is None else LocalizedDatetime.construct_from_iso8601(self.__opts.end)
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdDeviceTopics:{client_id:%s, minutes:%s, start:%s, end:%s, verbose:%s}" % \
(self.client_id, self.minutes, self.start, self.end, self.verbose)
|
efbb2e68634a80a3ebd662fc7b67334c841b3f52
|
[
"Markdown",
"Python"
] | 24
|
Python
|
south-coast-science/scs_osio
|
8628e2ae68c361c31b7deed5b58ef3cca8a09607
|
b60d2868d3ac765081893f2700ec2b9a420e1262
|
refs/heads/master
|
<repo_name>vodinhhung2204/do-an-cnpm-practical-laboratory-management-system<file_sep>/src/reducers/index.js
import { combineReducers } from "redux";
import user from "./user";
const myReducer = combineReducers({
user: user
});
export default myReducer;
<file_sep>/src/views/MyProfile/Profile.js
import React, { Component } from "react";
import MyProfile from "./MyProfile";
import EditProfile from "./EditProfile";
import { createBrowserHistory } from "history";
const hist = createBrowserHistory();
export default class UserProfile extends Component {
constructor() {
super();
this.state = {
status: 0
};
this.changeStatus = this.changeStatus.bind(this);
}
changeStatus(value) {
this.setState({
status: value
});
console.log(value);
}
componentDidMount() {
this.setState({
status: 0
});
}
render() {
return (
<div>
{this.state.status === 0 && (
<MyProfile changeStatus={this.changeStatus}></MyProfile>
)}
{this.state.status === 1 && (
<EditProfile changeStatus={this.changeStatus}></EditProfile>
)}
{/* <BrowserRouter>
<Route path="/admin/myprofile" exact component={MyProfile}></Route>
<Route path="/admin/myprofile/edit" exact component={EditProfile} />
</BrowserRouter> */}
</div>
);
}
}
<file_sep>/src/views/ImageUpload/Upload.js
import React, { Component } from 'react';
import firebase from "firebase";
import "./Upload.css";
import {
Button,
Label,
} from 'reactstrap';
const storage = firebase.storage();
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
image: null,
url: '',
progress: 0,
status: false,
}
this.handleChange = this
.handleChange
.bind(this);
this.handleUpload = this.handleUpload.bind(this);
}
handleChange = e => {
if (e.target.files[0]) {
const image = e.target.files[0];
this.setState(() => ({ image }));
}
}
handleUpload = () => {
this.setState({status: false});
const { image } = this.state;
const mssv = this.props.mssv;
const uploadTask = storage.ref(`users/image/${mssv}/${mssv}`).put(image);
uploadTask.on('state_changed',
(snapshot) => {
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
this.setState({ progress });
},
(error) => {
console.log(error);
},
() => {
storage.ref(`users/image/${mssv}/`).child(mssv).getDownloadURL().then(url => {
this.setState({ url });
})
});
}
render() {
const style = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
};
var turnButton;
return (
<div style={style}>
<br />
<img src={ this.props.image || this.state.url || 'http://via.placeholder.com/400x300'} alt="Uploaded images" height="240" width="300" />
<progress hidden="hidden" value={this.state.progress} max="100" />
<Label for="file-upload" className="custom-file-upload">
<i className="fa fa-cloud-upload"></i> Change Image
</Label>
<input id="file-upload" type="file" onChange={this.handleChange} onClick={() => this.setState({status: true})}/>
<Button color="primary" onClick={this.handleUpload}>Update Image</Button>
</div>
)
}
}
export default ImageUpload;<file_sep>/src/views/Base/RoomSearch/RoomsSearch.js
import React, { Component } from 'react';
import {
Badge, Card, CardBody, CardHeader,
Col, Pagination, PaginationItem, PaginationLink, Row, Table,
Form,
FormGroup,
Label,
Dropdown,
DropdownToggle,
ButtonDropdown,
DropdownItem,
DropdownMenu,
Modal,
ModalBody,
ModalFooter,
Alert
} from 'reactstrap';
import fire from "../../../config/fire";
import { isTerminatorless } from '@babel/types';
import { Button, Input } from '@material-ui/core';
import Alerts from '../../Notifications/Alerts/Alerts';
const firebase = require("firebase");
const storage = firebase.storage();
// Required for side-effects
require("firebase/firestore");
var db = fire.firestore();
var idfinal = null;
class Rooms extends Component {
constructor() {
super()
this.state = {
listRooms: [],
modalisOpen: false,
modalisOpenToEdit: false,
modalisOpenToAdd: false,
idRoomCurrent: '',
idNewRoom: idfinal,
amount: '',
broken: '',
name: '',
status: '',
type: '',
listCurrentRoom: [],
listCouresChange: [],
valueCourseChange: [],
dayCurrentCourse: [],
valueCourseChangeTmp: [],
idDayFinal: '',
periodFinal: '',
dayFinal: ''
}
this.toggleModal = this.toggleModal.bind(this);
this.toggleModalEdit = this.toggleModalEdit.bind(this);
this.toggleModalAdd = this.toggleModalAdd.bind(this);
this.GetRoomObject = this.GetRoomObject.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
async componentDidMount() {
//LAY LIST COURSE TRONG KHI EDIT
var listTmpChange = this.state.listCouresChange.slice();
var TmpStudent = null;
var numberstt = 0;
db.collection("courses").get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
doc.data().idDate.forEach(function (data) {
console.log(data)
var course_tmp = {
stt: numberstt,
id: doc.data().idCourses,
idDate: data.id,
name: doc.data().nameCourses,
day: '',
period: '',
room: '',
nameroom: '',
giangvien: '',
students: [],
}
doc.data().idStudent.forEach(async function (dataStudent) {
var docRef = db.collection("students").doc(dataStudent.id);
docRef
.get()
.then(async function (doc) {
if (doc.exists) {
TmpStudent = {
mssv: doc.data().mssv,
name: doc.data().name,
email: doc.data().email,
phone: doc.data().phone
}
//
course_tmp.students.push(TmpStudent)
TmpStudent = null;
}
})
.catch(function (error) {
console.log(error);
});
})
var docRefgv = db.collection("professors").doc(doc.data().idProfessor.id);
docRefgv
.get()
.then(function (doc) {
if (doc.exists) {
course_tmp.giangvien = doc.data().name;
}
})
var docRef = db.collection("date").doc(data.id);
docRef
.get()
.then(function (doc) {
if (doc.exists) {
course_tmp.day = doc.data().day;
course_tmp.period = doc.data().period;
course_tmp.room = doc.data().room.id;
}
//console.log(course_tmp.id)
var docRefroom = db.collection("rooms").doc(course_tmp.room);
docRefroom
.get()
.then(function (doc) {
if (doc.exists) {
course_tmp.nameroom = doc.data().name;
}
//console.log(course_tmp.id)
listTmpChange.push(course_tmp)
}
)
}
)
.catch(function (error) {
console.log(error);
});
})
});
})
this.setState({
valueCourseChange: listTmpChange,
})
//////////////////////////
var listTmp = this.state.listRooms.slice();
await db.collection("rooms").get().then(async function (querySnapshot) {
querySnapshot.forEach(async function (doc) {
var room_tmp = {
id: doc.id,
name: doc.data().name,
amount: doc.data().amount,
broken: doc.data().broken,
status: doc.data().status,
type: doc.data().type,
period: [],
day: '',
vacant: [
'1,2,3,4,5,6,7,8,9,10', // thu 2
'1,2,3,4,5,6,7,8,9,10', // thu 3
'1,2,3,4,5,6,7,8,9,10', // thu 4
'1,2,3,4,5,6,7,8,9,10', //thu 5
'1,2,3,4,5,6,7,8,9,10', // thu 6
'1,2,3,4,5,6,7,8,9,10', // thu7
]
}
if (doc.data().type === "1") {
listTmp.push(room_tmp)
idfinal = Number(room_tmp.id) + 1;
}
});
})
await db.collection("date").get().then(async function (querySnapshot) {
await querySnapshot.forEach(async function (doc) {
listTmp.forEach(function (data) {
if (data.id === doc.data().idRoom) {
var dau = doc.data().period.slice(0, 1) // vi tri dau cua thu
var cuoi = doc.data().period.slice(2, 4) // vi tri cuoi cua thu
//console.log("hom nay la " + thu + "dau la " + dau + " cuoi " + cuoi + " lich nay cua phong " + data.name)
data.vacant[doc.data().day - 2].split(",")
//console.log(data.vacant[doc.data().day - 2])
var periodcurrent = data.vacant[doc.data().day - 2];
periodcurrent = periodcurrent.split(",")
for (var i = 0; i < 10; i++) {
if (periodcurrent[i] === dau) {
periodcurrent[i] = "n";
for (var k = i + 1; k < 10; k++) {
if (periodcurrent[k] !== cuoi) {
periodcurrent[k] = "n"
}
if (periodcurrent[k] === cuoi) {
periodcurrent[k] = "n";
break
}
}
}
}
var tmp = periodcurrent.join()
//console.log(tmp)
data.vacant[doc.data().day - 2] = tmp
//console.log(periodcurrent)
}
})
});
})
//console.log("day la list room", listTmp)
//Lay list course de edit
var msgv = localStorage.getItem("DataUser")
var listCouresChangeTmp = []
await db.collection("courses").get().then(async function (querySnapshot) {
await querySnapshot.forEach(async function (doc) {
console.log(doc.data())
if (doc.data().msgv === msgv) {
listCouresChangeTmp.push(doc.data())
}
})
})
console.log(listCouresChangeTmp)
this.setState({
listRooms: listTmp,
listCouresChange: listCouresChangeTmp
})
}
ChangeCourseAction = (obj) => {
console.log(obj.target.value)
console.log(this.state.valueCourseChange)
var ListCourseChange = this.state.valueCourseChange;
//this.state.valueCourseChange
var inforCourseChange = []
ListCourseChange.forEach(function (Data) {
console.log(Data)
if (Data.id === obj.target.value) {
var TmpChange = {
room: '',
day: '',
period: '',
idDate: Data.idDate
}
TmpChange.room = Data.nameroom;
TmpChange.day = Data.day;
TmpChange.period = Data.period
inforCourseChange.push(TmpChange)
}
})
this.setState({
valueCourseChangeTmp: inforCourseChange
})
}
ChangeCourseActionDetail = (obj) => {
this.setState({
idDayFinal: obj.target.value
})
}
ChangeCourseActionDayFinal = (obj) => {
this.setState({
dayFinal: obj.target.value
})
}
handleEdit = (e) => {
this.setState({
modalisOpenToEdit: !this.state.modalisOpenToEdit,
idRoomCurrent: e
})
console.log(e)
var idroom = this.state.idRoomCurrent
var tmp = {
day: this.state.dayFinal,
idRoom: db.doc(`/roomBooked/${idroom}`),
period: this.state.periodFinal,
mssv: localStorage.getItem('DataUser')
}
console.log(tmp)
}
toggleModal = value => event => {
this.setState({
modalisOpen: !this.state.modalisOpen,
idRoomCurrent: value
})
}
toggleModalEdit = value => event => {
this.setState({
modalisOpenToEdit: !this.state.modalisOpenToEdit,
idRoomCurrent: value
})
}
toggleModalAdd = event => {
this.setState({
modalisOpenToAdd: !this.state.modalisOpenToAdd,
})
}
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
console.log(value)
}
GetRoomObject = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
return (
<div className="animated fadeIn">
<Modal id="articleModal" isOpen={this.state.modalisOpen}
toggle={this.toggleModal.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabel" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Xác nhận thông tin</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Bạn chắc chắn muốn xoá thông tin phòng này chứ?
</Form>
</ModalBody>
<ModalFooter>
<Button id="abc" type="submit" color="success" className="success ml-auto"
style={{ background: "darkgreen", color: "white" }}
onClick={this.toggleModal("0").bind(this)} onClick={e => this.handleDelete()}>Xác nhận</Button>{' '}
<Button id="abc" type="Button" className="second"
style={{ background: "gray", color: "white" }}
onClick={this.toggleModal("0").bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Modal id="articleModalEdit" isOpen={this.state.modalisOpenToEdit}
toggle={this.toggleModalEdit("0").bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabelEdit" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Cập nhật thông tin</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Điền đầy đủ thông tin
</Form>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>Chọn thứ</th>
<th>Chọn tiết (*-*)</th>
</tr>
</thead>
<tbody onChange={this.GetRoomObject}>
<tr>
<td>
<select onChange={this.ChangeCourseActionDayFinal} >
<option key={0} value="Select">Select</option>
<option key={1} value="2">Thứ 2</option>
<option key={2} value="3">Thứ 3</option>
<option key={3} value="4">Thứ 4</option>
<option key={4} value="5">Thứ 5</option>
<option key={5} value="6">Thứ 6</option>
<option key={6} value="7">Thứ 7</option>
</select>
</td>
<td>
<Input className="login-input-text"
placeholder="vd: 6-8 , 5-10"
labelClassName="Password"
value={this.state.password}
type="text"
id="periodChange"
name="periodFinal"
onChange={this.handleInputChange}
><i class="fa fa-lock" aria-hidden="true"></i></Input>
</td>
</tr>
</tbody>
</Table>
</ModalBody>
<ModalFooter>
<Button id="abcEdit" type="submit" className="success ml-auto"
style={{ background: "darkgreen", color: "white" }}
onClick={e => this.handleEdit()}>Lưu thay đổi</Button>{' '}
<Button id="abcEdit" className="second"
style={{ background: "gray", color: "white" }}
onClick={this.toggleModalEdit("0").bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Modal id="articleModalAdd" isOpen={this.state.modalisOpenToAdd}
toggle={this.toggleModalAdd.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabelAdd" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Thêm phòng mới</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Điền đầy đủ thông tin
</Form>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>Tên phòng</th>
<th>Số lượng</th>
<th>Số máy hỏng</th>
<th>Loại phòng(0/1)</th>
</tr>
</thead>
<tbody onChange={this.GetRoomObject}>
<tr>
<td><Input
labelClassName="Name"
placeholder=""
value={this.state.name}
type="text"
id="name"
name="name"
onChange={this.handleInputChange}
/></td>
<td><Input
labelClassName="Amount"
placeholder=""
value={this.state.amount}
type="text"
id="amount"
name="amount"
onChange={this.handleInputChange} /></td>
<td><Input
labelClassName="Broken"
placeholder=""
value={this.state.broken}
type="text"
id="broken"
name="broken"
onChange={this.handleInputChange} /></td>
<td><Input
labelClassName="Type"
placeholder="0.Thuc Hanh, 1.Tu Hoc"
value={this.state.type}
type="text"
id="type"
name="type"
onChange={this.handleInputChange} /></td>
</tr>
</tbody>
</Table>
</ModalBody>
<ModalFooter>
<Button id="abcAdd" type="submit" color="success" className="success ml-auto"
style={{ background: "darkgreen", color: "white" }}
onClick={this.toggleModalAdd.bind(this)} onClick={e => this.handleAdd()}>Thêm phòng</Button>{' '}
<Button id="abcAdd" type="Button" className="second"
style={{ background: "gray", color: "white" }}
onClick={this.toggleModalAdd.bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Danh sách các phòng
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>STT</th>
<th>Tên phòng</th>
<th>Tiết (n: số tiết đã được đặt)</th>
<th>Số Lượng Máy</th>
<th>Loại phòng</th>
<th>Đặt Phòng</th>
</tr>
</thead>
<tbody>
{this.state.listRooms.map((item, i) => {
if (item.type === "1") {
return <tr key={i.id} >
<td>{i + 1}</td>
<td>{item.name}</td>
<td>
{item.vacant.map((data, index) => {
return (
<p key={index}>Thứ {index + 2} : {data}</p>
)
})}
</td>
<td>{item.amount}</td>
<td>{item.type === "0" ? "Thuc hanh" : "Tu hoc"}</td>
<td>
<Button
onClick={()=>this.handleEdit(item.id)}>
<i className="fa fa-edit" ></i>
</Button>
</td>
</tr>
}
})}
</tbody>
</Table>
<nav>
<Row>
<Col sm={10}>
<Pagination>
<PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem>
<PaginationItem active>
<PaginationLink tag="button">1</PaginationLink>
</PaginationItem>
<PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem>
</Pagination>
</Col>
<Col sm={2}>
</Col>
</Row>
</nav>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Rooms;<file_sep>/src/config/fire.js
const firebase = require('firebase/app');
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "test-3ed77.firebaseapp.com",
databaseURL: "https://test-3ed77.firebaseio.com",
projectId: "test-3ed77",
storageBucket: "test-3ed77.appspot.com",
messagingSenderId: "547377359506",
appId: "1:547377359506:web:dacd7f8266173ba4ab944b",
measurementId: "G-C229LDRLP7"
};
// Initialize Firebase
const fire = firebase.initializeApp(firebaseConfig);
export {
fire as default
}<file_sep>/src/views/MyProfile/MyProfile.js
import React, { Component } from "react";
import GridItem from "../Grid/GridItem";
import GridContainer from "../Grid/GridContainer.js";
import {
Form,
FormGroup,
Label,
Modal,
ModalBody,
ModalFooter,
Card,
CardBody,
CardHeader,
Button,
CardFooter,
Col,
Row
} from 'reactstrap';
import "./Myprofile.css";
import LabelInput from "../LabelInput/LabelInput";
import { connect } from "react-redux";
import fire from "../../config/fire";
import UploadImage from "../ImageUpload/Upload";
const firebase = require("firebase");
const storage = firebase.storage();
// Required for side-effects
require("firebase/firestore");
var db = fire.firestore();
var DataUser = {};
class UserProfile extends Component {
constructor() {
super();
this.state = {
email: '',
gender: '',
mssv: '',
name: '',
birthday: '',
pass:'',
modalisOpen: false,
avatars: [],
status: true,
statusButton: false,
typepass: "<PASSWORD>",
image: '',
classes: {
cardCategoryWhite: {
color: "rgba(255,255,255,.62)",
margin: "0",
fontSize: "14px",
marginTop: "0",
marginBottom: "0"
},
cardTitleWhite: {
color: "#FFFFFF",
marginTop: "0px",
minHeight: "auto",
fontWeight: "300",
fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
marginBottom: "3px",
textDecoration: "none"
}
}
};
this.handleInputChange = this.handleInputChange.bind(this);
this.changeStatus = this.changeStatus.bind(this);
this.onDrop = this.onDrop.bind(this);
this.handleButton = this.handleButton.bind(this);
this.clickNHold = this.clickNHold.bind(this);
this.ClickNHoldEnd = this.ClickNHoldEnd.bind(this);
this.SaveData = this.SaveData.bind(this);
this.toggleModal = this.toggleModal.bind(this);
this.CancelChange = this.CancelChange.bind(this);
}
async componentDidMount() {
var docRef = db.collection("students").doc(localStorage.getItem('DataUser'));
await docRef
.get()
.then(function (doc) {
if (doc.exists) {
DataUser = doc.data();
}
})
.catch(function (error) {
console.log(error);
});
if (Object.entries(DataUser).length !== 0 && DataUser.constructor === Object) {
this.setState({
mssv: DataUser.mssv,
phone: DataUser.phone,
name: DataUser.name,
email: DataUser.email,
birthday: DataUser.birthday,
gender: DataUser.gender,
pass: <PASSWORD>
})
}
var storageRef = storage.ref();
var starsRef = storageRef.child(`users/image/${localStorage.getItem('DataUser')}/${localStorage.getItem('DataUser')}`);
var tmp = '';
await starsRef.getDownloadURL().then(async function (url) {
tmp = url
})
this.setState({ image: tmp })
}
toggleModal() {
this.setState({
modalisOpen: !this.state.modalisOpen
})
}
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
changeStatus() {
this.props.changeStatus(1)
}
onDrop(avatar) {
this.setState({
avatars: this.state.avatars.concat(avatar),
});
}
handleButton() {
this.setState({
status: true,
})
}
clickNHold() {
this.setState({
typepass: "text"
})
}
ClickNHoldEnd() {
this.setState({
typepass: "<PASSWORD>"
})
}
CancelChange() {
this.componentDidMount();
this.setState({
status: true
})
}
SaveData() {
}
handleSubmit(e) {
db.collection("students").doc(localStorage.getItem('DataUser')).update({
mssv: this.state.mssv,
phone: this.state.phone,
name: this.state.name,
email: this.state.email,
birthday: this.state.birthday,
gender: this.state.gender,
password: this.state.pass
})
this.setState({
modalisOpen: !this.state.modalisOpen,
status: true
})
}
render() {
const status = this.state.status;
const statusButton = this.state.statusButton;
var girdChange;
var personresult;
var checkperson = parseInt(this.state.mssv);
if (parseInt(checkperson / 1000000) === 102) {
personresult = <span>Sinh viên: </span>
} else {
personresult = <span>Giảng viên: </span>
}
var ButtonChange;
if (statusButton === false) {
ButtonChange = <Button onClick={() => this.setState({ typepass: 'text', statusButton: true })}
style={{ padding: 12 }}
>
<span className="fa fa-fw fa-eye field-icon" /></Button>
}
if (statusButton === true) {
ButtonChange = <Button onClick={() => this.setState({ typepass: 'password', statusButton: false })}
style={{ padding: 12 }}
>
<span className="fa fa-fw fa-eye field-icon" /></Button>
}
if (status === false) {
girdChange = <GridItem xs={12} sm={12} md={8}>
<Card>
<CardHeader color="primary">
<h4 className={this.state.classes.cardTitleWhite}>
Chỉnh sửa thông tin
</h4>
<p className={this.state.classes.cardCategoryWhite}>
Điền thông tin cần chỉnh sửa
</p>
</CardHeader>
<CardBody>
<Form>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="MSSV"
>
Họ và tên:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Name"
placeholder="name"
value={this.state.name}
type="text"
id="name"
name="name"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="Email"
>
Email:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Email"
placeholder="Email"
value={this.state.email}
type="text"
id="email"
name="email"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="Phone"
>
Số điện thoại:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Phone"
placeholder="Phone"
value={this.state.phone}
type="text"
id="phone"
name="phone"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="Birthday"
>
Ngày sinh:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Birthday"
placeholder="Birthday"
value={this.state.birthday}
type="text"
id="birthday"
name="birthday"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="Gender"
>
Giới tính:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Gender"
placeholder="Gender"
value={this.state.gender}
type="text"
id="gender"
name="gender"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label
style={{ fontWeight: 'bold', fontSize: 16, paddingLeft: 0, paddingTop: 8 }}
for="Password"
>
Mật Khẩu:
</Label>
</Col>
<Col sm={8}>
<LabelInput style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}
labelClassName="Password"
placeholder="<PASSWORD>"
value={this.state.pass}
type="text"
id="pass"
name="pass"
onChange={this.handleInputChange}
></LabelInput>
</Col>
</Row>
</FormGroup>
</Form>
</CardBody>
<CardFooter>
<Button sm={5} color="success" onClick={this.toggleModal} style={{ marginLeft: 'auto' }}>Lưu lại</Button>
<Button color="gray" onClick={this.CancelChange}> Huỷ bỏ
</Button>
</CardFooter>
</Card>
</GridItem>;
}
else {
girdChange = <GridItem xs={12} sm={12} md={8}>
<Card>
<CardBody>
<Form onSubmit={this.handleChangeProfile}>
<CardHeader color="primary">
<h4 className={this.state.classes.cardTitleWhite}>
<NAME>ÂN
</h4>
</CardHeader>
<FormGroup></FormGroup>
<FormGroup>
<Row>
<Col sm={4}>
<Label
style={{ fontWeight: 'bold', fontSize: 16 }}
for="MSSV"
>
Mã số sinh viên:
</Label>
</Col>
<Col>
<Label style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.mssv}</Label>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={4}>
<Label for="gender" style={{ fontWeight: 'bold', fontSize: 16 }}>
Họ và tên:
</Label>
</Col>
<Col>
<Label style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.name}</Label>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={4}>
<Label style={{ fontWeight: 'bold', fontSize: 16 }} for="Email">
Email:
</Label>
</Col>
<Col>
<Label style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.email}</Label>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={4}>
<Label for="Phone" style={{ fontWeight: 'bold', fontSize: 16 }}>
Số điện thoại:
</Label>
</Col>
<Col>
<Label style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.phone}</Label>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={4}>
<Label for="gender" style={{ fontWeight: 'bold', fontSize: 16 }}>
Giới tính:
</Label>
</Col>
<Col>
<Label style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.gender}</Label>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col sm={3}>
<Label for="gender" style={{ fontWeight: 'bold', paddingright: 0, paddingTop: 10, fontSize: 16 }}>
Mật khẩu:
</Label>
</Col>
<Col md={5}>
<LabelInput type={this.state.typepass} value={this.state.pass}
onChange={this.handleInputChange}
className="typepassword"
style={{ fontSize: 16, color: 'rgb(97, 95, 95)' }}>{this.state.pass}</LabelInput>
</Col>
<Col>
{ButtonChange}
</Col>
</Row>
</FormGroup>
<div style={{ textAlign: 'right' }}>
<Button color="primary" style={{ display: 'float', fontSize: 16 }} onClick={() => this.setState({ status: false })}>
Chỉnh sửa thông tin
</Button>
</div>
</Form>
</CardBody>
</Card>
</GridItem>;
}
return (
<div>
<Modal id="articleModal" isOpen={this.state.modalisOpen}
toggle={this.toggleModal.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabel" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Xác nhận thông tin</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Bạn chắc chắn muốn thay đổi thông tin cá nhân chứ?
</Form>
</ModalBody>
<ModalFooter>
<Button id="abc" type="submit" color="success" className="success ml-auto" onClick={this.toggleModal.bind(this)} onClick={e => this.handleSubmit(e)}>Xác nhận</Button>{' '}
<Button id="abc" type="Button" className="second" onClick={this.toggleModal.bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<GridContainer>
<GridItem xs={12} sm={12} md={4}>
<Card >
{/* <CardAvatar profile>
<a href="#pablo" onClick={e => e.preventDefault()}>
<img src={avatar} alt="..." />
</a>
</CardAvatar> */}
<UploadImage mssv={this.state.mssv} image={this.state.image}></UploadImage>
<CardBody >
<h4 className={this.state.classes.cardTitle}>{personresult}{this.state.name}</h4>
<h6 className={this.state.classes.cardCategory}>
MSSV: {this.state.mssv}
</h6>
</CardBody>
</Card>
</GridItem>
{girdChange}
</GridContainer>
</div>
);
}
}
const mapStateToProps = state => {
return {
}
}
const mapDispatchToProps = (dispatch, props) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserProfile)<file_sep>/src/views/Base/Tables/Tables.js
import React, { Component } from 'react';
import {
Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem, PaginationLink, Row, TableModal,
ModalBody, ModalHeader, Form, Button, Modal, Table,
ModalFooter,
} from 'reactstrap';
import fire from "../../../config/fire";
const firebase = require("firebase");
const storage = firebase.storage();
// Required for side-effects
require("firebase/firestore");
var db = fire.firestore();
class Tables extends Component {
constructor() {
super()
this.state = {
listCourse: [],
listSinhvien: [],
modalisOpen: false
}
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal() {
this.setState({
modalisOpen: !this.state.modalisOpen
})
}
async componentDidMount() {
var listTmp = [];
var listTmpStudent = [];
await db.collection("courses").get().then(async function (querySnapshot) {
await querySnapshot.forEach(async function (doc) {
await doc.data().idStudent.forEach(async function (dataStudent) {
var docRef = await db.collection("students").doc(dataStudent.id);
await docRef
.get()
.then(async function (doc) {
if (doc.exists) {
listTmpStudent.push(doc.data())
}
})
.catch(function (error) {
console.log(error);
});
if (localStorage.getItem('DataUser') === dataStudent.id) {
await doc.data().idDate.forEach(async function (data) {
var course_tmp = {
id: doc.data().idCourses,
name: doc.data().nameCourses,
day: '',
period: '',
room: '',
giangvien: ''
}
var docRef = db.collection("professors").doc(doc.data().idProfessor.id);
await docRef
.get()
.then(async function (doc) {
if (doc.exists) {
course_tmp.giangvien = doc.data().name;
}
})
.catch(function (error) {
console.log(error);
});
var docRef2 = db.collection("date").doc(data.id);
await docRef2
.get()
.then(async function (doc) {
var docRef3 = db.collection("rooms").doc( doc.data().room.id);
await docRef3
.get()
.then(async function (doc) {
if (doc.exists) {
console.log(doc)
course_tmp.room = doc.data().name;
}
})
.catch(function (error) {
console.log(error);
});
if (doc.exists) {
course_tmp.day = doc.data().day;
course_tmp.period = doc.data().period;
}
console.log(doc.data().room.id);
await listTmp.push(course_tmp)
})
.catch(function (error) {
console.log(error);
});
})
}
})
});
})
this.setState({
listCourse: listTmp,
listSinhvien: listTmpStudent
})
}
isExist = (arr, x) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === x) return true;
}
return false;
}
deduplicate = (arr) => {
let isExist = (arr, x) => arr.includes(x);
let ans = [];
arr.forEach(element => {
if (!isExist(ans, element)) ans.push(element);
});
return ans;
}
render() {
var list = this.state.listCourse;
// var tmp=this.deduplicate(list);
// list.forEach(ele => {
// tmp.forEach(ele_tmp =>{
// if(ele.id===ele_tmp.id){
// ele.day += ele_tmp.day;
// ele.period += ele_tmp.period
// }
// else tmp.push(ele)
// })
// })
console.log(list)
return (
<div className="animated fadeIn">
<Modal id="articleModal" isOpen={this.state.modalisOpen}
toggle={this.toggleModal.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabel" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Danh sách sinh vien</h3>
<ModalBody>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Danh sach scac lop thuc hanh
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>STT</th>
<th>MSSV</th>
<th>Ten Sinh Vien</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{this.state.listSinhvien.map((d, key) => {
return (
<tr key={key}>
<td>{key}</td>
<td>{d.mssv}</td>
<td>{d.name}</td>
<td>{d.email}</td>
</tr>
)
})}
</tbody>
</Table>
</CardBody>
</Card>
</Col>
</Row>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Click de tat
</Form>
</ModalBody>
<ModalFooter>
<Button id="abc" type="Button" className="second" onClick={this.toggleModal.bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Danh sach cac lop thuc hanh
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>STT</th>
<th>Ma hoc phan</th>
<th>Ten hoc phan</th>
<th>Giang vien</th>
<th>Thoi khoa bieu</th>
<th>Danh sach</th>
</tr>
</thead>
<tbody>
{list.map((d, key) => {
return (
<tr key={key}>
<td>{key}</td>
<td>{d.id}</td>
<td>{d.name}</td>
<td>{d.giangvien}</td>
<td>{d.day},{d.period},{d.room}</td>
<td>
<Button sm={5} color="success" onClick={this.toggleModal} style={{ marginLeft: 'auto' }}>Danh sách</Button>
</td>
</tr>
)
})}
</tbody>
</Table>
<nav>
<Pagination>
<PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem>
<PaginationItem active>
<PaginationLink tag="button">1</PaginationLink>
</PaginationItem>
<PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem>
</Pagination>
</nav>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Tables;
<file_sep>/src/views/Base/Students/Students.js
import React, { Component } from 'react';
import {
Badge, Card, CardBody, CardHeader,
Col, Pagination, PaginationItem, PaginationLink, Row, Table,
Form,
FormGroup,
Label,
Modal,
ModalBody,
ModalFooter,
Alert
} from 'reactstrap';
import fire from "../../../config/fire";
import { isTerminatorless } from '@babel/types';
import { Button, Input } from '@material-ui/core';
import Alerts from '../../Notifications/Alerts/Alerts';
const firebase = require("firebase");
const storage = firebase.storage();
// Required for side-effects
require("firebase/firestore");
var db = fire.firestore();
var idfinal = null;
class Students extends Component {
constructor() {
super()
this.state = {
liststudents: [],
modalisOpen: false,
modalisOpenToEdit: false,
modalisOpenToAdd: false,
idstudentCurrent: '',
idNewstudent: idfinal,
birthday: '',
email: '',
name: '',
gender: '',
phone: '',
listCurrentstudent: [],
}
this.toggleModal = this.toggleModal.bind(this);
this.toggleModalEdit = this.toggleModalEdit.bind(this);
this.toggleModalAdd = this.toggleModalAdd.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.GetstudentObject = this.GetstudentObject.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
async componentDidMount() {
var listTmp = this.state.liststudents.slice();
await db.collection("students").get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
var student_tmp = {
id: doc.id,
name: doc.data().name,
birthday: doc.data().birthday,
email: doc.data().email,
gender: doc.data().gender,
phone: doc.data().phone,
}
listTmp.push(student_tmp)
idfinal = Number(student_tmp.id)+1;
});
})
this.setState({
liststudents: listTmp
})
}
handleDelete() {
db.collection("students").doc(this.state.idstudentCurrent).delete().then(function () {
setTimeout(function(){
document.location.reload();
}, 1000)
}).catch(function (error) {
console.error("Error removing document: ", error);
});
}
handleAdd() {
db.collection("students").doc(String(idfinal)).set({
name: this.state.name,
birthday: this.state.birthday,
email: this.state.email,
phone: this.state.phone,
mssv: String(idfinal),
password: "<PASSWORD>"
})
.then(function() {
setTimeout(function(){
document.location.reload();
}, 1000)
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
handleEdit() {
var updatestudent = db.collection("students").doc(this.state.idstudentCurrent);
// Set the "capital" field of the city 'DC'
return updatestudent.update({
"name" : this.state.name,
"birthday": this.state.birthday,
"email": this.state.email,
"gender": this.state.gender,
"phone": this.state.phone
})
.then(function () {
Alert("Document successfully updated!");
setTimeout(function(){
document.location.reload();
}, 1000)
})
.catch(function (error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
}
toggleModal = value => event => {
this.setState({
modalisOpen: !this.state.modalisOpen,
idstudentCurrent: value
})
}
toggleModalEdit = value => event => {
this.setState({
modalisOpenToEdit: !this.state.modalisOpenToEdit,
idstudentCurrent: value
})
}
toggleModalAdd = event => {
this.setState({
modalisOpenToAdd: !this.state.modalisOpenToAdd,
})
}
// GetValueAll = item => {
// this.setState({
// listCurrentstudent : item
// })
// console.log(this.state.listCurrentstudent)
// }
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
GetstudentObject = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
return (
<div className="animated fadeIn">
<Modal id="articleModal" isOpen={this.state.modalisOpen}
toggle={this.toggleModal.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabel" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Xác nhận thông tin</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Bạn chắc chắn muốn xoá thông tin phòng này chứ?
</Form>
</ModalBody>
<ModalFooter>
<Button id="abc" type="submit" color="success" className="success ml-auto"
style={{background: "darkgreen", color: "white"}}
onClick={this.toggleModal("0").bind(this)} onClick={e => this.handleDelete()}>Xác nhận</Button>{' '}
<Button id="abc" type="Button" className="second"
style={{background: "gray", color: "white"}}
onClick={this.toggleModal("0").bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Modal id="articleModalEdit" isOpen={this.state.modalisOpenToEdit}
toggle={this.toggleModalEdit("0").bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabelEdit" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Cập nhật thông tin</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Điền đầy đủ thông tin
</Form>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>Tên sinh viên</th>
<th>Ngày sinh</th>
<th>Địa chỉ email</th>
<th>Giới tính</th>
<th>Số điện thoại</th>
</tr>
</thead>
<tbody onChange={this.GetstudentObject}>
<tr>
<td><Input
labelClassName="Name"
placeholder=""
value={this.state.name}
type="text"
id="name"
name="name"
onChange={this.handleInputChange}
/></td>
<td><Input
labelClassName="birthday"
placeholder=""
value={this.state.birthday}
type="text"
id="birthday"
name="birthday"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="email"
placeholder=""
value={this.state.email}
type="text"
id="email"
name="email"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="gender"
placeholder=""
value={this.state.gender}
type="text"
id="gender"
name="gender"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="phone"
placeholder=""
value={this.state.phone}
type="text"
id="phone"
name="phone"
onChange={this.handleInputChange}/></td>
</tr>
</tbody>
</Table>
</ModalBody>
<ModalFooter>
<Button id="abcEdit" type="submit" color="success" className="success ml-auto"
style={{background: "darkgreen", color: "white"}}
onClick={this.toggleModalEdit("0").bind(this)} onClick={e => this.handleEdit()}>Lưu thay đổi</Button>{' '}
<Button id="abcEdit" type="Button" className="second"
style={{background: "gray", color: "white"}}
onClick={this.toggleModalEdit("0").bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Modal id="articleModalAdd" isOpen={this.state.modalisOpenToAdd}
toggle={this.toggleModalAdd.bind(this)} className={this.props.className}
>
<p></p>
<h3 className="modal-title" id="myModallabelAdd" style={{ fontSize: 24, fontWeight: "bold", paddingLeft: 16 }}>Thêm phòng mới</h3>
<ModalBody>
<Form encType="multipart/form-data" onSubmit={this.handleSubmit} noValidate>
Điền đầy đủ thông tin
</Form>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>Tên <NAME></th>
<th>Ngày sinh</th>
<th>Địa chỉ email</th>
<th>Giới tính</th>
<th>Số điện thoại</th>
</tr>
</thead>
<tbody onChange={this.GetstudentObject}>
<tr>
<td><Input
labelClassName="Name"
placeholder=""
value={this.state.name}
type="text"
id="name"
name="name"
onChange={this.handleInputChange}
/></td>
<td><Input
labelClassName="birthday"
placeholder=""
value={this.state.birthday}
type="text"
id="birthday"
name="birthday"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="email"
placeholder=""
value={this.state.email}
type="text"
id="email"
name="email"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="gender"
placeholder=""
value={this.state.gender}
type="text"
id="gender"
name="gender"
onChange={this.handleInputChange}/></td>
<td><Input
labelClassName="phone"
placeholder=""
value={this.state.phone}
type="text"
id="phone"
name="phone"
onChange={this.handleInputChange}/></td>
</tr>
</tbody>
</Table>
</ModalBody>
<ModalFooter>
<Button id="abcAdd" type="submit" color="success" className="success ml-auto"
style={{background: "darkgreen", color: "white"}}
onClick={this.toggleModalAdd.bind(this)} onClick={e => this.handleAdd()}>Thêm sinh viên</Button>{' '}
<Button id="abcAdd" type="Button" className="second"
style={{background: "gray", color: "white"}}
onClick={this.toggleModalAdd.bind(this)}>Huỷ bỏ</Button>
</ModalFooter>
</Modal>
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Danh sách các sinh viên
</CardHeader>
<CardBody>
<Table hover bordered striped responsive size="sm">
<thead>
<tr>
<th>STT</th>
<th>Tên sinh viên</th>
<th>Ngày sinh</th>
<th>Địa chỉ email</th>
<th>Giới tính</th>
<th>Số điện thoại</th>
</tr>
</thead>
<tbody>
{this.state.liststudents.map((item, i) => {
return <tr key={i} >
<td>{i + 1}</td>
<td>{item.name}</td>
<td>{item.birthday}</td>
<td>{item.email}</td>
<td>{item.gender}</td>
<td>{item.phone}</td>
</tr>
})}
</tbody>
</Table>
<nav>
<Row>
<Col sm={10}>
<Pagination>
<PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem>
<PaginationItem active>
<PaginationLink tag="button">1</PaginationLink>
</PaginationItem>
<PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem>
<PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem>
</Pagination>
</Col>
<Col sm={2}>
</Col>
</Row>
</nav>
</CardBody>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Students;<file_sep>/src/reducers/user.js
import * as types from "../constants/ActionTypes";
//var data = JSON.parse(localStorage.getItem("Data"));
//var initialState = data ? data : [];
var initialState = {};
var myReducer = (state = initialState, action) => {
if (action.type === types.SET_DATA_USER) {
state = action.dataUser;
return state;
}
return state;
};
export default myReducer;
<file_sep>/src/App.js
import React, { Component } from 'react';
import { HashRouter, Route, Switch, Redirect } from 'react-router-dom';
// import { renderRoutes } from 'react-router-config';
import './App.scss';
import { connect } from "react-redux";
import { messaging } from "./init-fcm";
import fire from "../src/config/fire";
const firebase = require("firebase");
const storage = firebase.storage();
// Required for side-effects
require("firebase/firestore");
var db = fire.firestore();
const loading = () => <div className="animated fadeIn pt-3 text-center">Loading...</div>;
// Containers
const DefaultLayout = React.lazy(() => import('./containers/DefaultLayout'));
// Pages
const Login = React.lazy(() => import('./views/Pages/Login'));
const Register = React.lazy(() => import('./views/Pages/Register'));
const Page404 = React.lazy(() => import('./views/Pages/Page404'));
const Page500 = React.lazy(() => import('./views/Pages/Page500'));
// ...
class App extends Component {
async componentDidMount() {
const mssv = localStorage.getItem("DataUser") ? localStorage.getItem("DataUser") : "";
messaging.onMessage((payload) => console.log('Message received. ', payload));
messaging.requestPermission()
.then(async function () {
const token = await messaging.getToken();
console.log("DAY LA sTO KEN", token)
if (mssv !== "") {
await db.collection("students").doc(mssv).update({
tokenWeb: token
})
}
})
navigator.serviceWorker.addEventListener("message", (message) => console.log(message));
if (mssv !== '') {
return (
<Redirect to='/login' />
)
}
}
render() {
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
} else {
console.log('Unable to get psermission to notify.');
}
});
return (
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
<Route exact path="/login" name="Login Page" render={props => <Login {...props} />} />
<Route exact path="/register" name="Register Page" render={props => <Register {...props} />} />
<Route exact path="/404" name="Page 404" render={props => <Page404 {...props} />} />
<Route exact path="/500" name="Page 500" render={props => <Page500 {...props} />} />
<Route path="/" name="Home" render={props => <DefaultLayout {...props} />} />
</Switch>
</React.Suspense>
</HashRouter>
);
}
}
const mapStateToProps = DataInStore => {
return {
dataUser: DataInStore.user
};
};
export default connect(
mapStateToProps,
null
)(App);
<file_sep>/src/action/index.js
import * as types from "../constants/ActionTypes";
import fire from "../config/fire";
require("firebase/firestore");
var db = fire.firestore();
export const setUser = dataUser => {
return {
type: types.SET_DATA_USER,
dataUser: dataUser
};
};
export const getUserBymssv = async (id) => {
var DataUser = {}
var docRef = db.collection("students").doc(id);
await docRef
.get()
.then(function (doc) {
DataUser = doc.data();
})
return dispatch => {
dispatch(getUser(DataUser))
}
}
export const getUser = (user) => {
return {
type: types.GET_DATA_USER,
user: user
};
};
|
49852fa0a913ace9195d0e8c431c6650ffb1eea7
|
[
"JavaScript"
] | 11
|
JavaScript
|
vodinhhung2204/do-an-cnpm-practical-laboratory-management-system
|
0c53cdf9fdec2e6f809a5433e836323de1f89967
|
e24ca8dba6cf83e4df5e68d3f14352d01e582995
|
refs/heads/master
|
<file_sep>var ages = [1, 23, 8, 12, 16]
var ratings = ['G', 'PG', 'M', 'MA']
var minAgeForRating = [0, 9, 12, 15]
|
1c5394b539159425eba33e6e5b8a98ac62445988
|
[
"JavaScript"
] | 1
|
JavaScript
|
cillianbc/js1Homework2
|
a786d5bfc1ea6e952505992dd6cf5cf6d6780136
|
95bc0eb7ef07c411262dd77c02dc26020f573290
|
refs/heads/master
|
<repo_name>RahulhajareOpsFuse/react-native-project<file_sep>/Components/CallApi.js
{/**
Api Call in React-Native:
-Api is chunks of JSON y
-api provides interactions between fronend and backend.
-We always call api under componentDidMountMethod.
*/}
import React from 'react'
import{
View,
Text,FlatList
}from 'react-native'
class CallApi extends React.Component{
constructor()
{
super()
this.state={
data:[]
}
}
componentDidMount(){
this.callApi()
}
async callApi(){
let resp=await fetch('https://reactnative.dev/movies.json')
let respJson=await resp.json()
//console.warn("respIson",respJson)
this.setState({data:respJson})
}
render(){
//console.warn("render",this .state.data)
return(
<View>
<Text style={{fontSize:40}}>
Api Call
</Text>
<FlatList
data={this.state.data} renderItem={({item})=><Text style={{color:'white',fontSize:50}}>{item.title}</Text>}/>
</View>
)
}
}
export default CallApi;<file_sep>/Components/State.js
{/*
State :
State is specially use to change the data from Form.
*/}
import React from 'react'
import {
View,
Text,
Button
} from 'react-native'
class State extends React.Component{
constructor(){
super()
this.state={
data:"This is a State data"
}
}
test(){
this.setState({data:"new State data"})
}
render(){
return(
<View>
<Text style={{fontSize:50}}>{this.state.data}</Text>
<Button title="Update State" onPress={()=>{this.test() }}/>
</View>
);
}
}
export default State;<file_sep>/Components/Props.js
{/*
Props:-
We can trsnsfer data between two components through the props.
props is a propertie or data(present inside functions(components)).
*/}
import React from 'react'
import {
Text,
View,
Button
}from 'react-native'
import Home from './Home'
const Props=( props)=>{
return(
<View>
<Home/>
</View>
)
}
export default Props;<file_sep>/Components/Home.js
{/*
Props:-
We can trsnsfer data between two components through the props.
props is a propertie or data(present inside functions(components)).
eg: button, image have props like title ,source, onPress etc.
*/}
import React from 'react'
import {
Text,
View,
Button
}from 'react-native'
const Home=(props)=>{
console.warn(props)
return(
<View>
<Text style={{fontSize:50, color:'red'}}>{props.data}</Text>
<Button title="press me"/>
</View>
)
}
export default Home;<file_sep>/Components/ExDidMountMethod.js
{/*
componentDidMount();
-this method is always called at the end of react-native lifecycle method.
-Basically use to call API under this method. becuse all html elements are set properly.
*/}
import React from 'react'
import{
View,
Text
}from 'react-native'
import App from '../App'
class ExDidMountMethod extends React.Component{
constructor(){
super()
//console.warn("Constructor Method is called")
this.state={
data:""
}
}
componentDidMount(){
//always use to fetch api under this method.
//let fetch api here.
this.setState({data:"Data from Api and componentDidMount() Method"})
}
render(){
return(
<View>
<Text style={{fontSize:30}}>
{this.state.data}
</Text>
</View>
);
}
}
export default ExDidMountMethod;
<file_sep>/Components/Login.js
import React from 'react'
import {
View,
Text
}from 'react-native'
const Login=()=>{
return(
<View>
<Text>Login Form</Text>
</View>
)
}
//to export screen
export default Login;<file_sep>/App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react'
import {
StyleSheet,
View,Text,
} from 'react-native';
import ReactVal from './Components/ReactVal';
const App=()=>{
//const data="<NAME> from Newasa"
return(
<View>
{/*<Home data={data}/> */}
{/*<State/>*/}
{/*<ExLyfecycle/>*/}
{/* <ExFlex/>*/}
{/*<ExDidMountMethod/>*/}
{/*<ExFlatlist/>*/}
{/* <CallApi/>*/}
<ReactVal/>
</View>
);
};
export default App;
<file_sep>/Components/Nav.js
import React from 'react'
import{
View,Text
}from 'react-native'
import{
createAppContainer
} from 'react-navigation'
import {
createStackNavigator
}from 'react-navigation-stack'
import App from '../App'
class Nav extends React.Component{
constructor(){
super()
}
render(){
return(
<View>
<Text style={{fontSize:80}}>React navigation</Text>
</View>
)
}
}
const appNavigator=createStackNavigator({
Home:{
screen:App
}
})
export default createAppContainer(appNavigator);<file_sep>/Components/App1.js
{/*
State :
State is specially use to change the data from Form.
*/}
import React from 'react'
import {
View,
Text,
Button
} from 'react-native'
{/*class App1 extends React.Component{
constructor(){
super()
this.state={
data:"some app data"
}
}
render(){
return(
<View>
<Text>{this.state.data}</Text>
</View>
);
}
}
*/}
import ExLyfecycle from ''
const App=()=>{
return(
<View>
<ExLyfecycle/>
</View>
)
}
export default App1;
|
f223d8da1ba63ca562f79c6c0f11fa89c80a35ec
|
[
"JavaScript"
] | 9
|
JavaScript
|
RahulhajareOpsFuse/react-native-project
|
17d7b5014b61eefd8cef809b9d1170b1ac43ccca
|
c4d57917243ae35c300a357525337bfd327f2860
|
refs/heads/master
|
<repo_name>caiovlima/WDGFrontEndTest<file_sep>/wdg-app/src/pages/Users/styles.js
import styled from "styled-components";
export const Div = styled.div`
max-width: 500px;
margin: 20px auto 0;
padding: 0 20px;
article {
background: #fff;
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
margin-bottom: 20px;
}
article p{
font-size: 16px;
color: #999;
margin-top: 5px;
line-height: 24px;
}
article a {
height: 42px;
border-radius: 5px;
border: 2px solid #da552d;
background: none;
margin-top: 10px;
color: #da552d;
font-weight: bold;
font-size: 16px;
text-decoration: none;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.2s;
}
article a:hover {
background: #da552d;
color: #fff;
}
p {
font-weight: bold;
}
strong {
padding-right: 5px;
padding-left: 20px;
}
`;
export const Actions = styled.div`
display: flex;
justify-content: space-between;
margin-bottom: 20px;
button {
padding: 10px;
border-radius: 5px;
border: 0;
background: #da552d;
color: #fff;
font-size: 16px;
font-weight: bold;
cursor: pointer;
}
button:hover{
opacity: 0.7;
}
button[disabled]{
opacity: 0.5;
cursor: default;
}
`;<file_sep>/wdg-app/src/pages/Users/edit.js
import React, { Component } from "react";
import { Button, Input, FormGroup } from "reactstrap";
import api from "../../services/api";
import { Div, Actions } from "./styles";
export default class UsersEdit extends Component {
state = {
user: {}
};
async componentDidMount() {
const { id } = this.props.match.params;
const response = await api.get(`/api/users/${id}`);
this.setState({ user: response.data.data });
}
saveUser = async () => {
try {
const { id } = this.props.match.params;
const { user } = this.state.user;
await api.put(`/api/users/${id}`, user);
this.props.history.push("/users", user);
} catch (error) {
alert(`Falha ao atualizar usuario. Erro: ${error}`)
}
};
deleteUser = async () => {
try {
const { id, user } = this.props.match.params;
await api.delete(`/api/users/${id}`);
this.props.history.push("/users", user);
} catch (error) {
alert(`Falha ao deletar usuario. Erro: ${error}`)
}
};
handleFirstName = (event) => {
this.setState({
user: {
...this.state.user,
first_name: event.currentTarget.value
}
});
}
handleLastName = (event) => {
this.setState({
user: {
...this.state.user,
last_name: event.currentTarget.value
}
});
}
render() {
const { user } = this.state;
return (
<Div>
<form>
<article>
<h1>
{user.first_name} {user.last_name}
</h1>
<FormGroup>
<Input
type="text"
name="first_name"
placeholder="Nome"
onChange={this.handleFirstName}
/>
</FormGroup>
<FormGroup>
<Input
type="text"
name="last_name"
placeholder="Sobrenome"
onChange={this.handleLastName}
/>
</FormGroup>
</article>
<Actions>
<Button color="success" onClick={this.saveUser}>Salvar</Button>
<Button color="danger" onClick={this.deleteUser}>Deletar</Button>
</Actions>
</form>
</Div>
);
}
}<file_sep>/README.md
Esse projeto foi criado para o desafio FrontEnd Developer Test para a empresa [WDG](https://www.wdgautomation.com/).
## Instruções
1 - Certifique-se que tenha a última versão do node instalado. [NODE](https://nodejs.org/en/)
2 - Clone/Baixe o repositório em seu computador.
3 - Via terminal, vá até o diretório onde baixou ou clonou o repositório
4 - Digite os seguintes comandos
### `npm install`
O comando irá instalar as dependências necessárias
### `npm start`
O comando irá subir a aplicação na porta 3000 [http://localhost:3000](http://localhost:3000)
#Yarn
Uma alternativa ao npm seria o yarn
1 - Baixe o Yarn de acordo com seu SO [Yarn](https://yarnpkg.com/en/docs/getting-started)
**Obs: É necessário o Node instalado
2 - Via terminal, vá até o diretório onde baixou ou clonou o repositório
4 - Digite os seguintes comandos
### `yarn install`
O comando irá instalar as dependências necessárias
### `yarn start`
O comando irá subir a aplicação na porta 3000 [http://localhost:3000](http://localhost:3000)
<file_sep>/wdg-app/src/pages/NotFound/index.js
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import { Form, Container } from "./styles";
class NotFound extends Component {
render() {
return (
<Container>
<h1>404</h1>
<h1>Ops! Algo deu errado</h1>
<p>x____x</p>
<Link to="/login">Voltar para o Login</Link>
</Container>
);
}
}
export default withRouter(NotFound);
|
6a97d202e4942f5d936770d3d8f9c4b2e589c2a8
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
caiovlima/WDGFrontEndTest
|
60142c74ce9cb67dc5c1c97f3bd20b4192188ed9
|
d85909c6864dc281e6c30d18769fa31c5e6c38bc
|
refs/heads/master
|
<repo_name>AchrafAsh/readwise-clone<file_sep>/highlights.py
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from book import Book
def open_amazon():
browser = webdriver.Chrome()
browser.get("https://read.amazon.com/notebook")
return browser
def sign_in(browser, account_email, account_password):
signin = ActionChains(browser)
signin.click(browser.find_element_by_css_selector("#ap_email"))
signin.send_keys(account_email)
signin.click(browser.find_element_by_css_selector("#ap_password"))
signin.send_keys(<PASSWORD>_password)
signin.click(browser.find_element_by_css_selector("#a-autoid-0 > span"))
signin.perform()
def get_library():
account_email = # enter your email account
account_password = # enter your password
browser = open_amazon()
sign_in(browser, account_email, account_password)
book_shelve = browser.find_element_by_xpath(
'//*[@id="kp-notebook-library"]')
books = book_shelve.find_elements_by_xpath(
'.//div[@class="a-row kp-notebook-library-each-book a-color-base-background"]')
books += book_shelve.find_elements_by_xpath(
'.//div[@class="a-row kp-notebook-library-each-book"]')
library = []
for book in books:
title = book.find_element_by_xpath('.//h2').text.encode('utf-8')
author = book.find_element_by_xpath('.//p').text.encode('utf-8')
actions = ActionChains(browser)
actions.click(book).perform()
timeout = 5
try:
element_present = EC.presence_of_element_located(
(By.ID, 'kp-notebook-highlights-count'))
WebDriverWait(browser, timeout).until(element_present)
highlights_count = int(browser.find_element_by_id(
'kp-notebook-highlights-count').text)
except TimeoutException:
print("Timed out waiting for page to load")
book_highlights = []
if highlights_count > 0:
highlights = browser.find_elements_by_id("highlight")
for highlight in highlights:
book_highlights.append(highlight.text.encode('utf-8'))
library.append(Book(title, author, book_highlights))
browser.quit()
return library
<file_sep>/book.py
class Book:
def __init__(self, title, author, highlights):
self._title = title
self._author = author
self._highlights = highlights
def get_title(self):
return self._title
def get_author(self):
return self._author
def get_highlights(self):
return self._highlights
def set_title(self, new_title):
self._title = new_title
def set_author(self, new_author):
self._author = new_author
def add_highlight(self, new_highlight):
self._highlights.append(new_highlight)
<file_sep>/send_email.py
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from highlights import get_library
s = smtplib.SMTP(host='smtp.office365.com', port=587)
#s = smtplib.SMTP(host='smtp.gmail.com', port=465) for gmail address
s.starttls()
email_address = # enter the email address from which the mail will be sent
password = # enter the password of this address
#login to your email account
s.login(email_address, passsword)
# create a message
msg = MIMEMultipart()
message = ""
library = get_library()
for book in library:
if book.get_highlights():
message += str(book.get_title().decode("utf-8")) + '\n'
message += str(book.get_author().decode("utf-8")) + '\n\n'
for highlight in book.get_highlights():
message += str(highlight.decode("utf-8")) + '\n'
message += '_________________________________' + '\n'
# setup the parameters of the message
msg['From'] = email_address
msg['To'] = email_address # you can change this address to the address you want to receive the email
msg['Subject']= "Your daily highlights" # change the subject of the email if you want
# add in the message body
msg.attach(MIMEText(message))
# send the message via the server set up earlier.
s.send_message(msg)
print('The email has been successfully sent')
del msg
s.quit()
<file_sep>/README.md
# readwise-clone
The purpose of this project is to retrieve one's higlights from kindle (read.amazon) and send an email composed of these highlights
I'm using python, with the selenium library to search within chrome browser automatically. I then use the SMP library to send the email.
It works fine, but the goal is to check the highlights and send an email regularly.
To do so I should either run the python script and the program emails in advance, or somehow run the current script regularly somehow from a remote server so that it can send an email without having me doing anything. (I think readwise is using a chrome extension to do that)
|
f3eca7ebcf594be56769fa91404b9276eeba3f1b
|
[
"Markdown",
"Python"
] | 4
|
Python
|
AchrafAsh/readwise-clone
|
8c9f2e95382b56de99e76a37e54deb333de97535
|
aae88bbebaf0c0e63dd5c26fdce1b4ce28787aac
|
refs/heads/master
|
<repo_name>Alex-gits/Homework-12<file_sep>/app.js
// Создать функцию, которая возвращает промис. Функция принимает два аргумента - время, через которое промис должен выполниться, и значение, с которым промис будет выполнен.
// function promiseCreator(...) {...}
// const prom = promiseCreator(500, 'Ok!');
// prom.then(console.log);
// Ok!
function promiseCreator(value, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value)
}, time);
})
}
const prom = promiseCreator('OK!', 2000);
prom.then((value) => console.log(value));
// -----------------------------------------------------------------------------------------------------
// Переписать данную функцию на fetch и промисы
function http() {
return {
get(url, cb) {
try {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.addEventListener('load', () => {
if (Math.floor(xhr.status / 100) !== 2) {
cb(`Error. Status code: ${xhr.status}`, xhr);
return;
}
const response = JSON.parse(xhr.responseText);
cb(null, response);
});
xhr.addEventListener('error', () => {
cb(`Error. Status code: ${xhr.status}`, xhr);
});
xhr.send();
} catch (error) {
cb(error);
}
},
post(url, body, headers, cb) {
try {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.addEventListener('load', () => {
if (Math.floor(xhr.status / 100) !== 2) {
cb(`Error. Status code: ${xhr.status}`, xhr);
return;
}
const response = JSON.parse(xhr.responseText);
cb(null, response);
});
xhr.addEventListener('error', () => {
cb(`Error. Status code: ${xhr.status}`, xhr);
});
if (headers) {
Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});
}
xhr.send(JSON.stringify(body));
} catch (error) {
cb(error);
}
},
};
}
// Первый способ:
function http2() {
return {
get(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.addEventListener('load', () => resolve(JSON.parse(xhr.responseText)));
xhr.addEventListener('error', () => reject({ status: xhr.status, url }));
});
},
post(url, body) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.addEventListener('load', () => resolve(JSON.parse(xhr.responseText)));
xhr.addEventListener('error', () => reject({ status: xhr.status, url }));
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(body));
});
},
};
}
const ajaxRequests = http2();
const newItem = {
name: 'Alex',
email: '<EMAIL>',
username: 'Time',
phone: 404812323,
website: 'test.test'
};
ajaxRequests.post('https://jsonplaceholder.typicode.com/users', newItem)
.then(res => console.log(res))
.catch(err => console.log(err));
// Второй способ. Более короткий:
function getRequest(url, method, body) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.addEventListener('load', () => resolve(JSON.parse(xhr.responseText)));
xhr.addEventListener('error', () => reject({ status: xhr.status, url }));
if (method === 'get') {
xhr.send();
} else {
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(body));
}
});
}
const newUser = {
name: 'Alex',
email: '<EMAIL>',
username: 'Time',
phone: 404812323,
website: 'test.test'
};
getRequest('https://jsonplaceholder.typicode.com/users', 'post', newUser)
.then(res => console.log(res))
.catch(err => console.log(err));
// Через fetch:
function fetchFnc() {
return {
get(url) {
return Promise.resolve().then(() => {
return fetch(url).then(res => res.json());
})
},
post(url, item) {
return Promise.resolve().then(() => {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(item)
}).then(res => res.json());
})
},
};
}
const fetchRequest = fetchFnc();
const newObj = {
name: 'Alex',
email: '<EMAIL>',
username: 'Time',
phone: 404812323,
website: 'test.test'
};
fetchRequest.post('https://jsonplaceholder.typicode.com/users', newObj)
.then(res => console.log(res))
.catch((err) => console.log(err));
// Или более простой вариант:
function fetchFnc2() {
return {
get(url) {
return fetch(url).then(res => res.json());
},
post(url, item) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(item)
}).then(res => res.json());
},
};
}
|
d11d275e3128698dc436a700b7215b29e8e059f5
|
[
"JavaScript"
] | 1
|
JavaScript
|
Alex-gits/Homework-12
|
80584c05f4b0cd6906684b660a71c2a7fccdc9ae
|
7f571f7c9acf6d6bed404e6882318b80f428cdbb
|
refs/heads/master
|
<file_sep>/**
*
*/
package com.bbva.capx.dto.calculator.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.bbva.capx.dto.viajes.DtoIn;
import junit.framework.Assert;
/**
* @author root
*
*/
public class DtoIntTest {
@Before
public void starting() {
String pruebaCiudad;
int HashcodePrueba;
String PruebaOperador;
boolean prueba;
DtoIn base = new DtoIn();
base.setOriginPoint("Bogota");
base.setDestinationPoint("Medellin");
pruebaCiudad = base.getDestinationPoint();
pruebaCiudad = base.getOriginPoint();
HashcodePrueba = base.hashCode();
prueba = base.equals(base);
}
@Test
public void testToString(){
DtoIn base = new DtoIn();
Assert.assertEquals(base.toString(), "ViajeDataIn [originPoint=null, destinationPoint=null]");
}
@Test
public void testToEquals() {
DtoIn entrada1 = new DtoIn();
DtoIn entrada2 = new DtoIn();
entrada1.equals(entrada2);
Assert.assertEquals(entrada1, entrada2);
DtoIn entrada3 = new DtoIn();
entrada3.setOriginPoint("Bogota");
entrada3.setDestinationPoint("Medellin");
DtoIn entrada4 = new DtoIn();
entrada4.setOriginPoint("Cali");
entrada4.setDestinationPoint("Bucaramanga");
entrada3.equals(entrada4);
entrada3.equals(null);
entrada3.equals("Hola mundo");
DtoIn entrada5 = new DtoIn();
entrada5.setOriginPoint("Pasto");
entrada5.setDestinationPoint("Manizales");
entrada3.equals(entrada5);
int Hash = entrada5.hashCode();
}
}
<file_sep>package com.bbva.capx.dto.viajes;
import com.bbva.apx.dto.AbstractDTO;
public class DtoDistance extends AbstractDTO {
/**
*
*/
private static final long serialVersionUID = -6361412813752655174L;
private String text;
private Integer value;
/**
*
*/
public DtoDistance() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the value
*/
public Integer getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(Integer value) {
this.value = value;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((text == null) ? 0 : text.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DtoDistance other = (DtoDistance) obj;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "DtoDistance [text=" + text + ", value=" + value + "]";
}
}
<file_sep>package com.bbva.capx.dto.calculator.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.bbva.capx.dto.viajes.DtoOut;
import junit.framework.Assert;
/**
* @author root
*
*/
public class DtoOutTest {
@Before
public void starting() {
String pruebaResultado;
int HashcodePrueba;
String PruebaOperador;
boolean prueba;
DtoOut base = new DtoOut();
base.setDistance("400 km");
pruebaResultado = base.getDistance();
base.setTime("2 horas");
pruebaResultado = base.getTime();
HashcodePrueba = base.hashCode();
prueba = base.equals(base);
}
@Test
public void testToString(){
DtoOut base = new DtoOut();
Assert.assertEquals(base.toString(), "ViajeDataOut [distance=null, time=null]");
}
@Test
public void testToEquals() {
DtoOut salida1 = new DtoOut();
DtoOut salida2 = new DtoOut();
salida1.equals(salida2);
Assert.assertEquals(salida1, salida2);
DtoOut salida3 = new DtoOut();
salida3.setDistance("400 km");
DtoOut salida4 = new DtoOut();
salida4.setTime("2 horas");
salida3.equals(salida4);
salida3.equals(salida3);
salida3.equals(null);
salida3.equals("Hola mundo");
}
}
<file_sep>package com.bbva.capx.dto.viajes;
import com.bbva.apx.dto.AbstractDTO;
public class DtoIn extends AbstractDTO{
/**
*
*/
private static final long serialVersionUID = -8511523837024284821L;
private String originPoint;
private String destinationPoint;
/**
*
*/
public DtoIn() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return the originPoint
*/
public String getOriginPoint() {
return originPoint;
}
/**
* @param originPoint the originPoint to set
*/
public void setOriginPoint(String originPoint) {
this.originPoint = originPoint;
}
/**
* @return the destinationPoint
*/
public String getDestinationPoint() {
return destinationPoint;
}
/**
* @param destinationPoint the destinationPoint to set
*/
public void setDestinationPoint(String destinationPoint) {
this.destinationPoint = destinationPoint;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ViajeDataIn [originPoint=" + originPoint + ", destinationPoint=" + destinationPoint + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((destinationPoint == null) ? 0 : destinationPoint.hashCode());
result = prime * result + ((originPoint == null) ? 0 : originPoint.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DtoIn other = (DtoIn) obj;
if (destinationPoint == null) {
if (other.destinationPoint != null)
return false;
} else if (!destinationPoint.equals(other.destinationPoint))
return false;
if (originPoint == null) {
if (other.originPoint != null)
return false;
} else if (!originPoint.equals(other.originPoint))
return false;
return true;
}
}
<file_sep>package com.bbva.capx.dto.viajes;
import com.bbva.apx.dto.AbstractDTO;
public class DtoElement extends AbstractDTO {
/**
*
*/
private static final long serialVersionUID = -102752557642754823L;
private DtoDistance distance;
private DtoDuration duration;
private String status;
/**
*
*/
public DtoElement() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return the distance
*/
public DtoDistance getDistance() {
return distance;
}
/**
* @param distance the distance to set
*/
public void setDistance(DtoDistance distance) {
this.distance = distance;
}
/**
* @return the duration
*/
public DtoDuration getDuration() {
return duration;
}
/**
* @param duration the duration to set
*/
public void setDuration(DtoDuration duration) {
this.duration = duration;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((distance == null) ? 0 : distance.hashCode());
result = prime * result + ((duration == null) ? 0 : duration.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DtoElement other = (DtoElement) obj;
if (distance == null) {
if (other.distance != null)
return false;
} else if (!distance.equals(other.distance))
return false;
if (duration == null) {
if (other.duration != null)
return false;
} else if (!duration.equals(other.duration))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "DtoElement [distance=" + distance + ", duration=" + duration + ", status=" + status + "]";
}
}
<file_sep>package com.bbva.capx.dto.viajes;
import java.util.List;
import com.bbva.apx.dto.AbstractDTO;
public class DTORow extends AbstractDTO {
/**
*
*/
private static final long serialVersionUID = -6267121875699765633L;
private List<DtoElement> elements;
/**
*
*/
public DTORow() {
super();
}
/**
* @return the elements
*/
public List<DtoElement> getElements() {
return elements;
}
/**
* @param elements the elements to set
*/
public void setElements(List<DtoElement> elements) {
this.elements = elements;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((elements == null) ? 0 : elements.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DTORow other = (DTORow) obj;
if (elements == null) {
if (other.elements != null)
return false;
} else if (!elements.equals(other.elements))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "DTORow [elements=" + elements + "]";
}
}
|
849efb7f8b74e290286d4afabe7199ba5566a463
|
[
"Java"
] | 6
|
Java
|
josenchez69/Curso-APX
|
6fef7e4bad186ac5b897e8aea0694afa787a41ec
|
bc0772307f9e2cc17620a9cf4ec8a657e54e0efe
|
refs/heads/master
|
<repo_name>CTMoney/Scraper-Mongoose<file_sep>/routes/api-routes.js
const axios = require("axios"),
cheerio = require("cheerio"),
db = require("../models")
let util = require('util')
module.exports = function (app) {
app.get("/scrape", (req, res) => {
axios.get("https://old.reddit.com/r/worldnews/", {
validateStatus: function (status) {
return status < 201; // Reject only if the status code is greater than or equal to 201
}
}).then(response => {
const $ = cheerio.load(response.data)
console.log($)
$("div.top-matter").each((i, element) => {
let result = {}
result["headline"] = $(this)
.children("p.title a")
.text();
console.log(result)
})
res.send("Scraped!")
}).catch(err => {
if (err.response) {
// console.log(err.response.data)
console.log(err.response.status)
console.log(err.response.headers)
}
})
})
app.get("/article/:id", (req, res) => {
db.Article.findById(req.params.id)
.populate("User")
})
}<file_sep>/server.js
const express = require("express"),
logger = require("morgan"),
mongoose = require("mongoose"),
exphbs = require("express-handlebars"),
PORT = process.env.PORT || 3000,
app = express()
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/mongoHeadlines"
app.use(logger("dev"))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(express.static("public"))
app.engine("handlebars", exphbs({ defaultLayout: "main" }))
app.set("view engine", "handlebars")
mongoose.connect(MONGODB_URI, { useNewUrlParser: true })
require("./routes/html-routes.js")(app)
require("./routes/api-routes.js")(app)
app.listen(PORT, () => console.log(`Running on localhost:${PORT}`))
<file_sep>/models/userModel.js
const mongoose = require("mongoose")
let Schema = mongoose.Schema;
let UserSchema = new Schema({
"username": {
type: String,
required: true,
unique: true
},
"password": {
type: String,
required: true,
minLength: 6,
maxLength: 24,
match: {
args: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#!@#$%^&*()~`=+_])[A-Za-z\d!@#$%^&*()~`=+_]{8,128}$/g,
msg: 'Please enter a password with atleast one of each: lowercase letter, uppercase letter, number, and special character'
}
}
})
let User = mongoose.model("User", UserSchema)
module.exports = User
|
3c60b98514818a4d76a8d14c24aa8e29655f7873
|
[
"JavaScript"
] | 3
|
JavaScript
|
CTMoney/Scraper-Mongoose
|
f608afc8c069911119175d43f77f5bafd743ad52
|
d8c21de9fac3ad950fc4777b865c8eedca7d9ac2
|
refs/heads/main
|
<file_sep># music_predicter
It's not my own idea.
It would predict your music taste by your age and gender. It's so basic. I couldn't finish it, because i have some problem with visual studio.
<file_sep>import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import joblib
# music_data = pd.read_csv('music.csv')
# X = music_data.drop(columns=['genre'])
# y = music_data['genre']
# model = DecisionTreeClassifier()
# model.fit(X, y)
model = joblib.load( 'music-recommender.joblib')
predictions = model.predict([[21, 1]])
predictions
<file_sep>import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
music_data = pd.read_csv('music.csv')
X = music_data.drop(columns=['genre'])
y = music_data['genre']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = accuracy_score(y_test, predictions)
score
|
adb9b3889d49978800a6a55c50b3b668c7716e4c
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
Kristofka995/music_predicter
|
c4c80be53e46ce99f7c744c6211be4c3a29c1360
|
896ced9df279603d6ae22a90d83feb85a2904b0f
|
refs/heads/master
|
<repo_name>pramodith/VERAClassifier<file_sep>/create_dataset.py
import json
def create_dataset(filename):
x_dict=[]
with open(filename,'r') as f:
text=f.read()
text=text.split(".")
for line in text:
tmp={}
tmp['x']=line
tmp['y']="other"
x_dict.append(tmp)
with open("datasets/cheetahs.json",'w') as f:
json.dump(x_dict,f,indent=3)
create_dataset("Wikipedia/cheetahs.txt")<file_sep>/NeuralNet.py
import torch
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk import download
import torch.nn as nn
import torch.autograd as autograd
import torch.optim as optim
import torch.nn.functional as F
import time
from collections import defaultdict
class CBOW(nn.Module):
def __init__(self,context_size=2, embedding_size=50, vocab_size=None):
super(CBOW,self).__init__()
self.embeddings = nn.Embedding(vocab_size+1, embedding_size)
self.linear1 = nn.Linear(embedding_size, vocab_size+1)
def forward(self, inputs):
lookup_embeds = self.embeddings(inputs)
embeds = lookup_embeds.sum(dim=0)
out = self.linear1(embeds)
out = F.log_softmax(out)
return out
def make_context_vector(self,context,word_to_index):
indexes=[word_to_index[x] for x in context]
tensor = torch.LongTensor(indexes)
if torch.cuda.is_available():
tensor=tensor.cuda()
return autograd.Variable(tensor)
class NeuralNet():
Context_size=2
EMBEDDING_SIZE=50
def __init__(self):
self.vocab=None
self.word_set=set()
self.words=[]
self.X=[]
self.word_to_index={}
self.index_to_word={}
self.embeddings=None
self.linear1=None
def preprocess(self,filename):
with open(filename,'r') as f:
wiki_text=f.read()
stopWords = set(stopwords.words('english'))
words = word_tokenize(wiki_text)
wordsFiltered = []
for w in words:
if w not in stopWords:
wordsFiltered.append(w)
def file_to_set(self,filename):
with open(filename,'r')as f:
word_set=f.read().split(" ")
return word_set
def word_to_index_convert(self,files_list):
for file in files_list:
raw_words=(self.file_to_set(file))
self.words.extend(raw_words)
self.word_set=self.word_set.union(set(raw_words))
self.vocab=len(self.word_set)
word_to_index={word:cnt+1 for cnt,word in enumerate(list(self.word_set))}
self.word_to_index=word_to_index
return word_to_index
def index_to_word(self,word_to_index):
index_to_word={word_to_index[x]:x for x in word_to_index.keys()}
index_to_word=defaultdict(int,index_to_word)
self.index_to_word=index_to_word
return index_to_word
def create_dataset(self):
global Context_size
Context_size=2
for i in range(Context_size,len(self.words)-Context_size):
data=[self.words[i-2],self.words[i-1],self.words[i+1],self.words[i+2]]
target=self.words[i]
self.X.append((data,target))
n=NeuralNet()
n.word_to_index_convert(["Wikipedia/sharks_wikipedia.txt","Wikipedia/cheetahs.txt"])
n.create_dataset()
def train_model():
Context_size=2
EMBEDDING_SIZE=50
loss_func = nn.CrossEntropyLoss()
module=CBOW(Context_size, embedding_size=EMBEDDING_SIZE, vocab_size=n.vocab)
module= module.cuda()
optimizer = optim.SGD(module.parameters(), lr=0.01)
for epoch in range(100):
total_loss = 0
if epoch%10==0:
time.sleep(5)
for context, target in n.X:
context_var = module.make_context_vector(context,n.word_to_index)
module.zero_grad()
log_probs=module(context_var)
if not torch.cuda.is_available():
loss = loss_func(log_probs.unsqueeze(0), autograd.Variable(
torch.LongTensor([n.word_to_index[target]])))
else:
loss = loss_func(log_probs.unsqueeze(0), autograd.Variable(
torch.LongTensor([n.word_to_index[target]]).cuda()))
loss.backward()
optimizer.step()
total_loss += loss.data
print("Epoch is "+str(epoch))
print(total_loss)
torch.save(module.state_dict(),"word2vec_50.pkl")
train_model()
<file_sep>/Wikipedia.py
import wikipedia
import sys
import codecs
class Wikipedia:
def __init__(self):
pass
def get_wikipedia_page(self,species_name):
sharks=wikipedia.page(species_name)
with open("cheetahs.txt",'w') as f:
c=sharks.content.encode('utf-8')
f.write(str(c))
w=Wikipedia()
w.get_wikipedia_page("cheetah")<file_sep>/CNN.py
import torch
from torch import backends
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import dataloader
import numpy as np
from torch.autograd import Variable
from collections import defaultdict
import json
import time
class CNN(nn.Module):
def __init__(self):
super(CNN,self).__init__()
self.voacb_size=5304
self.batch_size=1
self.num_filters=3
self.word_embed=torch.load("word2vec.pkl")
self.in_channel=1
self.filter_sizes=[1,2,3]
self.embedding_length=200
self.number_classes=4
self.embed = nn.Embedding(self.voacb_size + 1, self.embedding_length)
#self.embed.weight.data.copy_(torch.from_numpy(self.word_embed.weight.data))
#self.embed.weight.requires_grad=False
self.conv1=nn.ModuleList([nn.Conv2d(in_channels=self.in_channel,out_channels=self.num_filters,kernel_size=(x,self.embedding_length)) for x in self.filter_sizes])
self.dropout=nn.Dropout(p=0.5)
self.fc=nn.Linear(self.num_filters*len(self.filter_sizes),self.number_classes)
def forward(self,input_x):
x = self.embed(input_x)
x=x.unsqueeze(1)
x = [F.relu(conv(x)).squeeze(3) for conv in self.conv1]
x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x]
x = torch.cat(x, 1)
x = self.dropout(x) # (batch_size,len(kernel_sizes)*num_kernels)
logit = F.log_softmax(self.fc(x)) # (batch_size, num_aspects)
return logit
#model=CNN()
def build_word_idx(filenames):
word_to_index={}
for file in filenames:
with open(file,'r') as f:
lines=f.read()
lines=list(set(lines.split(" ")))
for x in lines:
word_to_index[x]=len(word_to_index)+1
word_to_index=defaultdict(int,word_to_index)
return word_to_index
word_to_index=build_word_idx(["Wikipedia/sharks_wikipedia.txt","Wikipedia/cheetahs.txt"])
print(len(word_to_index))
all_classes=["other","eats","habitat","lifespan"]
def create_dataset(filenames):
X=[]
y=[]
ind=-1
for file in filenames:
with open(file,'r') as f:
doc_dict=json.load(f)
for cnt,sent in enumerate(doc_dict):
X.append([word_to_index[ind] for ind in sent['x'].split(" ")])
ind+=1
while len(X[ind])<50:
X[ind].append(5305)
if len(X)>50:
X[ind]=X[ind][:50]
y.append(all_classes.index(sent['y']))
return X,y
X,y=create_dataset(["datasets/sharks.json","datasets/cheetahs.json"])
def train_model(X,y,epochs=100):
cnt=0
model = CNN()
loss_fn = nn.NLLLoss()
loss_accumulated = 0
model=model.cuda()
#trainloader = torch.utils.data.DataLoader(X, batch_size=32, shuffle=True, num_workers=8)
#trainloader_label=torch.utils.data.DataLoader(y, batch_size=32, shuffle=True, num_workers=8)
optimizer = torch.optim.SGD(model.parameters(),lr=0.05,momentum=0.5)
for i in range(epochs):
for data,label in zip(X,y):
data, target = Variable(torch.LongTensor([data])).cuda(), Variable(torch.LongTensor([label])).cuda()
model.zero_grad()
logit=model(data)
cnt+=1
loss=loss_fn(logit,target)
loss.backward()
loss_accumulated+=loss.data
print(loss.data)
optimizer.step()
if i%10==0:
print("Sleeping ...")
time.sleep(5)
print("Epoch is "+ str(i))
print(loss_accumulated)
torch.save(model.state_dict(), "CNN_params.pkl")
backends.cudnn.benchmark=True
train_model(X,y,100)
|
4b80f9643ca934cf9e1e7e5bbff269febcef0305
|
[
"Python"
] | 4
|
Python
|
pramodith/VERAClassifier
|
931cba40ee301611bcad592569a07b1807154ae4
|
0a1d6acd110b1d89a7071fa3f434cedd2331bed8
|
refs/heads/master
|
<file_sep>import math
def p(xyz):
print(xyz)
name = input("Name: \n")
p("\n" + name + " is an amazing name!")
ask = input("\nDo you want to play a game? Yes or No: \n")
if(ask == "Yes"):
p("\nSending you to the game...")
elif(ask == "No"):
p("\nAwww, okay. Come back again!")
else:
p("Sorry, invalid syntax, try agaiun. Please write 'Yes' or 'No'")
#def game():
<file_sep># Cool-Project
Hello! We smart boiis lol
- HTML, CSS, and JavaScript WEB Page
- Python
- Java
<file_sep>function calculateTest() {
var num = document.getElementById("number").value;
var result = num * 2;
alert(result);
}
function calculateAdd() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = parseFloat(num1) + parseFloat(num2);
alert(num1 + " + " + num2 + " = " + result);
}
function calculateSubtract() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = num1 - num2;
alert(num1 + " - " + num2 + " = " + result);
}
function calculateMultiply() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = num1 * num2;
alert(num1 + " * " + num2 + " = " + result);
}
function calculateDivide() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = num1 / num2;
alert(num1 + " / " + num2 + " = " + result);
}
function calculateModulus() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = num1 % num2;
alert(num1 + " % " + num2 + " = " + result);
}
function calculatePower() {
var num1 = document.getElementById("text1").value;
var num2 = document.getElementById("text2").value;
var result = num1 ** num2;
alert(num1 + " ^ " + num2 + " = " + result);
}
/* JavaScript Comments:
*/
<file_sep># my_script.rb
def say_input
puts "What should we say?"
input = gets.strip
puts "Okay, let's say: #{input}!"
end
say_input # this is to actually run the method when the file loads
# the command line
$ ruby my_script.rb
What should we say?
say this! # user types something like this
Okay, let's say: say this!!
#=> nil
<file_sep>Console.Write("C# Programming");
<file_sep>class Main {
// Print Statement Function
public static void print(String xyz) {
System.out.println(xyz);
}
public static void main(String[] args) {
print("Hello world!");
print("I just made a java one cuz why not. We have a lot of projects now lol");
}
}
|
cf93ae477bbc4a5523b29f6af0faae863f2d1d01
|
[
"Ruby",
"Markdown",
"JavaScript",
"C#",
"Python",
"Java"
] | 6
|
Python
|
MarkoKupresanin/Cool-Project
|
18eae1f6e829682889c9ddabeca120f39458faef
|
ade0b1d27014d8ea768b3359fb75d24af1a5923d
|
refs/heads/master
|
<repo_name>neville1355/RailsSampleApp<file_sep>/spec/models/relationship_spec.rb
require 'rails_helper'
require 'unit_spec_helper'
RSpec.describe Relationship, type: :model do
it 'should be valid' do
relationship = Relationship.new follower_id:1, followed_id:1
is_valid = relationship.valid?
expect(is_valid).to be(true)
end
it 'requires a follower id' do
relationship = Relationship.new followed_id:1
is_valid = relationship.valid?
expect(is_valid).to be(false)
end
it 'requires a followed id' do
relationship = Relationship.new follower_id:1
is_valid = relationship.valid?
expect(is_valid).to be(false)
end
end
<file_sep>/app/controllers/password_resets_controller.rb
class PasswordResetsController < ApplicationController
before_action :get_user, only:[:edit, :update]
before_action :confirm_valid_user_for_reset, only:[:edit, :update]
before_action :reset_not_expired, only:[:edit, :update]
before_action :password_not_blank, only:[:update]
def new
end
def edit
end
def update
if @user.update_attributes(password_reset_params)
flash[:success] = 'Password reset successfully'
login_user @user
redirect_to @user
else
render 'edit'
end
end
def create
email = params[:password_reset][:email].downcase
@user = User.find_by(email: email)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = 'Check your email for instructions'
redirect_to root_url
else
flash.now[:danger] = 'Invalid information provided'
render 'new'
end
end
private
def get_user
@user = User.find_by(email: params[:email])
end
def password_reset_params
params.require(:user).permit(:password, :password_confirmation)
end
def confirm_valid_user_for_reset
redirect_to root_url unless @user && @user.activated? && @user.authenticated?(:reset, params[:id])
end
def password_not_blank
if params[:user][:password].blank?
flash.now[:danger] = 'Password cannot be blank'
render 'edit'
end
end
def reset_not_expired
if @user.password_reset_expired?
flash[:danger] = 'Password reset expired'
redirect_to new_password_reset_url
end
end
end
<file_sep>/spec/integration/users_signup_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user signup' do
it 'does not create user if validation errors are present' do
before_count = User.count
post users_path, user: { name:'',
email:'',
password:'', password_confirmation: ''}
expect(User.count).to eql(before_count)
end
it 'does not create user if validation errors are present' do
before_count = User.count
post users_path, user: {
name:'',
email:'',
password:'',
password_confirmation: ''
}
after_count = User.count
expect(after_count).to eql(before_count)
end
it 'adds a user if valid info provided' do
before_count = User.count
post users_path, user: {
name:'Joe',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
after_count = User.count
expect(after_count).to eql(before_count + 1)
end
it 'does not allow unactivated users to log in immediately' do
post users_path, user: {
name:'Joe',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
log_in_as User.find_by(email:'<EMAIL>')
expect(is_logged_in?).to be(false)
end
it 'allows activated users to log in' do
post users_path, user: {
name:'Joe',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
# pulls user instance var from controller,
# gives us scope to get activation_token which is not stored in db
user = assigns(:user)
get edit_account_activation_path(user.activation_token, email: user.email)
log_in_as(user)
expect(is_logged_in?).to be(true)
end
it 'rejects activations with bad emails' do
post users_path, user: {
name:'Joe',
email:'joe<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
# pulls user instance var from controller,
# gives us scope to get activation_token which is not stored in db
user = assigns(:user)
get edit_account_activation_path(user.activation_token, email: '<EMAIL>')
log_in_as(user)
expect(is_logged_in?).to be(false)
end
it 'rejects activations with good emails but bad tokens' do
post users_path, user: {
name:'Joe',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
# pulls user instance var from controller,
# gives us scope to get activation_token which is not stored in db
user = assigns(:user)
get edit_account_activation_path('invalid_token', email: '<EMAIL>')
log_in_as(user)
expect(is_logged_in?).to be(false)
end
end<file_sep>/spec/integration/password_resets_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user password reset' do
it 'updates reset time and digest when vaild email provided' do
user = create_user!
reset_at_before = user.reset_sent_at
reset_digest_before = user.reset_digest
post password_resets_path(password_reset: { email: user.email} )
user.reload
reset_at_after = user.reset_sent_at
reset_digest_after = user.reset_digest
expect(reset_at_before).to be(nil)
expect(reset_digest_before).to be(nil)
expect(reset_at_after).to_not be(nil)
expect(reset_digest_after).to_not be(nil)
end
it 'resets password ' do
user = create_user!
password_before = user.password_digest
post password_resets_path(password_reset: { email: user.email} )
user_from_controller = assigns(:user)
patch password_reset_path(user_from_controller.reset_token, {
email: user.email,
user: {
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
})
user.reload
password_after = user.password_digest
expect(password_before).to_not eq(password_after)
end
it 'does not reset password with bad token' do
user = create_user!
password_before = user.password_digest
post password_resets_path(password_reset: { email: user.email} )
patch password_reset_path('bad token', {
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
})
user.reload
password_after = user.password_digest
expect(password_before).to eq(password_after)
end
it 'does not resets password if blank' do
user = create_user!
password_before = user.password_digest
post password_resets_path(password_reset: { email: user.email} )
user_from_controller = assigns(:user)
patch password_reset_path(user_from_controller.reset_token, {
email: user.email,
user: {
password: '',
password_confirmation: ''
}
})
user.reload
password_after = user.password_digest
expect(password_before).to eq(password_after)
end
it 'does not resets password if not same' do
user = create_user!
password_before = user.password_digest
post password_resets_path(password_reset: { email: user.email} )
user_from_controller = assigns(:user)
patch password_reset_path(user_from_controller.reset_token, {
email: user.email,
user: {
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
}
})
user.reload
password_after = user.password_digest
expect(password_before).to eq(password_after)
end
end<file_sep>/spec/integration/user_login_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user login' do
describe 'login with invalid information' do
it 'displays login error on screen' do
get login_path
post login_path, session:{email:'', password:''}
flash_empty_before = flash.empty?
get root_path
flash_empty_after = flash.empty?
expect(flash_empty_before).to be(false)
expect(flash_empty_after).to be(true)
end
it 'logs a user in when valid information provided' do
#this should be refactored to use arrange->act->assert
user = create_user! email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', name:'Asdasd'
get login_path
post login_path, session:{email:'<EMAIL>', password:'<PASSWORD>'}
assert_redirected_to user
follow_redirect!
assert_template 'users/show'
end
end
describe 'will log users out' do
it 'logs a user out' do
user = create_user! email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', name:'Asdasd'
get login_path
post login_path, session:{email:'<EMAIL>', password:'<PASSWORD>'}
expect(is_logged_in?).to be(true)
#now we are logged in
delete logout_path
expect(is_logged_in?).to be(false)
end
it 'wont log out a user that is already logged out' do
user = create_user! email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', name:'Asdasd'
get login_path
post login_path, session:{email:'<EMAIL>', password:'<PASSWORD>'}
expect(is_logged_in?).to be(true)
#now we are logged in
delete logout_path
expect(is_logged_in?).to be(false)
#simulate second logout, maybe in a separate browser window
delete logout_path
expect(is_logged_in?).to be (false)
end
end
describe 'remember me' do
it 'creates an extra cookie on login' do
user = create_user!
log_in_as(user, remember_me: '1')
remember_cookie = cookies['remember_token']
expect(remember_cookie).to_not be(nil)
end
it 'cookie is not present if not remember selected' do
user = create_user!
log_in_as(user, remember_me: '0')
remember_cookie = cookies['remember_token']
expect(remember_cookie).to be(nil)
end
end
end<file_sep>/spec/controllers/users_controller_spec.rb
require 'rails_helper'
RSpec.describe UsersController, type: :controller do
it 'shows new view' do
get :new
assert_response :success
end
end
<file_sep>/spec/integration/site_layout_spec.rb
require 'rails_helper'
require 'spec_helper'
RSpec.describe StaticPagesController, type: :controller do
render_views
it 'looks correct' do
get :home
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path
assert_select "a[href=?]", home_path
assert_select "a[href=?]", help_path
assert_select "a[href=?]", contact_path
assert_select "a[href=?]", about_path
end
end<file_sep>/spec/integration_spec_helper.rb
require 'spec_helper'
def create_user! ( attributes = {} )
user = User.new(
name:'test',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation:'<PASSWORD>',
activated: true,
activated_at: Time.zone.now
)
user.assign_attributes attributes
user.save!
user
end
#Returns true if there is a user id in the session cookie
def is_logged_in?
#cannot re-use session module in tests for reasons...?
!session[:user_id].nil?
end
def log_in_as(user, attributes = {})
password = attributes[:password]
remember_me = attributes[:remember_me] || '0'
post login_path, session: {
email: user.email,
password: <PASSWORD>,
remember_me: remember_me
}
end
def create_micropost!(user, attributes = {content:'some content'})
micropost = user.microposts.create(attributes)
micropost
end<file_sep>/spec/integration/user_following_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user following spec' do
it 'should follow and unfollow a user' do
user_a = create_user!
user_b = create_user! email: '<EMAIL>'
expect(user_a.following?(user_b)).to be(false)
user_a.follow(user_b)
expect(user_a.following?(user_b)).to be(true)
expect(user_b.followers.include?(user_a)).to be(true)
user_a.unfollow(user_b)
expect(user_a.following?(user_b)).to be(false)
end
end<file_sep>/spec/mailers/user_mailer_spec.rb
require "rails_helper"
require 'integration_spec_helper'
RSpec.describe UserMailer, type: :mailer do
describe "account_activation" do
let(:user) { create_user! activation_token: User.new_token}
let(:mail) { UserMailer.account_activation user }
it "renders the headers" do
expect(mail.subject).to eq('Please activate your account')
expect(mail.to).to eq(['<EMAIL>'])
#must search for escaped email since we send it already encoded in the hyperlink
expect(mail.body.encoded).to match(CGI::escape(user.email))
end
it "renders the body" do
expect(mail.body.encoded).to match('Please activate')
end
end
describe "password_reset" do
let(:mail) { UserMailer.password_reset }
xit "renders the headers" do
expect(mail.subject).to eq("Password reset")
expect(mail.to).to eq(["<EMAIL>"])
expect(mail.from).to eq(["<EMAIL>"])
end
xit "renders the body" do
expect(mail.body.encoded).to match("Hi")
end
end
end
<file_sep>/spec/integration/user_delete_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user delete' do
it 'should not allow non-admin users to delete other users' do
user_a = create_user!
user_b = create_user! email: '<EMAIL>'
log_in_as(user_a)
delete user_path(user_b)
user_b_after_delete = User.find_by(id: user_b.id)
expect(user_b_after_delete).not_to be(nil)
end
it 'should allow admin users to delete other users' do
user_a = create_user! admin: true
user_b = create_user! email: '<EMAIL>'
log_in_as(user_a)
delete user_path(user_b)
user_b_after_delete = User.find_by(id: user_b.id)
expect(user_b_after_delete).to be(nil)
end
it 'should not allow users to delete themselves' do
user_a = create_user! admin: true
log_in_as(user_a)
delete user_path(user_a)
user_a_after_delete = User.find_by(id: user_a.id)
expect(user_a_after_delete).not_to be(nil)
end
end<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token, :reset_token
#dependent: :destroy tells rails to destroy all microposts associated to a user when user is destroyed
has_many :microposts, dependent: :destroy
has_many :active_relationships,
class_name: 'Relationship',
foreign_key: 'follower_id',
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :passive_relationships,
class_name: 'Relationship',
foreign_key: 'followed_id',
dependent: :destroy
has_many :followers, through: :passive_relationships, source: :follower
VALID_EMAIL_REGEX = /[\w+\-.]+@[a-z\-.]+\.[a-x]+/i
has_secure_password
#this is hot garbage right here
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: {maximum: 50}
validates :email, presence: true, length: {maximum: 250},
uniqueness: { case_sensitive:false },
format: { with: VALID_EMAIL_REGEX }
validates :password, length: {minimum:8}, allow_blank: true
def self.new_token
# generates a random base 64 digest of length 22
SecureRandom.urlsafe_base64
end
def self.digest(string)
cost = ActiveModel::SecurePassword.min_cost ?
BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(self.remember_token))
end
def forget
update_attribute(:remember_digest, nil)
end
def authenticated? (attribute, token)
digest = self.send("#{attribute}_digest")
return false if digest.nil?
#check if the encrypted value of our param equals the remember digest in the db for this user
BCrypt::Password.new(digest).is_password?(token)
end
def activate
self.update_attributes!(activated: true, activated_at: Time.zone.now)
end
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
def create_reset_digest
self.reset_token = User.new_token
self.update_attributes!(
reset_digest: User.digest(reset_token),
reset_sent_at: Time.zone.now
)
end
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
def password_reset_expired?
#three hours ago is less than 2 hours ago
reset_sent_at < 2.hours.ago
end
def feed
following_ids_subselect = 'SELECT followed_id FROM relationships
WHERE follower_id = :user_id'
Micropost.where("user_id IN (#{following_ids_subselect}) OR user_id = :user_id",
user_id: id)
end
def following? user
# self.following.include? user.id
active_relationships.find_by(followed_id: user.id).present?
end
def follow user
# self.following.create(followed_id: user.id)
active_relationships.create(follower_id: self.id, followed_id: user.id)
end
def unfollow user
# self.following.find(user.id).destroy
active_relationships.find_by(followed_id: user.id).destroy
end
private
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
def downcase_email
self.email = email.downcase
end
end
<file_sep>/spec/integration/user_profile_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user profile microposts' do
before(:each) do
@user = create_user!
end
it 'should allow users who are logged in to post' do
before_count = Micropost.all.size
log_in_as(@user)
post microposts_path, micropost: {
content: 'la la la',
user_id: @user.id
}
after_count = Micropost.all.size
expect(before_count + 1).to eq(after_count)
end
it 'should not allow posts from users who are not logged in' do
before_count = Micropost.all.size
post microposts_path, micropost: {
content: 'la la la',
user_id: @user.id
}
after_count = Micropost.all.size
expect(before_count).to eq(after_count)
end
it 'should not allow delete when not logged in' do
micropost = create_micropost! @user
before_count = Micropost.all.size
delete micropost_path(micropost.id)
after_count = Micropost.all.size
expect(before_count).to eq(after_count)
end
it 'should allow delete when logged in for own posts' do
micropost = create_micropost! @user
before_count = Micropost.all.size
log_in_as(@user)
delete micropost_path(micropost.id)
after_count = Micropost.all.size
expect(before_count - 1).to eq(after_count)
end
it 'should not allow delete for other users posts' do
user_b = create_user! email: '<EMAIL>'
micropost = create_micropost! user_b
before_count = Micropost.all.size
log_in_as(@user)
delete micropost_path(micropost.id)
after_count = Micropost.all.size
expect(before_count).to eq(after_count)
end
end<file_sep>/app/helpers/users_helper.rb
module UsersHelper
def gravatar_for(user, options = { size: 80 })
email_md5 = Digest::MD5::hexdigest(user.email)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{email_md5}?s=#{size}"
image_tag(gravatar_url, alt:user.name, class:'gravatar')
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
#Returns the full title for a page
def full_title(page_title = '')
base_title = 'Sample Rails App'
base_title = "#{page_title} | #{base_title}" if not page_title.empty?
end
end
<file_sep>/db/migrate/20160421013949_add_index_to_user_email.rb
class AddIndexToUserEmail < ActiveRecord::Migration
def up
add_index :users, :email, :name => 'idx_email_uniqueness', unique:true
end
def down
remove_index :users, :name => 'idx_email_uniqueness'
end
end
<file_sep>/spec/controllers/relationships_controller_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe RelationshipsController, type: :controller do
describe 'creating a relationship' do
it 'should require logged in user' do
end
end
end
<file_sep>/app/models/micropost.rb
class Micropost < ActiveRecord::Base
belongs_to :user
#default scope updates queries globally (?)
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :user_id, presence:true
validates :content, presence:true, length: { maximum: 140 }
validate :check_picture_size
private
def check_picture_size
if picture.size > 1.megabytes
errors.add(:picture, 'File size is too large')
end
end
end
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
require 'unit_spec_helper'
RSpec.describe User, type: :model do
it 'should be valid with good model data' do
user = create_user
valid = user.valid?
expect(valid).to be(true)
end
describe 'name' do
it 'should always be present' do
user = create_user name:''
valid = user.valid?
expect(valid).to be(false)
end
it 'should be lte 50 chars' do
name = 'a' * 51
user = create_user name: name
valid = user.valid?
expect(valid).to be(false)
end
end
describe 'email' do
it 'email should be present' do
user = create_user email:' '
valid = user.valid?
expect(valid).to be(false)
end
it 'should be lte 250 chars' do
email = 'a' * 250
user = create_user email: "a@#{email}"
valid = user.valid?
expect(valid).to be(false)
end
it 'should verify valid email format' do
user = create_user
valid_addresses = [ '<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>']
valid_addresses.each do |address|
user.email = address
valid = user.valid?
expect(valid).to be(true)
end
#[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}
end
it'should reject invalid email format' do
user = create_user
invalid_addresses = [ '+@.com',
'google.com',
'asd']
invalid_addresses.each do |address|
user.email = address
valid = user.valid?
expect(valid).to be(false)
end
end
it 'should be unique' do
user_a = create_user email:'<EMAIL>'
user_b = create_user email:'<EMAIL>'
user_a.save!
valid = user_b.valid?
expect(valid).to be(false)
end
it 'compares email uniqueness case insensitive' do
user_a = create_user email:'<EMAIL>'
user_b = create_user email:'<EMAIL>'
user_a.save!
valid = user_b.valid?
expect(valid).to be(false)
end
end
describe 'password' do
it 'should have a minimum length' do
user = create_user
user.password = '1'
user.password_confirmation = '1'
valid = user.valid?
expect(valid).to be(false)
end
end
describe 'authenticated?' do
it 'should gracefully handle nil values' do
user = create_user
is_authenticated = user.authenticated? :remember, nil
expect(is_authenticated).to be(false)
end
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
admin_user = User.create!(
name: 'admin',
email: '<EMAIL>',
password:'<PASSWORD>',
password_confirmation: '<PASSWORD>',
admin: true,
activated: true,
activated_at: Time.zone.now
)
99.times do |i|
User.create!(
name: "User #{i}",
email: "<EMAIL>",
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>',
activated: true,
activated_at: Time.zone.now
)
end
users = User.order(:created_at).take(20)
50.times do |i|
users.each do |user|
user.microposts.create!(content:"some content #{i}")
end
end
#following
users[2..10].each do |user|
admin_user.follow(user)
end
users[8..20].each do |user|
user.follow(admin_user)
end<file_sep>/spec/integration/micropost_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'microposts' do
it 'should order by most recent first' do
user = create_user!
create_micropost! user, content: '1', created_at: 2.days.ago
most_recent = create_micropost! user, content: '2', created_at: 1.days.ago
create_micropost! user, content: '3', created_at: 1.years.ago
first_micropost = Micropost.first
expect(most_recent.id).to eq(first_micropost.id)
end
it 'should be destroyed when the parent user object is also destroyed' do
user = create_user!
create_micropost! user, content: '1', created_at: 2.days.ago
create_micropost! user, content: '2', created_at: 1.days.ago
create_micropost! user, content: '3', created_at: 1.years.ago
micropost_size = Micropost.all.size
user.destroy!
micropost_size_after = Micropost.all.size
expect(micropost_size_after).to eq(micropost_size - 3)
end
it 'should show a feed of all of followed users' do
user_a = create_user!
user_b = create_user! email: '<EMAIL>'
user_c = create_user! email: '<EMAIL>'
user_a.follow(user_b)
user_a.save
user_c.follow(user_a)
user_c.save
#includes follower posts
user_a.microposts.create(content:'this is a test from user_a')
user_a.microposts.create(content:'this is a test from user_a')
#include self posts
user_b.microposts.create(content:'this is a test from user_b')
user_b.microposts.create(content:'this is a test from user_b')
#do not include non-follower posts
user_c.microposts.create(content:'this is a test from user_c')
user_c.microposts.create(content:'this is a test from user_c')
feed = user_a.feed
#ensure all of user b's posts are in the user a feed
user_b.microposts.each do |post|
expect(feed.include? post).to be(true)
end
user_a.microposts.each do |post|
expect(feed.include? post).to be(true)
end
user_c.microposts.each do |post|
expect(feed.include? post).to be(false)
end
end
end<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
#display loging form
def new
end
#create login sessions
def create
user = User.find_by(email: params[:session][:email])
if(!!user && user.authenticate(params[:session][:password]))
if(user.activated?)
login_user user
params[:session][:remember_me] == '1' ? remember(user) : forget_user(user)
flash[:success] = "Successfully logged in as #{user.name}!"
#redirect to user profile path (get to users controller)
redirect_back_or(user)
else
flash[:warning] = 'You must activate your account before logging in'
redirect_to root_url
end
else
#return errors
flash.now[:danger] = 'Invalid email or password'
render 'new'
end
end
#logout/destroy session
def destroy
log_out
flash[:success] = 'Successfully logged out!'
redirect_to root_url
end
end
<file_sep>/spec/integration/edit_user_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe UsersController do
describe 'update user' do
it 'does not save with bad data' do
user = create_user! name: 'test', email: '<EMAIL>'
log_in_as(user)
patch user_path(user), user: {
name: '',
email:'',
password:'',
password_confirmation:''
}
user.reload
expect(user.name).to eq('test')
expect(user.email).to eq('<EMAIL>')
end
it 'saves correctly with good data' do
user = create_user! name: 'test'
log_in_as(user)
patch user_path(user), user: {
name: '<NAME>'
}
user.reload
expect(user.name).to eq('<NAME>')
end
it 'should not allow edits to users when not logged in' do
user = create_user! name: 'test'
patch user_path(user), user: {
name: '<NAME>'
}
user.reload
expect(user.name).to eq('test')
end
it 'should not allow users to edit other users' do
user_a = create_user! name: 'test'
user_b = create_user! name: 'bob', email:'<EMAIL>'
log_in_as(user_a)
patch user_path(user_b), user: {
name: '<NAME>'
}
user_b.reload
#should not accept change since we logged in as user a
expect(user_b.name).to eq('bob')
end
it 'should redirect to login and then redirect to edit page after login' do
user = create_user! name: 'test'
get edit_user_path(user)
log_in_as(user)
assert_redirected_to edit_user_path(user)
end
end
end<file_sep>/spec/models/micropost_spec.rb
require 'rails_helper'
require 'unit_spec_helper'
RSpec.describe Micropost, type: :model do
it 'should be valid' do
micropost = create_micropost
is_valid = micropost.valid?
expect(is_valid).to be(true)
end
it 'should not be valid if user id is missing' do
micropost = create_micropost user_id: nil
is_valid = micropost.valid?
expect(is_valid).to be(false)
end
it 'should not be valid if content is missing' do
micropost = create_micropost content: ''
is_valid = micropost.valid?
expect(is_valid).to be(false)
end
it 'should not be valid if content length greater than 140' do
micropost = create_micropost content: 'a' * 141
is_valid = micropost.valid?
expect(is_valid).to be(false)
end
end
<file_sep>/spec/integration/user_index_page_spec.rb
require 'rails_helper'
require 'integration_spec_helper'
RSpec.describe 'user index page' do
# before :all do
# (1..99).each do |n|
# create_user! email: "<EMAIL>", name: "Test #{n}"
# end
#end
it 'displays a list of users' do
user = create_user!
log_in_as(user)
get users_path
# assert_template 'users/index'
# assert_select 'div.pagination'
# User.paginate(page:1).each do |user|
# expect(response.body).to have_selector(:css, "a[href=/users/#{user.id}")
# end
end
# after :all do
# User.all.each do |user|
# user.destroy
# end
# end
end<file_sep>/README.md
# Rails tutorial sample application
My code as I'm following the railstutorial.org lessons
<file_sep>/spec/unit_spec_helper.rb
require 'spec_helper'
def create_user ( attributes = {} )
user = User.new(
name:'test',
email:'<EMAIL>',
password:'<PASSWORD>',
password_confirmation:'<PASSWORD>',
activated: true,
activated_at: Time.zone.now
)
user.assign_attributes attributes
user
end
def create_micropost (attributes = { user_id: 0, content: 'some content'})
Micropost.create(attributes)
end<file_sep>/spec/controllers/static_pages_controller_spec.rb
require 'rails_helper'
require 'spec_helper'
RSpec.describe StaticPagesController, type: :controller do
#render_views is important for rspec in order for it to actually render the view at all
#so we can use assert_select with it
render_views
it 'shows home' do
get :home
assert_response :success
assert_select 'title', 'Home | Sample Rails App'
end
it 'should get help' do
get :help
assert_response :success
assert_select 'title', 'Help | Sample Rails App'
end
it 'should get about' do
get :about
assert_response :success
assert_select 'title', 'About | Sample Rails App'
end
it 'shows contact page' do
get :contact
assert_response :success
assert_select 'title', 'Contact | Sample Rails App'
end
end
|
96aee5ed6affb3b0a51a256d41b93428b316e816
|
[
"Markdown",
"Ruby"
] | 28
|
Ruby
|
neville1355/RailsSampleApp
|
5d6cad0e3e90beed3bb30d242bb63ab89ccc3462
|
7589234f75d2d62c2de0a5286e1c93feee7a0fa0
|
refs/heads/master
|
<repo_name>tjwldnjss13/yolov2-mobile-pytorch<file_sep>/garbage.py
import torch
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from models.darknet53_ds import *
from PIL import Image
if __name__ == '__main__':
a = torch.Tensor([float('nan'), 1, 2])
for i in range(100):
for j in range(100):
for m in range(100):
print(i, j, m)
if torch.isnan(a).sum() > 0:
exit(0)<file_sep>/models/yolov2_model.py
import torch
import torch.nn as nn
from models.backbone import YoloBackbone
from models.darknet19_ds import Darknet19DS
from models.darknet53_ds import Darknet53DS
from models.dsconv import DSConv
from utils.rpn_util import generate_anchor_box
class YOLOV2Mobile(nn.Module):
def __init__(self, in_size, num_classes, anchor_box_samples):
"""
:param in_size: tuple or list, (height of input, width of input)
:param num_classes: int
:param anchor_box_samples: tensor, [num anchor boxes, (height of anchor box, width of anchor box)]
"""
super(YOLOV2Mobile, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.anchor_box_samples = torch.Tensor([[1.73145, 1.3221],
[4.00944, 3.19275],
[8.09892, 5.05587],
[4.84053, 9.47112],
[10.0071, 11.2364]])
self.feature_model = YoloBackbone()
# self.reg_layer = DSConv(1024, len(anchor_box_samples) * (5 + num_classes), 1, 1, 0, 'relu')
self.reg_layer = nn.Sequential(
nn.Conv2d(1024, len(anchor_box_samples) * (5 + num_classes), 1, 1)
)
# self.anchor_boxes = self._get_valid_anchor_boxes()
self._initialize_weights()
def _get_valid_anchor_boxes(self):
dummy = torch.zeros(1, 3, 416, 416)
out_dummy = self.feature_model(dummy)
h_out = out_dummy.shape[2]
anchor_stride = int(self.in_size[0] / h_out)
anchor_boxes, valid_mask = generate_anchor_box(self.anchor_box_samples, self.in_size, anchor_stride)
return anchor_boxes[torch.nonzero(valid_mask, as_tuple=False)].squeeze(1)
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
def forward(self, x):
x = self.feature_model(x)
x = self.reg_layer(x)
x = x.permute(0, 2, 3, 1)
return x
if __name__ == '__main__':
from torchsummary import summary
model = YOLOV2Mobile((416, 416), 20, torch.Tensor([[20, 30], [10, 40]])).cuda()
summary(model, (3, 416, 416))
<file_sep>/train.py
import os
import copy
import cv2 as cv
import numpy as np
import time
import argparse
import torch
import torch.optim as optim
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, ConcatDataset, Subset
from PIL import Image
from utils.util import time_calculator
from utils.pytorch_util import make_batch
from utils.yolov2_tensor_generator import get_output_anchor_box_tensor, get_yolo_v2_output_tensor, get_yolo_v2_target_tensor
from dataset.coco_dataset import COCODataset, custom_collate_fn
# from dataset.voc_dataset import VOCDataset, custom_collate_fn
from dataset.augment import GaussianNoise
from models.yolov2_model import YOLOV2Mobile
from loss import yolov2_custom_loss_1 as loss_func
from early_stopping import EarlyStopping
def get_coco_dataset(root):
from dataset.coco_dataset import COCODataset, custom_collate_fn
dset_name = 'coco2017'
root = 'D://DeepLearningData/COCOdataset2017/'
train_img_dir = os.path.join(root, 'images', 'train')
val_img_dir = os.path.join(root, 'images', 'val')
train_ann_pth = os.path.join(root, 'annotations', 'instances_train2017.json')
val_ann_pth = os.path.join(root, 'annotations', 'instances_val2017.json')
transform_og = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
transform_noise = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor(),
GaussianNoise(mean=0, std=.2),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
train_dset = COCODataset(root=root, images_dir=train_img_dir, annotation_path=train_ann_pth, image_size=(416, 416),
is_categorical=True, transforms=transform_og)
train_dset_noise = COCODataset(root=root, images_dir=train_img_dir, annotation_path=train_ann_pth, image_size=(416, 416),
is_categorical=True, transforms=transform_noise)
# train_dset_rotate = COCODataset(root=root, images_dir=train_img_dir, annotation_path=train_ann_pth, image_size=(416, 416), is_categorical=True, transforms=transform_og, rotate_angle=(-30, 30))
num_classes = train_dset.num_classes
# train_dset = ConcatDataset([train_dset, train_dset_noise])
val_dset = COCODataset(root=root, images_dir=val_img_dir, annotation_path=val_ann_pth, image_size=(416, 416),
is_categorical=True, transforms=transform_og)
collate_fn = custom_collate_fn
return dset_name, train_dset, val_dset, collate_fn
def get_voc_dataset(root):
from dataset.voc_dataset import VOCDataset, custom_collate_fn
dset_name = 'voc2012'
transform_og = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor()])
transform_norm = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
transform_noise = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor(),
GaussianNoise(mean=0, std=.2)])
transform_norm_noise = transforms.Compose([transforms.Resize((416, 416)),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225]),
GaussianNoise(mean=0, std=.2)])
transform_rotate = transforms.Compose([transforms.Resize((416, 416)),
transforms.RandomRotation((-60, 60)),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
transform_vflip = transforms.Compose([transforms.Resize((416, 416)),
transforms.RandomVerticalFlip(1),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
transform_hflip = transforms.Compose([transforms.Resize((416, 416)),
transforms.RandomHorizontalFlip(1),
transforms.ToTensor(),
transforms.Normalize([.485, .456, .406], [.229, .224, .225])])
dset_og = VOCDataset(root, img_size=(416, 416), transforms=transform_og, is_categorical=True)
dset_norm = VOCDataset(root, img_size=(416, 416), transforms=transform_norm, is_categorical=True)
dset_noise = VOCDataset(root, img_size=(416, 416), transforms=transform_noise, is_categorical=True)
dset_norm_noise = VOCDataset(root, img_size=(416, 416), transforms=transform_norm_noise, is_categorical=True)
# dset_rotate = VOCDataset(root, img_size=(416, 416), transforms=transform_rotate, is_categorical=True)
# dset_vflip = VOCDataset(root, img_size=(416, 416), transforms=transform_vflip, is_categorical=True)
# dset_hflip = VOCDataset(root, img_size=(416, 416), transforms=transform_hflip, is_categorical=True)
num_classes = dset_og.num_classes
n_data = len(dset_og)
n_train_data = int(n_data * .7)
indices = list(range(n_data))
np.random.shuffle(indices)
train_idx, val_idx = indices[:n_train_data], indices[n_train_data:]
train_dset_og = Subset(dset_og, indices=train_idx)
train_dset_norm = Subset(dset_norm, indices=train_idx)
train_dset_noise = Subset(dset_noise, indices=train_idx)
train_dset_norm_noise = Subset(dset_norm_noise, indices=train_idx)
# train_dset_rotate = Subset(dset_rotate, indices=train_idx)
# train_dset_vflip = Subset(dset_vflip, indices=train_idx)
# train_dset_hflip = Subset(dset_hflip, indices=train_idx)
# train_dset = ConcatDataset([dset_og, dset_norm, dset_noise, dset_norm_noise])
train_dset = train_dset_og
val_dset = Subset(dset_og, indices=val_idx)
collate_fn = custom_collate_fn
return dset_name, train_dset, val_dset, collate_fn
if __name__ == '__main__':
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Define hyper parameters, parsers
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, required=False, default=16)
parser.add_argument('--lr', type=float, required=False, default=.0001)
parser.add_argument('--weight_decay', type=float, required=False, default=.0005)
parser.add_argument('--momentum', type=float, required=False, default=.9)
parser.add_argument('--num_epochs', type=int, required=False, default=50)
args = parser.parse_args()
batch_size = args.batch_size
learning_rate = args.lr
weight_decay = args.weight_decay
momentum = args.momentum
num_epochs = args.num_epochs
model_save_term = 1
# Generate COCO dataset
root = 'D://DeepLearningData/COCOdataset2017/'
dset_name, train_dset, val_dset, collate_fn = get_coco_dataset(root)
num_classes = 92
# Generate VOC dataset
# root = 'D://DeepLearningData/VOC2012'
# dset_name, train_dset, val_dset, collate_fn = get_voc_dataset(root)
# num_classes = 20
# Generate data loaders
train_loader = DataLoader(train_dset, batch_size=batch_size, shuffle=True, drop_last=True, collate_fn=custom_collate_fn)
val_loader = DataLoader(val_dset, batch_size=batch_size, shuffle=True, drop_last=True, collate_fn=custom_collate_fn)
# Load model
model_name = 'yolov2mobile_backbone'
anchor_box_samples = torch.Tensor([[1.73145, 1.3221],
[4.00944, 3.19275],
[8.09892, 5.05587],
[4.84053, 9.47112],
[10.0071, 11.2364]])
model = YOLOV2Mobile(in_size=(416, 416), num_classes=num_classes, anchor_box_samples=anchor_box_samples).to(device)
state_dict_pth = None
# state_dict_pth = 'pretrained models/yolov2mobile19_coco2017_16epoch_0.0001lr_20.36563loss_5.41336losscoord_10.7989938721lossconf_4.15328losscls.pth'
if state_dict_pth is not None:
model.load_state_dict(torch.load(state_dict_pth), strict=False)
# Define optimizer, loss function
optimizer = optim.Adam(params=model.parameters(), lr=learning_rate, weight_decay=weight_decay)
# optimizer = optim.SGD(params=model.parameters(), lr=learning_rate, momentum=momentum, weight_decay=weight_decay)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=.9)
# Define anchor box configuration
dummy = torch.zeros(1, 3, 416, 416).to(device)
pred_dummy = model(dummy)
anchor_box_base = get_output_anchor_box_tensor(anchor_box_sizes=anchor_box_samples, out_size=pred_dummy.shape[1:3]).to(device)
# for idx1 in range(13):
# for idx2 in range(13):
# for idx3 in range(5):
# print(f'({idx1}, {idx2}, {idx3}) {anchor_box_base[idx1, idx2, 4 * idx3:4 * (idx3 + 1)]}')
num_iter = 0
train_loss_list = []
train_loss_coord_list = []
train_loss_confidence_list = []
train_loss_class_list = []
val_loss_list = []
val_loss_coord_list = []
val_loss_confidence_list = []
val_loss_class_list = []
model.train()
t_start = time.time()
for e in range(num_epochs):
num_batches = 0
num_datas = 0
train_loss = 0
train_loss_coord = 0
train_loss_confidence = 0
train_loss_class = 0
t_train_start = time.time()
for i, (imgs, anns) in enumerate(train_loader):
t_batch_start = time.time()
num_batches += 1
num_datas += len(imgs)
num_iter += 1
print('[{}/{}] '.format(e + 1, num_epochs), end='')
print(f'({num_iter}) ', end='')
print('{}/{} '.format(num_datas, len(train_dset)), end='')
x = make_batch(imgs).to(device)
predict_temp = model(x)
predict_list = []
y_list = []
for b in range(len(anns)):
ground_truth_box = anns[b]['bbox']
label_categorical = anns[b]['label_categorical']
# print(f'{label_int} {label_categorical} {name} {fn} {ground_truth_box / 32}')
h_img, w_img = 416, 416
ratio_y, ratio_x = 1 / 32, 1 / 32
ground_truth_box = torch.as_tensor(ground_truth_box)
if len(ground_truth_box.shape) < 2:
ground_truth_box = ground_truth_box.unsqueeze(0)
predict_list.append(get_yolo_v2_output_tensor(predict_temp[b], anchor_box_base))
y_temp = get_yolo_v2_target_tensor(ground_truth_boxes=ground_truth_box,
anchor_boxes=anchor_box_base,
labels=label_categorical,
n_bbox_predict=5,
n_class=num_classes,
in_size=(h_img, w_img),
out_size=(13, 13))
y_list.append(y_temp)
y = make_batch(y_list).to(device)
predict = make_batch(predict_list).to(device)
# for idx1 in range(13):
# for idx2 in range(13):
# for idx3 in range(5):
# if y[0, idx1, idx2, 25 * idx3 + 4] != 0:
# print('\nPredict_temp: ({}, {}, {}) {}'.format(idx1, idx2, idx3, predict_temp[0, idx1, idx2, 25 * idx3:25 * (idx3 + 1)]))
# print('\nPredict: ({}, {}, {}) {}'.format(idx1, idx2, idx3, predict[0, idx1, idx2, 25 * idx3:25 * (idx3 + 1)]))
# print('y: ({}, {}, {}) {}'.format(idx1, idx2, idx3, y[0, idx1, idx2, 25 * idx3:25 * (idx3 + 1)]))
del x, predict_temp, predict_list, y_list, y_temp
optimizer.zero_grad()
loss, loss_coord, loss_confidence, loss_class = loss_func(predict=predict, target=y, anchor_boxes=anchor_box_base,
num_bbox_predict=5, num_classes=num_classes, lambda_coord=1)
if loss.detach().cpu().item() > 1000:
for ann in anns:
print(ann['file_name'])
if torch.isnan(loss).sum() > 0:
print('NaN appears.')
exit(0)
loss.backward()
optimizer.step()
train_loss += loss.detach().cpu().item()
train_loss_coord += loss_coord.detach().cpu().item()
train_loss_confidence += loss_confidence.detach().cpu().item()
train_loss_class += loss_class.detach().cpu().item()
t_batch_end = time.time()
H, M, S = time_calculator(t_batch_end - t_start)
print('<loss> {: <8.5f} <loss_coord> {: <8.5f} <loss_confidence> {: <8.5f} <loss_class> {: <8.5f} '.format(
loss.detach().cpu().item(), loss_coord.detach().cpu().item(),
loss_confidence.detach().cpu().item(), loss_class.detach().cpu().item()), end='')
print('<loss_avg> {: <8.5f} <loss_coord_avg> {: <8.5f} <loss_confidence_avg> {: <8.5f} <loss_class_avg> {: <8.5f} '.format(
train_loss / num_batches, train_loss_coord / num_batches, train_loss_confidence / num_batches,
train_loss_class / num_batches
), end='')
print('<time> {:02d}:{:02d}:{:02d}'.format(int(H), int(M), int(S)))
if num_iter > 0 and num_iter % 5000 == 0:
save_pth = 'saved models/ckp_{}_{}_{}epoch_{}iter_{}lr.pth'.format(
model_name, dset_name, e + 1, num_iter, learning_rate)
torch.save(model.state_dict(), save_pth)
del y, predict, loss
train_loss /= num_batches
train_loss_coord /= num_batches
train_loss_confidence /= num_batches
train_loss_class /= num_batches
train_loss_list.append(train_loss)
train_loss_coord_list.append(train_loss_coord)
train_loss_confidence_list.append(train_loss_confidence)
train_loss_class_list.append(train_loss_class)
t_train_end = time.time()
H, M, S = time_calculator(t_train_end - t_train_start)
print(' <train_loss> {: <8.5f} <train_loss_coord> {: <8.5f} <train_loss_confidence> {: <8.5f} <train_loss_class> {: <8.5f} '.format(
train_loss_list[-1], train_loss_coord_list[-1], train_loss_confidence_list[-1], train_loss_class_list[-1]), end='')
print('<time> {:02d}:{:02d}:{:02d} '.format(int(H), int(M), int(S)))
with torch.no_grad():
model.eval()
val_loss = 0
val_loss_coord = 0
val_loss_confidence = 0
val_loss_class = 0
num_batches = 0
for i, (imgs, anns) in enumerate(val_loader):
num_batches += 1
x = make_batch(imgs).to(device)
predict_temp = model(x)
predict_list = []
y_list = []
for b in range(len(anns)):
h_img, w_img = 416, 416
ground_truth_box = anns[b]['bbox']
label = anns[b]['label_categorical']
ratio_h, ratio_w = 1 / 32, 1 / 32
ground_truth_box = torch.as_tensor(ground_truth_box)
if len(ground_truth_box.shape) < 2:
ground_truth_box = ground_truth_box.unsqueeze(0)
# if len(ground_truth_box) > 0:
# ground_truth_box[:, 0] *= ratio_h
# ground_truth_box[:, 1] *= ratio_w
# ground_truth_box[:, 2] *= ratio_h
# ground_truth_box[:, 3] *= ratio_w
predict_list.append(get_yolo_v2_output_tensor(predict_temp[b], anchor_box_base))
y_list.append(get_yolo_v2_target_tensor(ground_truth_boxes=ground_truth_box,
labels=label,
anchor_boxes=anchor_box_base,
n_bbox_predict=5,
n_class=num_classes,
in_size=(h_img, w_img),
out_size=(13, 13)))
y = make_batch(y_list).to(device)
predict = make_batch(predict_list).to(device)
del predict_temp, predict_list, y_list
loss, loss_coord, loss_confidence, loss_class = loss_func(predict=predict, target=y, anchor_boxes=anchor_box_base,
num_bbox_predict=5, num_classes=num_classes, lambda_coord=1)
val_loss += loss.detach().cpu().item()
val_loss_coord += loss_coord.detach().cpu().item()
val_loss_confidence += loss_confidence.detach().cpu().item()
val_loss_class += loss_class.detach().cpu().item()
del x, y, predict, loss
val_loss /= num_batches
val_loss_coord /= num_batches
val_loss_confidence /= num_batches
val_loss_class /= num_batches
val_loss_list.append(val_loss)
val_loss_coord_list.append(val_loss_coord)
val_loss_confidence_list.append(val_loss_confidence)
val_loss_class_list.append(val_loss_class)
print(' <val_loss> {: <10.5f} <val_loss_coord> {: <10.5f} <val_loss_confidence> {: <10.10f} <val_loss_class> {: <10.5f}'.format(
val_loss_list[-1], val_loss_coord_list[-1], val_loss_confidence_list[-1], val_loss_class_list[-1]))
if (e + 1) % model_save_term == 0:
save_pth = 'saved models/{}_{}_{}epoch_{}lr_{:.5f}loss_{:.5f}losscoord_{:.10f}lossconf_{:.5f}losscls.pth'.format(
model_name, dset_name, e + 1, learning_rate, val_loss_list[-1], val_loss_coord_list[-1],
val_loss_confidence_list[-1], val_loss_class_list[-1])
torch.save(model.state_dict(), save_pth)
x_axis = [i for i in range(len(train_loss_list))]
plt.figure(0)
plt.plot(x_axis, train_loss_list, 'r-', label='Train')
plt.plot(x_axis, val_loss_list, 'b-', label='Validation')
plt.title('Train/Validation loss')
plt.legend()
plt.show()
<file_sep>/dataset/augment.py
import torch
import cv2 as cv
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
class GaussianNoise(object):
def __init__(self, mean=0., std=.1):
self.mean = mean
self.std = std
def __call__(self, tensor):
return tensor + torch.randn(tensor.size()) * self.std + self.mean
def __repr__(self):
return self.__class__.__name__ + f'(mean={self.mean}, std={self.std}'
def rotate2d(image, bounding_box, angle):
"""
:param image: Tensor, [channel, height, width]
:param bounding_box: Tensor, [num bounding box, (y_min, x_min, y_max, x_max)]
:param angle: int
:return: img_rotate, bbox_rotate
"""
_, h_og, w_og = image.shape
img = image.permute(1, 2, 0).numpy()
h, w, _ = img.shape
x_ctr, y_ctr = int(w / 2), int(h / 2)
bbox = bounding_box.numpy()
mat = cv.getRotationMatrix2D((x_ctr, y_ctr), angle, 1)
abs_cos = abs(mat[0, 0])
abs_sin = abs(mat[0, 1])
bound_w = int(h * abs_sin + w * abs_cos)
bound_h = int(h * abs_cos + w * abs_sin)
mat[0, 2] += bound_w / 2 - x_ctr
mat[1, 2] += bound_h / 2 - y_ctr
img_rotate = cv.warpAffine(img, mat, (bound_w, bound_h))
h_rotate, w_rotate, _ = img_rotate.shape
x_ctr_rotate, y_ctr_rotate = int(w_rotate / 2), int(h_rotate / 2)
theta = angle * np.pi / 180
w_dif, h_dif = int((w_rotate - w) / 2), int((h_rotate - h) / 2)
bbox_rotate_list = []
if len(bbox) > 0:
theta *= -1
for i in range(len(bbox)):
x0, y0, x2, y2 = bbox[i]
x1, y1, x3, y3 = x2, y0, x0, y2
x0, y0, x1, y1 = x0 + w_dif, y0 + h_dif, x1 + w_dif, y1 + h_dif
x2, y2, x3, y3 = x2 + w_dif, y2 + h_dif, x3 + w_dif, y3 + h_dif
x0_rot = int((((x0 - x_ctr_rotate) * np.cos(theta)) - ((y0 - y_ctr_rotate) * np.sin(theta)) + x_ctr_rotate))
y0_rot = int((((x0 - x_ctr_rotate) * np.sin(theta)) + ((y0 - y_ctr_rotate) * np.cos(theta)) + y_ctr_rotate))
x1_rot = int((((x1 - x_ctr_rotate) * np.cos(theta)) - ((y1 - y_ctr_rotate) * np.sin(theta)) + x_ctr_rotate))
y1_rot = int((((x1 - x_ctr_rotate) * np.sin(theta)) + ((y1 - y_ctr_rotate) * np.cos(theta)) + y_ctr_rotate))
x2_rot = int((((x2 - x_ctr_rotate) * np.cos(theta)) - ((y2 - y_ctr_rotate) * np.sin(theta)) + x_ctr_rotate))
y2_rot = int((((x2 - x_ctr_rotate) * np.sin(theta)) + ((y2 - y_ctr_rotate) * np.cos(theta)) + y_ctr_rotate))
x3_rot = int((((x3 - x_ctr_rotate) * np.cos(theta)) - ((y3 - y_ctr_rotate) * np.sin(theta)) + x_ctr_rotate))
y3_rot = int((((x3 - x_ctr_rotate) * np.sin(theta)) + ((y3 - y_ctr_rotate) * np.cos(theta)) + y_ctr_rotate))
x_min, y_min = int(min(x0_rot, x1_rot, x2_rot, x3_rot)), int(min(y0_rot, y1_rot, y2_rot, y3_rot))
x_max, y_max = int(max(x0_rot, x1_rot, x2_rot, x3_rot)), int(max(y0_rot, y1_rot, y2_rot, y3_rot))
bbox_rotate_list.append([y_min, x_min, y_max, x_max])
h_rot, w_rot, _ = img_rotate.shape
h_ratio, w_ratio = h_og / h_rot, w_og / w_rot
img_rotate = cv.resize(img_rotate, (w_og, h_og), interpolation=cv.INTER_CUBIC)
img_rotate = torch.as_tensor(img_rotate).permute(2, 0, 1)
bbox_rotate = torch.as_tensor(bbox_rotate_list).type(dtype=torch.float64)
if len(bbox_rotate) > 0:
bbox_rotate[:, 0] *= h_ratio
bbox_rotate[:, 1] *= w_ratio
bbox_rotate[:, 2] *= h_ratio
bbox_rotate[:, 3] *= w_ratio
return img_rotate, bbox_rotate
def horizontal_flip(image, bounding_box):
"""
:param image: Tensor, [channel, height, width]
:param bounding_box: Tensor, [num bounding box, (y_min, x_min, y_max, x_max)]
:return:
"""
img_flip = transforms.RandomHorizontalFlip(1)(image)
_, h, w = img_flip.shape
bbox = bounding_box
for i in range(len(bbox)):
bbox[i, 1], bbox[i, 3] = w - bbox[i, 3], w - bbox[i, 1]
return img_flip, bbox
if __name__ == '__main__':
img_pth = '../sample/boat.jpg'
img = Image.open(img_pth)
import torchvision.transforms as transforms
img = transforms.ToTensor()(img)
bbox = torch.Tensor([[150, 110, 240, 410]])
img_flip, bbox_flip = horizontal_flip(img, bbox)
print(bbox_flip)
import matplotlib.pyplot as plt
plt.imshow(img_flip.permute(1, 2, 0))
plt.show()
|
477921e5bf382acd6dc3272fbf860ce57fb9e10e
|
[
"Python"
] | 4
|
Python
|
tjwldnjss13/yolov2-mobile-pytorch
|
a80f710864e75255101835e661b21f52d3689c9f
|
bf8bd16452348ea1bca85e445e66d2ac653324b5
|
refs/heads/master
|
<file_sep>package de.milltree.liquibaseexample.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"product_id", "reductionAmount"})})
@NamedQueries({ @NamedQuery(name = Discount.FIND_ALL, query = "SELECT d FROM Discount d") })
public class Discount {
public static final String FIND_ALL = "findAllDiscounts";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
private Product product;
private double reductionAmount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public double getReductionAmount() {
return reductionAmount;
}
public void setReductionAmount(double reductionAmount) {
this.reductionAmount = reductionAmount;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((product == null) ? 0 : product.hashCode());
long temp;
temp = Double.doubleToLongBits(reductionAmount);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Discount other = (Discount) obj;
if (product == null) {
if (other.product != null)
return false;
} else if (!product.equals(other.product))
return false;
if (Double.doubleToLongBits(reductionAmount) != Double
.doubleToLongBits(other.reductionAmount))
return false;
return true;
}
}
<file_sep>package de.milltree.liquibaseexample.extensions;
import liquibase.change.custom.CustomTaskChange;
import liquibase.change.custom.CustomTaskRollback;
import liquibase.database.Database;
import liquibase.exception.CustomChangeException;
import liquibase.exception.RollbackImpossibleException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
/**
* Simple example of a {@link CustomTaskChange} which can perform any Java code
* without the need to create SQL statements as result.
* <p>
* Be aware that this kind of change cannot be included in update SQL files
* generated by Liquibase.
* </p>
*/
public class PrintText implements CustomTaskChange, CustomTaskRollback {
@SuppressWarnings("unused")
private ResourceAccessor resourceAccessor;
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String getConfirmationMessage() {
return "Printed text: " + text + ".";
}
@Override
public void setUp() throws SetupException {
}
@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
this.resourceAccessor = resourceAccessor;
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors errors = new ValidationErrors();
errors.checkRequiredField("text", text);
return errors;
}
@Override
public void execute(Database database) throws CustomChangeException {
System.out.println(text);
}
@Override
public void rollback(Database database) throws CustomChangeException,
RollbackImpossibleException {
System.out.println("Rollback: " + text);
}
}
<file_sep>package de.milltree.liquibaseexample.service.entity;
import java.util.Collection;
import java.util.Collections;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import de.milltree.liquibaseexample.entity.Product;
import de.milltree.liquibaseexample.entity.StockEntry;
/**
* Management service for stock entries.
*/
@Component
public class StockEntryService {
@Inject
private EntityManager entityManager;
@Transactional
public void save(StockEntry stockEntry) {
if (stockEntry.getId() == null) {
entityManager.persist(stockEntry);
} else {
entityManager.merge(stockEntry);
}
}
@Transactional
@SuppressWarnings("unchecked")
public void deleteAll() {
Collection<StockEntry> entries = entityManager.createNamedQuery(
StockEntry.FIND_ALL).getResultList();
for (StockEntry entry : entries) {
entityManager.remove(entry);
}
}
@Transactional(readOnly = true)
public StockEntry findById(Long id) {
return entityManager.find(StockEntry.class, id);
}
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public Collection<StockEntry> findByProducts(Collection<Product> products) {
if (products == null || products.isEmpty()) {
return Collections.<StockEntry>emptyList();
}
Query query = entityManager.createNamedQuery(StockEntry.FIND_BY_PRODUCTS);
query.setParameter("products", products);
return query.getResultList();
}
}
<file_sep>DROP TABLE IF EXISTS `stockentry`;
DROP TABLE IF EXISTS `campaign`;
DROP TABLE IF EXISTS `discount`;
DROP TABLE IF EXISTS `product`;
DROP TABLE IF EXISTS `productgroup`;
DROP TABLE IF EXISTS `databasechangelog`;
DROP TABLE IF EXISTS `databasechangeloglock`;
CREATE TABLE `productgroup` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `product` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`price` double NOT NULL,
`productGroup_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`,`price`,`productGroup_id`),
KEY `FK50C664CF1B5743CF` (`productGroup_id`),
CONSTRAINT `FK50C664CF1B5743CF` FOREIGN KEY (`productGroup_id`) REFERENCES `productgroup` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `discount` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`reductionAmount` double NOT NULL,
`product_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_id` (`product_id`,`reductionAmount`),
KEY `FK1422D9614EA02205` (`product_id`),
CONSTRAINT `FK1422D9614EA02205` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `stockentry` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`amount` int(11) DEFAULT NULL,
`product_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_id` (`product_id`,`amount`),
KEY `FK9D13FB1C4EA02205` (`product_id`),
CONSTRAINT `FK9D13FB1C4EA02205` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
<file_sep>INSERT INTO productgroup (name) VALUES ('Weather');
INSERT INTO product (name, price, productgroup_id) VALUES ('Snow', 13.59, (SELECT g.id FROM productgroup g WHERE g.name = 'Weather'));
INSERT INTO product (name, price, productgroup_id) VALUES ('Sun', 50.0, (SELECT g.id FROM productgroup g WHERE g.name = 'Weather'));
INSERT INTO product (name, price, productgroup_id) VALUES ('Rain', 199.9, (SELECT g.id FROM productgroup g WHERE g.name = 'Weather'));<file_sep>package de.milltree.liquibaseexample.service.entity;
import java.util.Collection;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import de.milltree.liquibaseexample.entity.ProductGroup;
/**
* Management service for product groups.
*/
@Component
public class ProductGroupService {
@Inject
private EntityManager entityManager;
@Transactional
public void save(ProductGroup productGroup) {
if (productGroup.getId() == null) {
entityManager.persist(productGroup);
} else {
entityManager.merge(productGroup);
}
}
@Transactional
@SuppressWarnings("unchecked")
public void deleteAll() {
Collection<ProductGroup> groups = entityManager.createNamedQuery(
ProductGroup.FIND_ALL).getResultList();
for (ProductGroup group : groups) {
entityManager.remove(group);
}
}
@Transactional(readOnly = true)
public ProductGroup findById(Long id) {
return entityManager.find(ProductGroup.class, id);
}
@Transactional(readOnly = true)
public ProductGroup findByName(String name) {
try {
Query query = entityManager
.createNamedQuery(ProductGroup.FIND_BY_NAME);
query.setParameter("name", name);
return (ProductGroup) query.getSingleResult();
} catch (EntityNotFoundException enfe) {
return null;
}
}
}
<file_sep>package de.milltree.liquibaseexample.extensions;
import liquibase.change.custom.CustomSqlChange;
import liquibase.change.custom.CustomSqlRollback;
import liquibase.database.Database;
import liquibase.exception.CustomChangeException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.UpdateStatement;
/**
* Example implementation of a {@link CustomSqlChange} which produces a set of
* SQL statements to be executed.
* <p>
* Additionally this class could implement {@link CustomSqlRollback} for
* providing default rollback statements. However in this case no useful default
* rollback exists.
* </p>
*/
public class UpdateGroupStock implements CustomSqlChange {
@SuppressWarnings("unused")
private ResourceAccessor resourceAccessor;
private String productGroupName;
private Integer newStockAmount;
public String getProductGroupName() {
return productGroupName;
}
public void setProductGroupName(String productGroupName) {
this.productGroupName = productGroupName;
}
public Integer getNewStockAmount() {
return newStockAmount;
}
public void setNewStockAmount(Integer newStockAmount) {
this.newStockAmount = newStockAmount;
}
@Override
public String getConfirmationMessage() {
return "Stock updated to " + newStockAmount
+ " for all products in product group " + productGroupName
+ ".";
}
@Override
public void setUp() throws SetupException {
}
@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
this.resourceAccessor = resourceAccessor;
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors errors = new ValidationErrors();
errors.checkRequiredField("productGroupName", productGroupName);
errors.checkRequiredField("newStockAmount", newStockAmount);
return errors;
}
@Override
public SqlStatement[] generateStatements(Database database)
throws CustomChangeException {
UpdateStatement updateStock = new UpdateStatement(
database.getDefaultCatalogName(),
database.getDefaultSchemaName(), "stockentry");
updateStock.addNewColumnValue("amount", newStockAmount);
updateStock
.setWhereClause("product_id IN (SELECT p.id FROM product p WHERE p.productgroup_id IN ("
+ "SELECT g.id FROM productgroup g WHERE g.name = '"
+ productGroupName + "'))");
return new SqlStatement[] { updateStock };
}
}
<file_sep>package de.milltree.liquibaseexample;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Simply starts the spring context so that the Liquibase bean is initialized and executed.
*/
public class LiquibaseMain {
@SuppressWarnings("resource")
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring/spring-liquibase.xml");
}
}
<file_sep># Setup the initial database
1. Create an empty database
2. Execute the statements provided in "src/main/resources/mysql/create-tables.sql" to create the initial schema
3. Adjust the database configuration in "src/main/resources/spring/datasource.xml"
4. Run "InitMain" as Java Application to insert the initial data
# Run Liquibase via Spring
Simply execute "LiquibaseMain" as Java Application in order to migrate the database to the latest version.
This should result in two new database tables "databasechangelog" and "databasechangeloglock".
In the "databasechangelog" table you should see that all changesets defined in "src/main/resources/changelogs/db-changelog-master.xml" have been executed.
In order to test the available features, adjust the Liquibase parameters in "src/main/resources/spring/spring-liquibase.xml".
See also: http://www.liquibase.org/documentation/spring.html
# Setup Liquibase for commandline usage
1. Download the current Liquibase release (http://www.liquibase.org/download/index.html)
2. Unpack it somwhere on the file system
3. Copy the file "src/main/resources/liquibase/liquibase.properties" into "<liquibase-home>" and adjust the contained properties
4. Copy the file "src/main/resources/liquibase/mysql-connector-java-5.1.10.jar" into "<liquibase-home>/lib"
5. Open a commandline and navigate to "<liquibase-home>"
6. Run the following command to migrate the database to the latest version: liquibase.bat --defaultsFile=.\liquibase.properties update
Other interesting commands:
liquibase.bat --defaultsFile=.\liquibase.properties --contexts=test update
liquibase.bat --defaultsFile=.\liquibase.properties updateSQL > foo.sql
liquibase.bat --defaultsFile=.\liquibase.properties rollback 1.4
liquibase.bat --defaultsFile=.\liquibase.properties rollbackCount 3
liquibase.bat --defaultsFile=.\liquibase.properties rollbackToDate 2014-01-01
See also: http://www.liquibase.org/documentation/command_line.html<file_sep>DELETE FROM product WHERE productgroup_id IN (SELECT g.id FROM productgroup g WHERE g.name = 'Weather');
DELETE FROM productgroup WHERE name = 'Weather';
|
5146b5cc629b8151e66e68b834eac900233eee67
|
[
"Java",
"Text",
"SQL"
] | 10
|
Java
|
milltree/liquibase-example
|
2381beaa381b39feec99b0a041da4675d6b58002
|
425c4673635672184cb783c78ed48cc371969147
|
refs/heads/master
|
<file_sep>package carangoVelho;
import java.text.DecimalFormat;
import java.util.Scanner;
public class fetageExerc05Discursiva {
public static void main(String[] args) {
String nomePesquisa;
String codAluno[] = new String[5];
String codCurso[] = new String[60];
int x,y,escalas, cargah=0;
int soma1=0,soma2=0,soma3=0,soma4=0,soma5=0,soma6=0;
boolean encontrou;
String resp1;
/*
* -Qual o código do aluno?
2036607
-Qual o código do curso que vai fazer?
2
-Quer cadastrar outro curso?
-Se sim: "Qual o código do curso que vai fazer?
-Se não: verificar se ele está com 12h de curso;
Se não: "Qual o código do curso que vai fazer? *
*/
Scanner leia = new Scanner(System.in);
for (x = 0; x < codAluno.length; x++) {
System.out.println("Digite o código do aluno: ");
codAluno[x] = leia.nextLine();
//2036607
//outro for aqui
System.out.println("Digite o código do curso: ");
codCurso[x] = leia.nextLine();
if(codCurso[x].equals("1")){
cargah = cargah+10;
soma1 = soma1+1;
}else if(codCurso[x].equals("2")){
cargah = cargah+7;
soma2 = soma2+1;
}else if(codCurso[x].equals("3")){
cargah = cargah+3;
soma3 = soma3+1;
}else if(codCurso[x].equals("4")){
cargah = cargah+4;
soma4 = soma4+1;
}else if(codCurso[x].equals("5")){
cargah = cargah+4;
soma5 = soma5+1;
}else if(codCurso[x].equals("6")){
cargah = cargah+2;
soma6 = soma6+1;
}
//}
//Verifica se está com 12h de cursos, se não solicitar mais um curso
// for (x = 0; x < codCurso.length; x++) {
System.out.println("Quer cadastrar outros cursos (S) ou (N)");
//nomePesquisa = leia.nextLine();
resp1 = leia.nextLine();
if (resp1.equals("N")) {
if (cargah>=12) {
break;
}else {
//for (x = 0; x < codAluno.length; x++) {
System.out.println("Digite o código do curso: ");
codCurso[x] = leia.nextLine();
if(codCurso[x].equals("1")){
cargah = cargah+10;
soma1 = soma1+1;
}else if(codCurso[x].equals("2")){
cargah = cargah+7;
soma2 = soma2+1;
}else if(codCurso[x].equals("3")){
cargah = cargah+3;
soma3 = soma3+1;
}else if(codCurso[x].equals("4")){
cargah = cargah+4;
soma4 = soma4+1;
}else if(codCurso[x].equals("5")){
cargah = cargah+4;
soma5 = soma5+1;
}else if(codCurso[x].equals("6")){
cargah = cargah+2;
soma6 = soma6+1;
}
}
//break;
}
//}
//}
//CALCULOS:
//preco = 0.25*distancia[x];
//tempo = (60*distancia[x])/800;
//escalas = (int) tempo/180;
//RELATÓRIO INTERMEDIÁRIO; Código do Aluno; Total de horas cadastradas
System.out.println("O código do aluno é: "+codAluno[x]);
//Total de horas cadastradas
System.out.println("O total de horas cadastradas é: "+cargah);
System.out.println("Relatorio final: Total de cadastros de cada curso");
System.out.println("");
System.out.println("Curso 1 teve "+soma1+"cadastros.");
System.out.println("Curso 2 teve "+soma2+"cadastros.");
System.out.println("Curso 3 teve "+soma3+"cadastros.");
System.out.println("Curso 4 teve "+soma4+"cadastros.");
System.out.println("Curso 5 teve "+soma5+"cadastros.");
System.out.println("Curso 6 teve "+soma6+"cadastros.");
}
}
}
|
3d659c05a35dbdfb7cf10eb33d9bf14c7e9eea41
|
[
"Java"
] | 1
|
Java
|
rafaeloliveirap11/iniciando
|
cd03826d2be55955755a68d140d6cd1074fcf985
|
1d42721dd906ec53e2861bc4d068e8ba2201028b
|
refs/heads/master
|
<repo_name>hlian/agat<file_sep>/Cargo.toml
[package]
name = "agat"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
tui = "0.5"
termion = "1.5"
unicode-width = "0.1"
failure = "0.1"
rand = "0.6"
github-rs = "0.7"
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
chrono = { version = "0.4", features = ["serde"] }
http = "0.1"
<file_sep>/src/main.rs
extern crate serde;
use chrono::{DateTime, Utc};
use failure::{bail, err_msg, Error};
use github_rs::client::{Executor, Github};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
login: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct PR {
title: String,
user: User,
created_at: DateTime<Utc>,
}
#[derive(Debug)]
struct Cache<T> {
value: T,
etag: http::header::HeaderValue,
}
fn prs(token: &str, cache: Option<Cache<Vec<PR>>>) -> Result<Cache<Vec<PR>>, Error> {
let client = Github::new(token).map_err(failure::SyncFailure::new)?;
let builder = client.get();
let builder2 = match &cache {
Some(Cache { etag, .. }) => builder.set_etag(etag),
None => builder,
};
let (headers, status, json) = builder2
.repos()
.owner("Originate")
.repo("dashboard")
.pulls()
.execute::<Vec<PR>>()
.map_err(failure::SyncFailure::new)?;
if status == 304 {
Ok(cache.ok_or_else(|| err_msg("impossible"))?)
} else if status != 200 {
bail!("nope {}", status);
} else {
println!("{:?}", headers);
Ok(Cache {
value: json.ok_or_else(|| err_msg("invalid response"))?,
etag: github_rs::headers::etag(&headers)
.ok_or_else(|| err_msg("missing etag"))?
.clone(),
})
}
}
fn main2(token: &str) -> Result<(), Error> {
let cache = prs(token, None)?;
let etag2 = prs(token, Some(cache))?;
println!("success {:?}, {}", etag2.value, etag2.etag.to_str()?);
Ok(())
}
fn main() -> Result<(), Error> {
match std::env::var_os("TOKEN").and_then(|s| s.into_string().ok()) {
Some(token2) => main2(&token2),
None => {
eprintln!("Missing TOKEN");
bail!("Missing TOKEN")
}
}
}
|
3a4f323d6421fdca9db23c3530f22fde683a275b
|
[
"TOML",
"Rust"
] | 2
|
TOML
|
hlian/agat
|
390ea9be9332af2131897827cbd8ce0f28546372
|
da528240a02d6654dc7d932b474a22f7f9b021b8
|
refs/heads/master
|
<repo_name>syoyo/CxxSwizzle<file_sep>/sample/main.cpp
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#if defined(USE_SIMD)
#include "use_simd.h"
#else
#include "use_scalar.h"
#endif
#include <swizzle/glsl/vector.h>
#include <swizzle/glsl/matrix.h>
#include <swizzle/glsl/texture_functions.h>
typedef swizzle::glsl::vector< float_type, 2 > vec2;
typedef swizzle::glsl::vector< float_type, 3 > vec3;
typedef swizzle::glsl::vector< float_type, 4 > vec4;
static_assert(sizeof(vec2) == sizeof(float_type[2]), "Too big");
static_assert(sizeof(vec3) == sizeof(float_type[3]), "Too big");
static_assert(sizeof(vec4) == sizeof(float_type[4]), "Too big");
typedef swizzle::glsl::matrix< swizzle::glsl::vector, vec4::scalar_type, 2, 2> mat2;
typedef swizzle::glsl::matrix< swizzle::glsl::vector, vec4::scalar_type, 3, 3> mat3;
typedef swizzle::glsl::matrix< swizzle::glsl::vector, vec4::scalar_type, 4, 4> mat4;
//! A really, really simplistic sampler using SDLImage
struct SDL_Surface;
class sampler2D : public swizzle::glsl::texture_functions::tag
{
public:
enum WrapMode
{
Clamp,
Repeat,
MirrorRepeat
};
typedef const vec2& tex_coord_type;
sampler2D(const char* path, WrapMode wrapMode);
~sampler2D();
vec4 sample(const vec2& coord);
private:
SDL_Surface *m_image;
WrapMode m_wrapMode;
// do not allow copies to be made
sampler2D(const sampler2D&);
sampler2D& operator=(const sampler2D&);
};
// this where the magic happens...
namespace glsl_sandbox
{
// a nested namespace used when redefining 'inout' and 'out' keywords
namespace ref
{
#ifdef CXXSWIZZLE_VECTOR_INOUT_WRAPPER_ENABLED
typedef swizzle::detail::vector_inout_wrapper<vec2> vec2;
typedef swizzle::detail::vector_inout_wrapper<vec3> vec3;
typedef swizzle::detail::vector_inout_wrapper<vec4> vec4;
#else
typedef vec2& vec2;
typedef vec3& vec3;
typedef vec4& vec4;
#endif
typedef ::float_type& float_type;
}
namespace in
{
typedef const ::vec2& vec2;
typedef const ::vec3& vec3;
typedef const ::vec4& vec4;
typedef const ::float_type& float_type;
}
#include <swizzle/glsl/vector_functions.h>
// constants shaders are using
float_type time = 1;
vec2 mouse(0, 0);
vec2 resolution;
// constants some shaders from shader toy are using
vec2& iResolution = resolution;
float_type& iGlobalTime = time;
vec2& iMouse = mouse;
sampler2D diffuse("diffuse.png", sampler2D::Repeat);
sampler2D specular("specular.png", sampler2D::Repeat);
struct fragment_shader
{
vec2 gl_FragCoord;
vec4 gl_FragColor;
void operator()(void);
};
// change meaning of glsl keywords to match sandbox
#define uniform extern
#define in in::
#define out ref::
#define inout ref::
#define main fragment_shader::operator()
#define float float_type
#define bool bool_type
#pragma warning(push)
#pragma warning(disable: 4244) // disable return implicit conversion warning
#pragma warning(disable: 4305) // disable truncation warning
//#include "shaders/sampler.frag"
//#include "shaders/leadlight.frag"
//#include "shaders/terrain.frag"
//#include "shaders/complex.frag"
//#include "shaders/road.frag"
//#include "shaders/gears.frag"
//#include "shaders/water_turbulence.frag"
#include "shaders/sky.frag"
// be a dear a clean up
#pragma warning(pop)
#undef bool
#undef float
#undef main
#undef in
#undef out
#undef inout
#undef uniform
}
// these headers, especially SDL.h & time.h set up names that are in conflict with sandbox'es;
// sandbox should be moved to a separate h/cpp pair, but out of laziness... including them
// *after* sandbox solves it too
#include <iostream>
#include <sstream>
#include <SDL.h>
#ifdef SDLIMAGE_FOUND
#include <SDL_image.h>
#endif
#include <time.h>
#include <memory>
#include <functional>
#if OMP_ENABLED
#include <omp.h>
#endif
//! A handy way of creating (and checking) unique_ptrs of SDL objects
template <class T>
std::unique_ptr< T, std::function<void (T*)> > makeUnique(T* value, std::function<void (T*)> deleter)
{
if (!value)
{
throw std::runtime_error("Null pointer");
}
return std::unique_ptr<T, decltype(deleter)>(value, deleter);
}
//! As above, but allows null initialisation
template <class T>
std::unique_ptr< T, std::function<void (T*)> > makeUnique(std::function<void (T*)> deleter)
{
return std::unique_ptr<T, decltype(deleter)>(nullptr, deleter);
}
//! Just a RAII wrapper around SDL_mutex
struct ScopedLock
{
SDL_mutex* mutex;
explicit ScopedLock( SDL_mutex* mutex ) : mutex(mutex)
{
SDL_LockMutex(mutex);
}
template <class T>
explicit ScopedLock( std::unique_ptr<SDL_mutex, T>& mutex ) : mutex(mutex.get())
{
SDL_LockMutex(this->mutex);
}
~ScopedLock()
{
SDL_UnlockMutex(mutex);
}
};
//! The surface to draw on.
auto g_surface = makeUnique<SDL_Surface>( SDL_FreeSurface );
//! Mutex used when exchaning frame between threads
auto g_frameHandshakeMutex = makeUnique<SDL_mutex>( SDL_CreateMutex(), SDL_DestroyMutex );
//! Signaled when a frame has been processed
auto m_frameReceivedEvent = makeUnique<SDL_cond>( SDL_CreateCond(), SDL_DestroyCond );
//! Signaled when a frame is ready to be processed
auto m_frameReadyEvent = makeUnique<SDL_cond>( SDL_CreateCond(), SDL_DestroyCond );
//! Additional flag set when a frame becomes ready, in case main thread is not waiting
bool g_frameReady = false;
//! Stop drawing
bool g_cancelDraw = false;
//! Quit!
bool g_quit = false;
const float_type c_one = 1.0f;
const float_type c_zero = 0.0f;
template <size_t Align, typename T>
T* alignPtr(T* ptr)
{
static_assert((Align & (Align - 1)) == 0, "Align needs to be a power of two");
auto value = reinterpret_cast<ptrdiff_t>(ptr);
return reinterpret_cast<T*>((value + Align) & (~(Align - 1)));
}
//! Thread used for rendering; it invokes the shader
static int renderThread(void*)
{
using ::swizzle::detail::static_for;
// feel with 0...scalar_count
raw_float_type offsets;
{
// well... this calls for an explanation: why not std::aligned_storage?
// turns out there's a thing like max_align_t that defines max possible
// align; SSE/AVX data has greater align than max_align_t on compilers
// I checked, so std::aligned_storage is useless here.
uint8_t unalignedBlob[scalar_count * sizeof(float) + float_entries_align];
float* aligned = alignPtr<float_entries_align>(reinterpret_cast<float*>(unalignedBlob));
static_for<0, scalar_count>([&](size_t i) { aligned[i] = static_cast<float>(i); });
load_aligned(offsets, aligned);
}
while (true)
{
auto bmp = g_surface.get();
#if !defined(_DEBUG) && OMP_ENABLED
#pragma omp parallel
{
int thredsCount = omp_get_num_threads();
int threadNum = omp_get_thread_num();
int heightStep = thredsCount;
int heightStart = threadNum;
int heightEnd = bmp->h;
#else
{
int heightStep = 1;
int heightStart = 0;
int heightEnd = bmp->h;
#endif
// check the comment above for explanation
unsigned unalignedBlob[3 * (scalar_count + uint_entries_align / sizeof(unsigned))];
unsigned* pr = alignPtr<uint_entries_align>(unalignedBlob);
unsigned* pg = alignPtr<uint_entries_align>(pr + scalar_count);
unsigned* pb = alignPtr<uint_entries_align>(pg + scalar_count);
glsl_sandbox::fragment_shader shader;
for (int y = heightStart; !g_cancelDraw && y < heightEnd; y += heightStep)
{
shader.gl_FragCoord.y = static_cast<float>(bmp->h - 1 - y);
uint8_t * ptr = reinterpret_cast<uint8_t*>(bmp->pixels) + y * bmp->pitch;
int limitX = bmp->w - scalar_count;
for (int x = 0; x < bmp->w; x += scalar_count)
{
// since we are likely moving by more than one pixel,
// this will shift x and ptr left in case of width and scalar_count
// not being aligned; will redraw up to (scalar_count-1) pixels,
// but well, what you gonna do.
if (x > limitX)
{
ptr -= 3 * (x - limitX);
x = limitX;
}
shader.gl_FragCoord.x = static_cast<float>(x) + offsets;
// vvvvvvvvvvvvvvvvvvvvvvvvvv
// THE SHADER IS INVOKED HERE
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
shader();
// convert to [0;255]
auto color = glsl_sandbox::clamp(shader.gl_FragColor, c_zero, c_one);
color *= 255 + 0.5f;
// save in the bitmap
store_aligned(static_cast<uint_type>(static_cast<raw_float_type>(color.r)), pr);
store_aligned(static_cast<uint_type>(static_cast<raw_float_type>(color.g)), pg);
store_aligned(static_cast<uint_type>(static_cast<raw_float_type>(color.b)), pb);
static_for<0, scalar_count>([&](size_t i)
{
*ptr++ = static_cast<uint8_t>(pr[i]);
*ptr++ = static_cast<uint8_t>(pg[i]);
*ptr++ = static_cast<uint8_t>(pb[i]);
});
}
}
}
ScopedLock lock(g_frameHandshakeMutex);
if ( g_quit )
{
return 0;
}
else
{
// frame is ready, change bool and raise signal (in case main thread is waiting)
g_frameReady = true;
SDL_CondSignal(m_frameReadyEvent.get());
// wait for the main thread to process the frame
SDL_CondWait(m_frameReceivedEvent.get(), g_frameHandshakeMutex.get());
if ( g_quit )
{
return 0;
}
}
}
}
extern "C" int main(int argc, char* argv[])
{
using namespace std;
#ifdef SDLIMAGE_FOUND
// initialise SDLImage
int flags = IMG_INIT_JPG | IMG_INIT_PNG;
int initted = IMG_Init(flags);
if ((initted & flags) != flags)
{
cerr << "WARNING: failed to initialise required jpg and png support: " << IMG_GetError() << endl;
}
#endif
// get initial resolution
swizzle::glsl::vector<int, 2> initialResolution;
initialResolution.x = 128;
initialResolution.y = 128;
if (argc == 2)
{
std::stringstream s;
s << argv[1];
if ( !(s >> initialResolution) )
{
cerr << "ERROR: unable to parse resolution argument" << endl;
return 1;
}
}
if ( initialResolution.x <= 0 || initialResolution.y < 0 )
{
cerr << "ERROR: invalid resolution: " << initialResolution << endl;
return 1;
}
cout << "\n";
cout << "+/- - increase/decrease time scale\n";
cout << "lmb - update glsl_sandbox::mouse\n";
cout << "space - blit now! (show incomplete render)\n";
cout << "esc - quit\n\n";
// it doesn't need cleaning up
SDL_Surface* screen = nullptr;
try
{
// a function to resize the screen; throws if unsuccessful
auto resizeOrCreateScreen = [&](int w, int h) -> void
{
screen = SDL_SetVideoMode( w, h, 24, SDL_SWSURFACE | SDL_RESIZABLE);
if ( !screen )
{
throw std::runtime_error("Unable to set video mode");
}
};
// a function used to resize the surface
auto resizeOrCreateSurface = [&](int w, int h) -> void
{
g_surface.reset( SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 24, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 ) );
if ( !g_surface )
{
throw std::runtime_error("Unable to create surface");
}
// update shader value
glsl_sandbox::resolution.x = static_cast<float>(w);
glsl_sandbox::resolution.y = static_cast<float>(h);
};
// initial setup
if (SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
throw std::runtime_error("Unable to init SDL");
}
SDL_EnableKeyRepeat(200, 16);
SDL_WM_SetCaption("SDL/Swizzle", "SDL/Swizzle");
resizeOrCreateScreen(initialResolution.x, initialResolution.y);
resizeOrCreateSurface(initialResolution.x, initialResolution.y);
float timeScale = 1;
int frame = 0;
float time = 0;
vec2 mousePosition(0, 0);
bool pendingResize = false;
bool mousePressed = false;
auto renderThreadInstance = SDL_CreateThread(renderThread, nullptr);
clock_t begin = clock();
clock_t frameBegin = begin;
float lastFPS = 0;
while (!g_quit)
{
bool blitNow = false;
// process events
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch ( event.type )
{
case SDL_VIDEORESIZE:
if ( event.resize.w != screen->w || event.resize.h != screen->h )
{
resizeOrCreateScreen( event.resize.w, event.resize.h );
ScopedLock lock(g_frameHandshakeMutex);
g_cancelDraw = pendingResize = true;
}
break;
case SDL_QUIT:
{
ScopedLock lock(g_frameHandshakeMutex);
g_quit = g_cancelDraw = true;
}
break;
case SDL_KEYDOWN:
switch ( event.key.keysym.sym )
{
case SDLK_SPACE:
blitNow = true;
break;
case SDLK_ESCAPE:
{
ScopedLock lock(g_frameHandshakeMutex);
g_quit = g_cancelDraw = true;
}
break;
case SDLK_PLUS:
case SDLK_EQUALS:
timeScale *= 2.0f;
break;
case SDLK_MINUS:
timeScale /= 2.0f;
break;
default:
break;
}
break;
case SDL_MOUSEMOTION:
if (mousePressed)
{
mousePosition.x = static_cast<float>(event.button.x);
mousePosition.y = static_cast<float>(g_surface->h - 1 - event.button.y);
}
break;
case SDL_MOUSEBUTTONDOWN:
mousePressed = true;
mousePosition.x = static_cast<float>(event.button.x);
mousePosition.y = static_cast<float>(g_surface->h - 1 - event.button.y);
break;
case SDL_MOUSEBUTTONUP:
mousePressed = false;
default:
break;
}
}
bool doFlip = false;
{
ScopedLock lock(g_frameHandshakeMutex);
if ( g_quit )
{
if ( g_frameReady )
{
// unlock waiting thread
SDL_CondSignal( m_frameReceivedEvent.get() );
}
}
// if either the flag is set or variable has been signaled do the blit
else if ( blitNow || g_frameReady || SDL_CondWaitTimeout(m_frameReadyEvent.get(), g_frameHandshakeMutex.get(), 33) == 0 )
{
doFlip = true;
SDL_BlitSurface( g_surface.get(), NULL, screen, NULL );
if ( pendingResize )
{
resizeOrCreateSurface(screen->w, screen->h);
pendingResize = false;
}
if (g_frameReady)
{
auto currClock = clock();
lastFPS = 1.0f / static_cast<float>((currClock - frameBegin) / double(CLOCKS_PER_SEC));
frameBegin = currClock;
}
if (!blitNow || g_frameReady)
{
// transfer variables (resolution is transfered elsewhere)
glsl_sandbox::time = time;
glsl_sandbox::mouse = mousePosition / vec2(screen->w, screen->h);
// reset flags
g_cancelDraw = g_frameReady = false;
SDL_CondSignal( m_frameReceivedEvent.get() );
}
}
}
if (doFlip)
{
++frame;
SDL_Flip( screen );
}
cout << "frame: " << frame << "\t time: " << time << "\t timescale: " << timeScale << "\t fps: " << lastFPS << " \r";
cout.flush();
clock_t delta = clock() - begin;
time += static_cast<float>(delta / double(CLOCKS_PER_SEC) * timeScale);
begin = clock();
}
// wait for the render thread to stop
cout << "\nwaiting for the worker thread to finish...";
SDL_WaitThread(renderThreadInstance, nullptr);
}
catch ( exception& error )
{
cerr << "ERROR: " << error.what() << endl;
}
catch (...)
{
cerr << "ERROR: Unknown error" << endl;
}
SDL_Quit();
return 0;
}
sampler2D::sampler2D( const char* path, WrapMode wrapMode )
: m_wrapMode(wrapMode)
, m_image(nullptr)
{
#ifdef SDLIMAGE_FOUND
m_image = IMG_Load(path);
if (!m_image)
{
std::cerr << "WARNING: Failed to load texture " << path << "\n";
std::cerr << " SDL_Image message: " << IMG_GetError() << "\n";
}
#else
std::cerr << "WARNING: Texture " << path << " won't be loaded, SDL_image was not found.\n";
#endif
}
sampler2D::~sampler2D()
{
if ( m_image )
{
SDL_FreeSurface(m_image);
m_image = nullptr;
}
}
vec4 sampler2D::sample( const vec2& coord )
{
using namespace glsl_sandbox;
vec2 uv;
switch (m_wrapMode)
{
case Repeat:
uv = mod(coord, 1);
break;
case MirrorRepeat:
uv = abs(mod(coord - 1, 2) - 1);
break;
case Clamp:
default:
uv = clamp(coord, 0, 1);
break;
}
// OGL uses left-bottom corner as origin...
uv.y = 1 - uv.y;
if ( !m_image )
{
// checkers
auto s = step(0.5f, uv);
auto m2 = abs(s.x - s.y);
return mix(vec4(1, 0, 0, 1), vec4(0, 1, 0, 1), m2);
/*if (uv_x < 0.5 && uv_y < 0.5 || uv_x > 0.5 && uv_y > 0.5)
{
return vec4(1, 0, 0, 1);
}
else
{
return vec4(0, 1, 0, 1);
}*/
}
else
{
uint_type x = static_cast<uint_type>(static_cast<raw_float_type>(uv.x * (m_image->w - 1) + 0.5));
uint_type y = static_cast<uint_type>(static_cast<raw_float_type>(uv.y * (m_image->h - 1) + 0.5));
auto& format = *m_image->format;
uint_type index = (y * m_image->pitch + x * format.BytesPerPixel);
// stack-alloc blob for storing indices and color components
uint8_t unalignedBlob[5 * (scalar_count * sizeof(unsigned) + uint_entries_align)];
unsigned* pindex = alignPtr<uint_entries_align>(reinterpret_cast<unsigned*>(unalignedBlob));
unsigned* pr = alignPtr<uint_entries_align>(pindex + scalar_count);
unsigned* pg = alignPtr<uint_entries_align>(pr + scalar_count);
unsigned* pb = alignPtr<uint_entries_align>(pg + scalar_count);
unsigned* pa = alignPtr<uint_entries_align>(pb + scalar_count);
store_aligned(index, pindex);
// fill the buffers
swizzle::detail::static_for<0, scalar_count>([&](size_t i)
{
auto pixelPtr = static_cast<uint8_t*>(m_image->pixels) + pindex[i];
uint32_t pixel = 0;
for (size_t i = 0; i < format.BytesPerPixel; ++i)
{
pixel |= (pixelPtr[i] << (i * 8));
}
pr[i] = (pixel & format.Rmask) >> format.Rshift;
pg[i] = (pixel & format.Gmask) >> format.Gshift;
pb[i] = (pixel & format.Bmask) >> format.Bshift;
pa[i] = format.Amask ? ((pixel & format.Amask) >> format.Ashift) : 255;
});
// load data
uint_type r, g, b, a;
load_aligned(r, pr);
load_aligned(g, pg);
load_aligned(b, pb);
load_aligned(a, pa);
vec4 result;
result.r = static_cast<raw_float_type>(r);
result.g = static_cast<raw_float_type>(g);
result.b = static_cast<raw_float_type>(b);
result.a = static_cast<raw_float_type>(a);
return clamp(result / 255.0f, c_zero, c_one);
}
}<file_sep>/include/swizzle/detail/static_functors.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
namespace swizzle
{
namespace detail
{
template <typename VectorType>
struct functor_assign
{
template <size_t i> inline void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> inline void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) = other;
}
};
template <typename VectorType>
struct functor_add
{
template <size_t i> inline void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> inline void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) += other;
}
};
template <typename VectorType>
struct functor_sub
{
template <size_t i> void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) -= other;
}
};
template <typename VectorType>
struct functor_mul
{
template <size_t i> void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) *= other;
}
};
template <typename VectorType>
struct functor_div
{
template <size_t i> void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) /= other;
}
};
template <typename VectorType>
struct functor_neg
{
template <size_t i> void operator()(VectorType& result, const VectorType& other)
{
operator()<i>(result, other.at(i));
}
template <size_t i> void operator()(VectorType& result, const typename VectorType::scalar_type& other)
{
result.at(i) = -other;
}
};
template <typename VectorType>
struct functor_equals
{
template <size_t i> void operator()(const VectorType& a, const VectorType& b, typename VectorType::bool_type& result)
{
result &= (a.at(i) == b.at(i));
}
};
template <typename VectorType, size_t offset, typename OtherVectorType>
struct functor_compose_from_other_vector
{
template <size_t i> void operator()(VectorType& result, const OtherVectorType& other)
{
result.at(i) = other.at(i - offset);
}
};
}
}<file_sep>/sample/use_scalar.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <<EMAIL> at <EMAIL>>
#pragma once
// uncomment this if you want proxies to be passable as inout and out parameters
// #define CXXSWIZZLE_VECTOR_INOUT_WRAPPER_ENABLED
#include <type_traits>
#include <swizzle/glsl/scalar_support.h>
typedef float float_type;
typedef float raw_float_type;
typedef unsigned uint_type;
typedef bool bool_type;
const size_t scalar_count = 1;
const size_t float_entries_align = std::alignment_of<float>::value;
const size_t uint_entries_align = std::alignment_of<unsigned>::value;
template <typename T>
inline void store_aligned(T&& value, typename std::remove_reference<T>::type* target)
{
*target = std::forward<T>(value);
}
template <typename T>
inline void load_aligned(T& value, const T* data)
{
value = *data;
}<file_sep>/include/swizzle/glsl/scalar_support.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at g<EMAIL>.com>
#pragma once
#include <swizzle/detail/vector_traits.h>
#include <cmath>
namespace swizzle
{
namespace glsl
{
template < class ScalarType, size_t Size >
class vector;
}
namespace detail
{
template <class T>
struct get_vector_type_impl_for_scalar
{
typedef ::swizzle::glsl::vector<T, 1> type;
};
template <>
struct get_vector_type_impl<bool> : get_vector_type_impl_for_scalar<bool>
{};
template <>
struct get_vector_type_impl<float> : get_vector_type_impl_for_scalar<float>
{};
template <>
struct get_vector_type_impl<double> : get_vector_type_impl_for_scalar<double>
{};
template <>
struct get_vector_type_impl<signed int> : get_vector_type_impl_for_scalar<signed int>
{};
template <>
struct get_vector_type_impl<unsigned int> : get_vector_type_impl_for_scalar<unsigned int>
{};
template <>
struct get_vector_type_impl<signed short> : get_vector_type_impl_for_scalar<signed short>
{};
template <>
struct get_vector_type_impl<unsigned short> : get_vector_type_impl_for_scalar<unsigned short>
{};
}
}
// add missing math functions
namespace std
{
inline float step(float edge, float x)
{
return x > edge ? 1.0f : 0.0f;
}
inline float rsqrt(float x)
{
return 1.0f / sqrt(x);
}
inline float sign(float x)
{
return (0 < x) - (x < 0);
}
inline float fract(float x)
{
return x - floor(x);
}
}<file_sep>/include/swizzle/detail/primitive_wrapper.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
#include <cmath>
#include <swizzle/detail/utils.h>
namespace swizzle
{
namespace detail
{
template <typename InternalType, typename ExternalType, typename BoolType = bool, typename AssignPolicy = nothing>
class primitive_wrapper
{
public:
typedef InternalType internal_type;
typedef ExternalType external_type;
typedef primitive_wrapper this_type;
typedef AssignPolicy assign_policy_type;
typedef BoolType bool_type;
typedef const primitive_wrapper& this_arg;
typedef const external_type& external_type_arg;
private:
internal_type data;
public:
primitive_wrapper()
{}
primitive_wrapper(const internal_type& data)
: data(data)
{ }
template <typename T>
primitive_wrapper(T && data, typename std::enable_if< std::is_convertible<T, internal_type>::value >::type* = nullptr)
: data(std::forward<T>(data))
{ }
primitive_wrapper(external_type_arg data)
: data(data)
{}
// functions
inline friend this_type sin(this_arg x)
{
return sin(x.data);
}
inline friend this_type cos(this_arg x)
{
return cos(x.data);
}
inline friend this_type tan(this_arg x)
{
return tan(x.data);
}
inline friend this_type asin(this_arg x)
{
return asin(x.data);
}
inline friend this_type acos(this_arg x)
{
return acos(x.data);
}
inline friend this_type atan(this_arg x)
{
return atan(x.data);
}
inline friend this_type atan2(this_arg y, this_arg x)
{
return atan2(y.data, x.data);
}
inline friend this_type abs(this_arg x)
{
return abs(x.data);
}
inline friend this_type pow(this_arg x, this_arg n)
{
return pow(x.data, n.data);
}
inline friend this_type exp(this_arg x)
{
return exp(x.data);
}
inline friend this_type log(this_arg x)
{
return log(x.data);
}
inline friend this_type exp2(this_arg x)
{
return exp2(x.data);
}
inline friend this_type log2(this_arg x)
{
return log2(x.data);
}
inline friend this_type sqrt(this_arg x)
{
return sqrt(x.data);
}
inline friend this_type rsqrt(this_arg x)
{
return rsqrt(x.data);
}
inline friend this_type sign(this_arg x)
{
return sign(x.data);
}
inline friend this_type fract(this_arg x)
{
return fract(x.data);
}
inline friend this_type floor(this_arg x)
{
return floor(x.data);
}
inline friend this_type ceil(this_arg x)
{
return ceil(x.data);
}
inline friend this_type mod(this_arg x, this_arg y)
{
return mod(x.data, y.data);
}
inline friend this_type min(this_arg x, this_arg y)
{
return min(x.data, y.data);
}
inline friend this_type max(this_arg x, this_arg y)
{
return max(x.data, y.data);
}
inline friend this_type step(this_arg edge, this_arg x)
{
return step(edge.data, x.data);
}
// unary operators
this_type operator-() const
{
return -data;
}
this_type& operator+=(this_arg other)
{
return *this = *this + other;
}
this_type& operator-=(this_arg other)
{
return *this = *this - other;
}
this_type& operator*=(this_arg other)
{
return *this = *this * other;
}
this_type& operator/=(this_arg other)
{
return *this = *this / other;
}
this_type& operator+=(external_type_arg other)
{
return *this = *this + other;
}
this_type& operator-=(external_type_arg other)
{
return *this = *this - other;
}
this_type& operator*=(external_type_arg other)
{
return *this = *this * other;
}
this_type& operator/=(external_type_arg other)
{
return *this = *this / other;
}
// binary operators
inline friend this_type operator+(this_arg a, this_arg b)
{
return a.data + b.data;
}
inline friend this_type operator-(this_arg a, this_arg b)
{
return a.data - b.data;
}
inline friend this_type operator*(this_arg a, this_arg b)
{
return a.data * b.data;
}
inline friend this_type operator/(this_arg a, this_arg b)
{
return a.data / b.data;
}
inline friend this_type operator+(this_arg a, external_type_arg b)
{
return a.data + b;
}
inline friend this_type operator+(external_type_arg a, this_arg b)
{
return b + a;
}
inline friend this_type operator-(this_arg a, external_type_arg b)
{
return a.data - b;
}
inline friend this_type operator-(external_type_arg a, this_arg b)
{
return internal_type(a) - b.data;
}
inline friend this_type operator*(this_arg a, external_type_arg b)
{
return a.data * b;
}
inline friend this_type operator*(external_type_arg a, this_arg b)
{
return b * a;
}
inline friend this_type operator/(this_arg a, external_type_arg b)
{
return a.data / b;
}
inline friend this_type operator/(external_type_arg a, this_arg b)
{
return internal_type(a) / b.data;
}
// casts
//! To avoid ADL-hell, cast is explict.
inline explicit operator internal_type() const
{
return data;
}
// assignment
inline this_type& operator=(this_arg other)
{
// this is where the masking magic may happen
assign(other, std::is_same<assign_policy_type, nothing>());
return *this;
}
// comparisons
inline friend bool_type operator>(this_arg a, this_arg b)
{
return a.data > b.data;
}
inline friend bool_type operator>=(this_arg a, this_arg b)
{
return a.data >= b.data;
}
inline friend bool_type operator<(this_arg a, this_arg b)
{
return a.data < b.data;
}
inline friend bool_type operator<=(this_arg a, this_arg b)
{
return a.data <= b.data;
}
inline friend bool_type operator==(this_arg a, this_arg b)
{
return a.data == b.data;
}
inline friend bool_type operator!=(this_arg a, this_arg b)
{
return a.data != b.data;
}
// for CxxSwizzle ADL-magic
this_type decay() const
{
return *this;
}
private:
inline void assign(this_arg other, std::false_type)
{
assign_policy_type::assign(data, other.data);
}
inline void assign(this_arg other, std::true_type)
{
data = other.data;
}
};
}
}<file_sep>/include/swizzle/detail/glsl/vector_functions_adapter.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
#include <cmath>
#include <swizzle/detail/utils.h>
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(name) \
static vector_type call_##name(vector_arg_type x) { return construct_static(functor_##name{}, x); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(name) \
static vector_type call_##name(vector_arg_type x, vector_arg_type y) { return construct_static(functor_##name{}, x, y); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS(name) \
static vector_type call_##name(vector_arg_type x, scalar_arg_type y) { return construct_static(functor_##name{}, x, y); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SV(name) \
static vector_type call_##name(scalar_arg_type x, vector_arg_type y) { return construct_static(functor_##name{}, x, y); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVV(name) \
static vector_type call_##name(vector_arg_type x, vector_arg_type y, vector_arg_type z) { return construct_static(functor_##name{}, x, y, z); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVS(name) \
static vector_type call_##name(vector_arg_type x, vector_arg_type y, scalar_arg_type z) { return construct_static(functor_##name{}, x, y, z); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VSS(name) \
static vector_type call_##name(vector_arg_type x, scalar_arg_type y, scalar_arg_type z) { return construct_static(functor_##name{}, x, y, z); }
#define CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SSV(name) \
static vector_type call_##name(scalar_arg_type x, scalar_arg_type y, vector_arg_type z) { return construct_static(functor_##name{}, x, y, z); }
namespace swizzle
{
namespace detail
{
namespace glsl
{
//! A class providing static functions matching GLSL's vector functions. Uses naive approach, i.e.
//! everything is done components-wise, using stdlib's math functions.
template <class Base, template <class, size_t> class VectorType, class ScalarType, size_t Size>
class vector_functions_adapter : public Base
{
public:
typedef VectorType<ScalarType, Size> vector_type;
typedef const VectorType<ScalarType, Size>& vector_arg_type;
typedef VectorType<bool, Size> bool_vector_type;
typedef ScalarType scalar_type;
typedef const ScalarType& scalar_arg_type;
private:
struct not_available;
//! Fires Func for each component an assigns back the result
template <typename Func, typename... Args>
static vector_type construct_static(Func func, Args&&... args)
{
vector_type result;
detail::static_for_with_static_call<0, Size>(func, result, std::forward<Args>(args)...);
return result;
}
template <class T, class Func>
static VectorType<T, Size> construct(Func func)
{
VectorType<T, Size> result;
detail::static_for<0, Size>([&](size_t i) -> void { result[i] = func(i); });
return result;
}
private:
struct functor_radians
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
result.at(i) = x.at(i) * scalar_type(3.14159265358979323846 / 180);
}
};
struct functor_degrees
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
result.at(i) = x.at(i) * scalar_type(180 / 3.14159265358979323846);
}
};
struct functor_mul
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type y)
{
result.at(i) = x.at(i) * y;
}
};
struct functor_sin
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = sin(x.at(i));
}
};
struct functor_cos
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = cos(x.at(i));
}
};
struct functor_tan
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = tan(x.at(i));
}
};
struct functor_asin
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = asin(x.at(i));
}
};
struct functor_acos
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = acos(x.at(i));
}
};
struct functor_atan
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = atan(x.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type y, vector_arg_type x)
{
using namespace std;
result.at(i) = atan2(y.at(i), x.at(i));
}
};
struct functor_pow
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type y)
{
using namespace std;
result.at(i) = pow(x.at(i), y);
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y)
{
using namespace std;
result.at(i) = pow(x.at(i), y.at(i));
}
};
struct functor_abs
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = abs(x.at(i));
}
};
struct functor_exp
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = exp(x.at(i));
}
};
struct functor_log
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = log(x.at(i));
}
};
struct functor_exp2
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = exp2(x.at(i));
}
};
struct functor_log2
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = log2(x.at(i));
}
};
struct functor_sqrt
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = sqrt(x.at(i));
}
};
struct functor_inversesqrt
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = rsqrt(x.at(i));
}
};
struct functor_sign
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = sign(x.at(i));
}
};
struct functor_fract
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
scalar_type xx = x.at(i);
result.at(i) = xx - floor(xx);
}
};
struct functor_mod
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y)
{
operator() < i > (result, x, y.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type y)
{
using namespace std;
auto xx = x.at(i);
result.at(i) = xx - y * floor(xx / y);
}
};
struct functor_min
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y)
{
operator() < i > (result, x, y.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type y)
{
using namespace std;
result.at(i) = min(x.at(i), y);
}
};
struct functor_max
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y)
{
operator() < i > (result, x, y.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type y)
{
using namespace std;
result.at(i) = max(x.at(i), y);
}
};
struct functor_clamp
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type a, vector_arg_type b)
{
operator() < i > (result, x, a.at(i), b.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, scalar_arg_type a, scalar_arg_type b)
{
using namespace std;
result.at(i) = max(min(x.at(i), b), a);
}
};
struct functor_mix
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y, vector_arg_type a)
{
operator() < i > (result, x, y, a.at(i));
}
template <size_t i> void operator()(vector_type& result, vector_arg_type x, vector_arg_type y, scalar_arg_type a)
{
using namespace std;
result.at(i) = x.at(i) + a * (y.at(i) - x.at(i));
}
};
struct functor_step
{
template <size_t i> void operator()(vector_type& result, vector_arg_type edge, vector_arg_type x)
{
operator() < i > (result, edge.at(i), x);
}
template <size_t i> void operator()(vector_type& result, scalar_arg_type edge, vector_arg_type x)
{
using namespace std;
result.at(i) = step(edge, x.at(i));
}
};
struct functor_smoothstep
{
template <size_t i> void operator()(vector_type& result, vector_arg_type edge0, vector_arg_type edge1, vector_arg_type x)
{
operator() < i > (result, edge0.at(i), edge1.at(i), x);
}
template <size_t i> void operator()(vector_type& result, scalar_arg_type edge0, scalar_arg_type edge1, vector_arg_type x)
{
using namespace std;
auto t = (x.at(i) - edge0) / (edge1 - edge0);
t = min(max(t, scalar_arg_type(0)), scalar_arg_type(1));
result.at(i) = t * t * (3 - 2 * t);
}
};
struct functor_dot
{
template <size_t i> void operator()(scalar_type& result, vector_arg_type x, vector_arg_type y)
{
result += x.at(i) * y.at(i);
}
};
struct functor_floor
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = floor(x.at(i));
}
};
struct functor_ceil
{
template <size_t i> void operator()(vector_type& result, vector_arg_type x)
{
using namespace std;
result.at(i) = ceil(x.at(i));
}
};
public:
// these functions do component-wise transform
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(degrees)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(radians)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(sin)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(cos)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(tan)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(asin)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(acos)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(atan)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(atan)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(abs)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(pow)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS(pow)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(exp)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(log)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(exp2)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(log2)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(sqrt)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(inversesqrt)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(sign)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(fract)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(floor)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V(ceil)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(mod)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS(mod)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(min)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS(min)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(max)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS(max)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVV(clamp)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VSS(clamp)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVV(mix)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVS(mix)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV(step)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SV(step)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVV(smoothstep)
CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SSV(smoothstep)
// these are more complex
static vector_type call_reflect(vector_arg_type I, vector_arg_type N)
{
//return (I - 2 * call_dot(I, N) * N);
scalar_type dot2 = 2 * call_dot(I, N);
vector_type n = N;
n *= dot2;
vector_type i = I;
i -= n;
return i;
}
// Geometric functions
static scalar_type call_length(vector_arg_type x)
{
using namespace std;
scalar_type dot = call_dot(x, x);
return sqrt(dot);
}
static scalar_type call_distance(vector_arg_type p0, const vector_arg_type p1)
{
return call_length(p0 - p1);
}
static scalar_type call_dot(vector_arg_type x, vector_arg_type y)
{
scalar_type result = 0;
detail::static_for_with_static_call<0, Size>(functor_dot{}, result, x, y);
return result;
}
static vector_type call_normalize(vector_arg_type x)
{
using namespace std;
scalar_type dot = call_dot(x, x);
return vector_type(x) * rsqrt(dot);
}
static typename std::conditional<Size == 3, vector_type, not_available>::type call_cross(const vector_type& x, const vector_type& y)
{
auto rx = x[1] * y[2] - x[2] * y[1];
auto ry = x[2] * y[0] - x[0] * y[2];
auto rz = x[0] * y[1] - x[1] * y[0];
return vector_type(rx, ry, rz);
}
static bool_vector_type call_lessThan(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] < y[i]; });
}
static bool_vector_type call_lessThanEqual(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] <= y[i]; });
}
static bool_vector_type call_greaterThan(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] > y[i]; });
}
static bool_vector_type call_greaterThanEqual(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] >= y[i]; });
}
static bool_vector_type call_equal(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] == y[i]; });
}
static bool_vector_type call_notEqual(vector_arg_type x, vector_arg_type y)
{
return construct<bool>([&](size_t i) -> bool { return x[i] != y[i]; });
}
static bool call_any(typename std::conditional<std::is_same<ScalarType, bool>::value, vector_arg_type, not_available>::type x)
{
bool result = false;
detail::static_for<0, Size>([&](size_t i) -> void { result |= x[i]; });
return result;
}
static bool call_all(typename std::conditional< std::is_same<scalar_type, bool>::value, vector_arg_type, not_available>::type x)
{
bool result = true;
detail::static_for<0, Size>([&](size_t i) -> void { result &= x[i]; });
return result;
}
static vector_type call_not(typename std::conditional< std::is_same<scalar_type, bool>::value, vector_arg_type, not_available>::type x)
{
return construct<bool>([&](size_t i) -> bool { return !x[i]; });
}
};
}
}
}
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_V
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VV
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VS
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SV
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVV
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VVS
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_VSS
#undef CXXSWIZZLE_DETAIL_SIMPLE_TRANSFORM_SSV<file_sep>/unit_test/test_proxies.cpp
// CxxSwizzle
// Copyright (c) 2013, <NAME> <gwiazdorrr+github at gmail.com>
#define CXXSWIZZLE_VECTOR_INOUT_WRAPPER_ENABLED
#include <boost/test/unit_test.hpp>
#include <array>
#include <limits>
#include "setup.h"
namespace
{
void foo(swizzle::detail::vector_inout_wrapper<vec2> a)
{}
void foo(swizzle::detail::vector_inout_wrapper<vec3> a)
{}
void foo(swizzle::detail::vector_inout_wrapper<vec4> a)
{}
}
BOOST_AUTO_TEST_SUITE(Proxies)
BOOST_AUTO_TEST_CASE(passing)
{
vec4 v;
foo(v.xz);
foo(v.xzy);
foo(v.xzyw);
}
BOOST_AUTO_TEST_SUITE_END()<file_sep>/include/swizzle/detail/vector_inout_wrapper.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
#include <type_traits>
#include <swizzle/detail/utils.h>
#include <swizzle/detail/vector_traits.h>
#include <functional>
namespace swizzle
{
namespace detail
{
//! A wrapper for a vector reference. Makes inout and out parameters work with proxies, but at a cost
//! of std::function call (and likely an alloc, too).
template <class VectorType>
struct vector_inout_wrapper : public VectorType
{
typedef VectorType vector_type;
private:
std::function<void(const vector_type&)> m_cleanup;
public:
vector_inout_wrapper(vector_type& value)
: vector_type(value)
{
m_cleanup = [&](const vector_type& v) -> void { value = v; };
}
vector_inout_wrapper(const vector_type& value, std::function<void(const vector_type&)> cleanup)
: vector_type(value)
, m_cleanup(cleanup)
{
}
~vector_inout_wrapper()
{
if (m_cleanup)
{
m_cleanup(*this);
}
}
};
template <class TVector>
struct get_vector_type_impl< vector_inout_wrapper<TVector> >
{
typedef TVector type;
};
}
}<file_sep>/include/swizzle/glsl/texture_functions.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
namespace swizzle
{
namespace glsl
{
namespace texture_functions
{
//! Deriving from this struct will make sure all texture* calls are going to be ADL resolved, without
//! "using" this namespace.
struct tag {};
template <class Sampler>
auto texture(Sampler& sampler, typename Sampler::tex_coord_type coord) -> decltype ( sampler.sample(coord) )
{
return sampler.sample(coord);
}
template <class Sampler>
auto texture(const Sampler& sampler, typename Sampler::tex_coord_type coord, float bias) -> decltype ( sampler.sample(coord, bias) )
{
return sampler.sample(coord, bias);
}
template <class Sampler>
auto textureOffset(const Sampler& sampler, typename Sampler::tex_coord_type coord, typename Sampler::tex_offset_type offset) -> decltype( sampler.sampleOffset(coord, offset) )
{
return sampler.sample(coord, offset);
}
template <class Sampler>
auto textureOffset(const Sampler& sampler, typename Sampler::tex_coord_type coord, typename Sampler::tex_offset_type offset, float bias) -> decltype( sampler.sampleOffset(coord, offset, bias) )
{
return sampler.sample(coord, offset, bias);
}
}
}
}<file_sep>/unit_test/test_basic.cpp
// CxxSwizzle
// Copyright (c) 2013, <NAME> <gwiazdorrr+github at gmail.com>
#include <boost/test/unit_test.hpp>
#include <array>
#include <limits>
#include "setup.h"
template <class TVec, class TScalar>
void test_operators(TVec a, TScalar b)
{
size_t index = 0;
auto negPredicate = [=](typename TVec::scalar_type x, typename TVec::scalar_type y) -> bool { return are_close(x, -y); };
auto addPredicate = [=](typename TVec::scalar_type x, typename TVec::scalar_type y) -> bool { return are_close(x, y + b); };
auto subPredicate = [=](typename TVec::scalar_type x, typename TVec::scalar_type y) -> bool { return are_close(x, y - b); };
auto mulPredicate = [=](typename TVec::scalar_type x, typename TVec::scalar_type y) -> bool { return are_close(x, y * b); };
auto divPredicate = [=](typename TVec::scalar_type x, typename TVec::scalar_type y) -> bool { return are_close(x, y / b); };
BOOST_ASSERT( are_equal(-a, a, negPredicate) );
BOOST_ASSERT( are_equal<TVec>(a + b, a, addPredicate) );
BOOST_ASSERT( are_equal<TVec>(b + a, a, addPredicate) );
BOOST_ASSERT( are_equal<TVec>(TVec(a) += b, a, addPredicate) );
BOOST_ASSERT( are_equal<TVec>(a - b, a, subPredicate) );
BOOST_ASSERT( are_equal<TVec>(-(b - a), a, subPredicate) );
BOOST_ASSERT( are_equal<TVec>(TVec(a) -= b, a, subPredicate) );
BOOST_ASSERT( are_equal<TVec>(a * b, a, mulPredicate) );
BOOST_ASSERT( are_equal<TVec>(b * a, a, mulPredicate) );
BOOST_ASSERT( are_equal<TVec>(TVec(a) *= b, a, mulPredicate) );
BOOST_ASSERT( are_equal<TVec>(a / b, a, divPredicate) );
BOOST_ASSERT( are_equal<TVec>(1 / (b / a), a, divPredicate) );
BOOST_ASSERT( are_equal<TVec>(TVec(a) /= b, a, divPredicate) );
}
template <class TVec>
void test_oprators(TVec a)
{
test_operators(a, double(1));
test_operators(a, int(1));
test_operators(a, float(1));
}
BOOST_AUTO_TEST_SUITE(Construction)
BOOST_AUTO_TEST_CASE(vec1_basic)
{
// default
vec1 a;
BOOST_CHECK(a.x == 0.0f);
// with a value
vec1 b(666);
BOOST_CHECK(b.x == 666.0f);
// copy
vec1 c(b);
BOOST_CHECK(b.x == c.x);
// from proxy
vec1 d(c.x);
BOOST_CHECK(c.x == d.x);
}
BOOST_AUTO_TEST_CASE(vec2_basic)
{
BOOST_CHECK( are_all_equal( vec2(), 0) );
BOOST_CHECK( !are_all_equal( vec2(), 666) );
BOOST_CHECK( are_all_equal( vec2(666), 666) );
// with a value
vec2 b(1, 2);
BOOST_CHECK(b.x == 1 && b.y == 2);
BOOST_CHECK( !are_all_equal(b, 666) );
// copy
vec2 c(b);
BOOST_CHECK(are_equal(b, c));
// from proxy (reverse)
vec2 d(c.yx);
BOOST_CHECK(are_equal_reverse(c, d));
c.yx = c;
}
BOOST_AUTO_TEST_CASE(vec3_basic)
{
BOOST_CHECK( are_all_equal( vec3(), 0) );
BOOST_CHECK( !are_all_equal( vec3(), 666) );
BOOST_CHECK( are_all_equal( vec3(666), 666) );
// with a value
vec3 b(1, 2, 3);
BOOST_CHECK(b.x == 1 && b.y == 2 && b.z == 3);
BOOST_CHECK( !are_all_equal(b, 666) );
// copy
vec3 c(b);
BOOST_CHECK(are_equal(b, c));
// from proxy (reverse)
vec3 d(c.zyx);
BOOST_CHECK(are_equal_reverse(c, d));
}
BOOST_AUTO_TEST_CASE(vec4_basic)
{
BOOST_CHECK( are_all_equal( vec4(), 0) );
BOOST_CHECK( !are_all_equal( vec4(), 666) );
BOOST_CHECK( are_all_equal( vec4(666), 666) );
// with a value
vec4 b(1, 2, 3, 4);
BOOST_CHECK( b.x == 1 && b.y == 2 && b.z == 3 && b.w == 4 );
BOOST_CHECK( !are_all_equal(b, 666) );
// copy
vec4 c(b);
BOOST_CHECK(are_equal(b, c));
// from proxy (reverse)
vec4 d(c.wzyx);
BOOST_CHECK(are_equal_reverse(c, d));
}
BOOST_AUTO_TEST_CASE(vec_proxy_test)
{
vec4 v1(1, 2, 3, 4);
// check if values make sense
BOOST_CHECK( are_equal<vec1>(vec1(1), vec1(v1.x)) );
BOOST_CHECK( are_equal<vec1>(vec1(4), vec1(v1.w)) );
BOOST_CHECK( !are_equal<vec1>(vec1(1), vec1(v1.w)) );
BOOST_CHECK( are_equal<vec2>(vec2(1, 2), v1.xy) );
BOOST_CHECK( are_equal<vec2>(vec2(4, 3), v1.wz) );
BOOST_CHECK( are_equal<vec2>(vec2(1, 4), v1.xw) );
BOOST_CHECK( !are_equal<vec2>(vec2(1, 2), v1.xw) );
BOOST_CHECK( are_equal<vec3>(vec3(1, 2, 3), v1.xyz) );
BOOST_CHECK( are_equal<vec3>(vec3(4, 3, 2), v1.wzy) );
BOOST_CHECK( are_equal<vec3>(vec3(1, 4, 4), v1.xww) );
BOOST_CHECK( !are_equal<vec3>(vec3(1, 2, 3), v1.xww) );
BOOST_CHECK( are_equal<vec4>(vec4(1, 2, 3, 4), v1.xyzw) );
BOOST_CHECK( are_equal<vec4>(vec4(4, 3, 2, 1), v1.wzyx) );
BOOST_CHECK( are_equal<vec4>(vec4(3, 2, 2, 4), v1.zyyw) );
}
BOOST_AUTO_TEST_CASE(vec_test_operators)
{
test_oprators( vec1(0) );
test_oprators( vec2(1, 2) );
test_oprators( vec3(1, 2, 3) );
test_oprators( vec4(1, 2, 3, 4) );
}
BOOST_AUTO_TEST_CASE(vec1_test_construct)
{
// if it compiles then great
vec1 v1(1);
vec2 v2(2, 3);
vec3 v3(4, 5, 6);
vec4 v4(7, 8, 9, 10);
BOOST_ASSERT( are_equal(vec1(v1.x), v1)) ;
BOOST_ASSERT( are_equal(vec1(v2.y), vec1(v2.yxyx)) );
BOOST_ASSERT( are_equal(vec1(v3.x), vec1(v3)) );
BOOST_ASSERT( are_equal(vec1(v4.w), vec1(v4.wwww)) );
}
BOOST_AUTO_TEST_CASE(vec2_test_construct)
{
// if it compiles then great
vec1 v1(1);
vec2 v2(2, 3);
vec3 v3(4, 5, 6);
vec4 v4(7, 8, 9, 10);
BOOST_ASSERT( are_equal(vec2(v1.x, v1.x), vec2(v1.xx)) );
BOOST_ASSERT( are_equal(vec2(v2.x, v2.y), vec2(v2.x, v2.yx)) );
BOOST_ASSERT( are_equal(vec2(v3.z, v3.y), vec2(v3.zyzz)) );
BOOST_ASSERT( are_equal(vec2(v4.w, v4.w), vec2(v4.w, v4.wwxx)) );
}
BOOST_AUTO_TEST_CASE(vec3_test_construct)
{
// if it compiles then great
vec1 v1(1);
vec2 v2(2, 3);
vec3 v3(4, 5, 6);
vec4 v4(7, 8, 9, 10);
BOOST_ASSERT( are_equal(vec3(v1.x, v1.x, v1.x), vec3(v1.xxxx)) );
BOOST_ASSERT( are_equal(vec3(v2.x, v2.y, v2.x), vec3(v2.x, v2.yx)) );
BOOST_ASSERT( are_equal(vec3(v3.x, v3.y, v3.z), vec3(v3)) );
BOOST_ASSERT( are_equal(vec3(v4.w, v4.w, v4.w), vec3(v4.w, v4.wwxx)) );
}
BOOST_AUTO_TEST_CASE(vec4_test_construct)
{
// if it compiles then great
vec1 v1(1);
vec2 v2(2, 3);
vec3 v3(4, 5, 6);
vec4 v4(7, 8, 9, 10);
BOOST_ASSERT( are_equal(vec4(v1.x, v1.x, v1.x, v1.x), vec4(v1.xxxx)) );
BOOST_ASSERT( are_equal(vec4(v2.x, v2.y, v2.x, v2.x), vec4(v2.x, v2.y, v2.x, v2.xyxy)) );
BOOST_ASSERT( are_equal(vec4(v3.x, v3.y, v3.z, v3.z), vec4(v3, v3.z)) );
BOOST_ASSERT( are_equal(vec4(v4.w, v4.w, v4.w, v4.x), vec4(v4.w, v4.wwxx)) );
}
BOOST_AUTO_TEST_SUITE_END()<file_sep>/README.md
CxxSwizzle
==========
2015.02.17 Update: The library now comes with SIMD support. More info soon.
CxxSwizzle (a reality-friendly way of writing down "C++ Swizzle") is a header-only, dependency free extensible library bringing shader languages' (GLSL, HSLS) vector "swizzle" syntax into C++. Basically, you can do this in C++ now:
vec4 foo(0); // 0,0,0,0
foo.yx = vec2(2, 1); // 1,2,0,0
foo.zw = foo.xy * 2; // 1,2,2,4
vec2 bar = max(foo.xw, foo.yz).yx; // 4,2
bar = clamp(foo.xw, 0, 2); // 1,2
mat2 m(foo.xyz, 1); // 1,2,2,1
bar *= m; // 5,2
// etc.
What's the use? Familiar and easy to use syntax for non-critical pieces of code. Also, given GLSL/HLSL similarity to C you can execute most shaders directly as C++ code, with just a little help from the preprocessor (keyword substitution). That gives debugging and flexibility capabilities unpararelled by existing shader debugging solutions - you can use IDE of your choice, add logging, assertions, breakpoints (even conditional ones!), unit tests for functions etc.
The following snippet will compile both in C++ and GLSL.
#ifdef __cplusplus
#include <cassert>
#include <iostream>
#else
#define assert(x)
#define CPP_DO(x)
#endif
void test_sin(vec4 a)
{
vec4 b = sin(a);
// sanity checks
assert( all(lessThanEqual(b, vec4(1))) );
assert( all(greaterThanEqual(b, vec4(-1))) );
// print out
CPP_DO( std::cout << "sin(" << a << ") == " << b << "\n"; )
#ifdef __cplusplus
// test trigonometric symmetry
const float c_pi = 3.14159265358979323846f;
const vec4 c_eps = vec4(0.0001);
vec4 c = cos(c_pi/2 - a);
if ( any(greaterThan(abs(c - b), c_eps)) )
{
// programmatic breakpoint
__asm int 3;
}
#endif
}
In fact you can pretty much take any shader from http://glsl.heroku.com or http://shadertoy.com (the second one takes loooong to load) and execute it as C++ code. The sample project is a simplistic example of how to do exactly that. For instance, this shader from sample, can be run both as GLSL (try it here: http://glsl.heroku.com/e#10661.0) and as C++ (in sample, shaders/leadlight.frag):
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
// Leadlight by @hintz 2013-05-02
void main()
{
vec2 position = gl_FragCoord.xy / resolution.x - 0.5;
float r = length(position);
float a = atan(position.y, position.x);
float t = time + 100.0/(r+1.0);
float light = 15.0*abs(0.05*(sin(t)+sin(time+a*8.0)));
vec3 color = vec3(-sin(r*5.0-a-time+sin(r+t)), sin(r*3.0+a-cos(time)+sin(r+t)), cos(r+a*2.0+log(5.001-(a/4.0))+time)-sin(r+t));
gl_FragColor = vec4((normalize(color)+0.3) * light , 1.0);
}
Note that contrary to the headers the sample needs SDL library.
HLSL can be compiled as well, but likely not without some changes. There's no way to make semantics valid in C++, for instance. Also, named cbuffers would need some work. I am still looking into this.
The library is written in C++11 subset supported by VS2013. It works with g++ 4.8.1 and most likely will work with clang, too. There are no external dependencies.
There is a legacy branch written in C++11 subset supported by VS2010 - most notably the lack of variadic templates was a great pain and limitation. That's why it's no longer maintained.
Compability
---------------------------------------------------
When using g++, following flags must be added to the compiler command line:
-std=c++11 -fno-operator-names
The less obvious second flag disables alterantive operators names, such as `and` ar `not` which, coincidentally, are also the names of some GLSL functions.
If using CMake, just set CMAKE_CXX_FLAGS variable.
Diferences between GLM
---------------------------------------------------
This shows up a lot in comments - why use CxxSwizzle and not GLM (http://glm.g-truc.net)? Well, here are main differences:
* GLM swizzling seems kind of half done and has its quirks. Bottom line, there's nowhere near as much flexibility as you have with GLSL/HLSL and CxxSwizzle.
* GLM is highly susceptible to ambiguity errors. In GLSL/HLSL number literals are contextual, i.e. `0.5` can mean any precision floating point number. Not in C++.
* GLM can't handle some vector construction cases.
* GLM has more features. Covers greater array of GLSL functions, as well as "support" OGL and GLU functions. Something CxxSwizzle will hopefully catch up soon.
* GLM has an optional SIMD support. Focus of CxxSwizzle was not a performance; it *is going to be painfully slow* regardless if you are going to emulate shader or even structure your code similarly to shaders. SSE is not going to help here much. However, I do recognise the room for improvement and am aware of naivity of current math implementation - hence the `swizzle::glsl::naive` namespace.
* GLM is mature
Other, "ideological" differences:
* GLM is code and macro heavy (for what it provides), while CxxSwizzle is compact, clean and mostly template based
<file_sep>/sample/CMakeLists.txt
# CxxSwizzle
# Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
find_package(SDL REQUIRED)
find_package(SDL_image)
find_package(OpenMP)
# this will look in the local cmake directory only if Vc hasn't been built/installed locally
if(MSVC)
# hint to use supplied, patched build
find_package(Vc CONFIG PATHS "${CMAKE_SOURCE_DIR}/external/cmake")
else()
# regular search
find_package(Vc)
endif()
if(SDL_FOUND)
if (OPENMP_FOUND)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS} -DOMP_ENABLED=1")
else()
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS} -DOMP_ENABLED=0")
endif()
# get all the shaders
file(GLOB shaders RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/*.frag")
source_group("" FILES main.cpp use_scalar.h use_simd.h use_simd_masked.h )
source_group("shaders" FILES ${shaders})
add_executable (sample_scalar main.cpp use_scalar.h ${shaders})
include_directories(${SDL_INCLUDE_DIR} ${CxxSwizzle_SOURCE_DIR}/include)
target_link_libraries (sample_scalar ${SDL_LIBRARY})
if(SDLIMAGE_FOUND)
include_directories(${SDL_IMAGE_INCLUDE_DIR})
target_link_libraries (sample_scalar ${SDL_IMAGE_LIBRARY})
set_target_properties(sample_scalar PROPERTIES COMPILE_FLAGS "-DUSE_SCALAR -DSDLIMAGE_FOUND")
else()
set_target_properties(sample_scalar PROPERTIES COMPILE_FLAGS "-DUSE_SCALAR")
message(WARNING "SDL_image not found, loading textures not going to be available.")
endif()
if(Vc_FOUND)
add_executable(sample_simd main.cpp use_simd.h ${shaders})
target_link_libraries(sample_simd ${SDL_LIBRARY} ${Vc_LIBRARIES})
if(SDLIMAGE_FOUND)
target_link_libraries(sample_simd ${SDL_IMAGE_LIBRARY})
set_target_properties(sample_simd PROPERTIES COMPILE_FLAGS "${Vc_DEFINITIONS} -DUSE_SIMD -DSDLIMAGE_FOUND")
else()
set_target_properties(sample_simd PROPERTIES COMPILE_FLAGS "${Vc_DEFINITIONS} -DUSE_SIMD")
endif()
target_include_directories(sample_simd PRIVATE ${Vc_INCLUDE_DIR})
else()
message(WARNING "Vc not found, SIMD sample not going to be available.")
endif()
endif()<file_sep>/include/swizzle/detail/common_binary_operators.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
#include "static_functors.h"
namespace swizzle
{
namespace detail
{
//! Inspired by boost/operators, this class defines arithmetic operators for a vector
//! and a scalar as friend inline functions (only accessible with ADL). The reason for that,
//! contrary to having global template operators is there's less typing and types decaying
//! to a vector/scalar (proxies!) can use these operators too.
//! Note that because VC++ is unable to align SIMD types when passing by value,
//! functions defined here use C++03 pass-by-reference style.
template <typename VectorType, typename ScalarType, typename VectorArgType = const VectorType&, typename ScalarArgType = const ScalarType&>
struct common_binary_operators
{
typedef VectorArgType vector_arg_type;
typedef ScalarArgType scalar_arg_type;
friend VectorType operator+(vector_arg_type v, scalar_arg_type s)
{
VectorType result(v);
return result += s;
}
friend VectorType operator+(scalar_arg_type s, vector_arg_type v)
{
return v + s;
}
friend VectorType operator+(vector_arg_type v1, vector_arg_type v2)
{
VectorType result(v1);
return result += v2;
}
friend VectorType operator*(vector_arg_type v, scalar_arg_type s)
{
VectorType result(v);
return result *= s;
}
friend VectorType operator*(scalar_arg_type s, vector_arg_type v)
{
return v * s;
}
friend VectorType operator*(vector_arg_type v1, vector_arg_type v2)
{
VectorType result(v1);
return result *= v2;
}
friend VectorType operator-(vector_arg_type v, scalar_arg_type s)
{
VectorType result(v);
return result -= s;
}
friend VectorType operator-(scalar_arg_type s, vector_arg_type v)
{
VectorType result(s);
return result -= v;
}
friend VectorType operator-(vector_arg_type v1, vector_arg_type v2)
{
VectorType result(v1);
return result -= v2;
}
friend VectorType operator/(vector_arg_type v, scalar_arg_type s)
{
VectorType result(v);
return result /= s;
}
friend VectorType operator/(scalar_arg_type s, vector_arg_type v)
{
VectorType result(s);
return result /= v;
}
inline friend VectorType operator/(vector_arg_type v1, vector_arg_type v2)
{
VectorType result(v1);
return result /= v2;
}
};
}
}<file_sep>/include/swizzle/glsl/simd_support_vc.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
// VC needs to come first or else it's going to complain (damn I hate these)
#include <Vc/vector.h>
#include <type_traits>
#include <swizzle/detail/primitive_wrapper.h>
#include <swizzle/glsl/vector_helper.h>
namespace swizzle
{
namespace glsl
{
#ifdef VC_UNCONDITIONAL_AVX2_INTRINSICS
typedef ::Vc::float_v::VectorType::Base raw_simd_type;
#else
typedef ::Vc::float_v::VectorType raw_simd_type;
#endif
//! ::Vc::float_v has a tiny bit different semantics than what we need,
//! so let's wrap it.
template<typename BoolType = ::Vc::float_m, typename AssignPolicy = detail::nothing>
using vc_float = detail::primitive_wrapper < ::Vc::float_v, ::Vc::float_v::EntryType, BoolType, AssignPolicy >;
//! Specialise vector_helper so that it knows what to do.
template <typename BoolType, typename AssignPolicy, size_t Size>
struct vector_helper<vc_float<BoolType, AssignPolicy>, Size>
{
//! Array needs to be like a steak - the rawest possible
//! (Wow - I managed to WTF myself upon reading the above after a week or two)
typedef std::array<raw_simd_type, Size> data_type;
template <size_t... indices>
struct proxy_generator
{
typedef detail::indexed_proxy< vector<vc_float<BoolType, AssignPolicy>, sizeof...(indices)>, data_type, indices...> type;
};
//! A factory of 1-component proxies.
template <size_t x>
struct proxy_generator<x>
{
typedef vc_float<BoolType, AssignPolicy> type;
};
typedef detail::vector_base< Size, proxy_generator, data_type > base_type;
};
}
namespace detail
{
//! CxxSwizzle needs to know which vector to create if it needs to
template <typename BoolType, typename AssignPolicy>
struct get_vector_type_impl< ::swizzle::glsl::vc_float<BoolType, AssignPolicy> >
{
typedef ::swizzle::glsl::vector<::swizzle::glsl::vc_float<BoolType, AssignPolicy>, 1> type;
};
}
}
// Vc generally supports it all, but it lacks some crucial functions.
namespace Vc
{
#ifdef VC_IMPL_Scalar
namespace Scalar
#elif defined(VC_IMPL_AVX)
namespace AVX
#elif defined(VC_IMPL_SSE)
namespace SSE
#endif
{
template <typename T>
inline Vector<T> step(const Vector<T>& edge, const Vector<T>& x)
{
auto result = Vector<T>::One();
result.setZero(x <= edge);
return result;
}
template <typename T>
inline Vector<T> pow(const Vector<T>& x, const Vector<T>& n)
{
//! Vc doesn't come with pow function, so we're gonna go
//! with the poor man's version of it.
return exp(n * log(x));
}
template <typename T>
inline Vector<T> fract(const Vector<T>& x)
{
return x - floor(x);
}
}
}<file_sep>/external/cmake/Vc/VcConfig.cmake
set(Vc_VERSION_MAJOR 0)
set(Vc_VERSION_MINOR 7)
set(Vc_VERSION_PATCH 4)
set(Vc_VERSION 0.7.4)
set(Vc_VERSION_STRING "0.7.4")
set(Vc_INSTALL_DIR "${CMAKE_SOURCE_DIR}/external")
set(Vc_LIB_DIR "${Vc_INSTALL_DIR}/lib")
set(Vc_CMAKE_MODULES_DIR "${Vc_INSTALL_DIR}/cmake/Vc")
find_path(Vc_INCLUDE_DIR Vc/Vc PATHS "${Vc_INSTALL_DIR}" NO_DEFAULT_PATH PATH_SUFFIXES include)
find_library(Vc_RELASE_LIBRARIES Vc PATHS "${Vc_INSTALL_DIR}" NO_DEFAULT_PATH PATH_SUFFIXES lib)
find_library(Vc_DEBUG_LIBRARIES Vc-d PATHS "${Vc_INSTALL_DIR}" NO_DEFAULT_PATH PATH_SUFFIXES lib)
set(Vc_LIBRARIES optimized ${Vc_RELASE_LIBRARIES} debug ${Vc_DEBUG_LIBRARIES})
include("${Vc_CMAKE_MODULES_DIR}/VcMacros.cmake")
set(Vc_DEFINITIONS)
vc_set_preferred_compiler_flags()
<file_sep>/unit_test/CMakeLists.txt
# CxxSwizzle
# Copyright (c) 2013, <NAME> <gwiazdorrr+github at gmail.com>
find_package(Boost)
if(Boost_FOUND)
file(GLOB headers RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.h")
file(GLOB source RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
source_group("" FILES ${source} ${headers})
include_directories(${Boost_INCLUDE_DIR} ${CxxSwizzle_SOURCE_DIR}/include)
add_executable (unit_test ${source} ${headers})
endif(Boost_FOUND)<file_sep>/sample/use_simd.h
// CxxSwizzle
// Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
#pragma once
// VC need to come first or else VC is going to complain.
#include <Vc/vector.h>
#include <swizzle/glsl/simd_support_vc.h>
// need to include scalars as well because we don't need literals
// to use simd (like sin(1))
#include <swizzle/glsl/scalar_support.h>
typedef swizzle::glsl::vc_float<> float_type;
typedef float_type::internal_type raw_float_type;
typedef Vc::uint_v uint_type;
//! By default Vc's masks (result of comparisons) decay to bools but
//! are not implicitly constructible; hence defining bool_type as bool
//! is the safest bet here.
typedef bool bool_type;
static_assert(static_cast<size_t>(raw_float_type::Size) == static_cast<size_t>(uint_type::Size), "Both float and uint types need to have same number of entries");
const size_t scalar_count = raw_float_type::Size;
const size_t float_entries_align = Vc::VectorAlignment;
const size_t uint_entries_align = Vc::VectorAlignment;
template <typename T>
inline void store_aligned(const Vc::Vector<T>& value, T* target)
{
value.store(target, Vc::Aligned);
}
template <typename T>
inline void load_aligned(Vc::Vector<T>& value, const T* data)
{
value.load(data, Vc::Aligned);
}
<file_sep>/CMakeLists.txt
# CxxSwizzle
# Copyright (c) 2013-2015, <NAME> <gwiazdorrr+github at gmail.com>
cmake_minimum_required (VERSION 2.6)
project (CxxSwizzle)
set_property(GLOBAL PROPERTY USE_FOLDERS On)
add_subdirectory(sample)
add_subdirectory(unit_test)
# get all the shaders
file(GLOB detail RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/swizzle/detail/*.h")
file(GLOB glsl RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/swizzle/glsl/*.h")
file(GLOB glsl_detail RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/swizzle/detail/glsl/*.h")
source_group("swizzle\\detail" FILES ${detail})
source_group("swizzle\\glsl" FILES ${glsl})
source_group("swizzle\\detail\\glsl" FILES ${glsl_detail})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${Vc_INCLUDE_DIR})
add_library(headers STATIC ${detail} ${glsl} ${glsl_detail} README.md)
set_target_properties(headers PROPERTIES LINKER_LANGUAGE CXX)
|
506440175789eabb0411e5da7e2c26bf626cfec6
|
[
"Markdown",
"CMake",
"C++"
] | 18
|
C++
|
syoyo/CxxSwizzle
|
e70de1c1eda7e9ab497c9b3929edc9642e725dc0
|
91c3094b2652b5a71eeebe8fb0912468bc65475e
|
refs/heads/master
|
<repo_name>ETHZ-TEC/exot_app_lib<file_sep>/include/exot/meters/utilisation_procfs.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/utilisation_procfs.h
* @author <NAME>
* @brief Metering module for obtaining utilisation values from /proc/stat.
*/
#pragma once
#if defined(__linux__)
#include <unistd.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <fstream>
#include <iterator>
#include <regex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/ostream.h>
namespace exot::modules {
/**
* @brief Module for reading utilisation values from procfs
*/
struct utilisation_procfs : module {
using return_type = std::vector<double>; /*! return type of `measure()` */
using reading_type = std::vector<int>; /*! internal raw reading type */
/**
* @brief Enumeration for types of CPU states to access
*/
enum class cpu_state { user, nice, system, idle };
/**
* @brief Structure holding the module settings.
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<unsigned> cores;
bool raw{false};
std::vector<cpu_state> states;
const char* name() const { return "utilisation_procfs"; }
void configure() {
bind_and_describe_data("cores", cores,
"cores to read utilisation of |uint[]|");
bind_and_describe_data(
"raw", raw,
"provide raw values? |bool|, if false, provide percentage values");
bind_and_describe_data(
"states", states,
"list of states to read |cpu_state[]|, choose from "
"[\"user\", \"nice\", \"system\", \"idle\"]");
}
};
/**
* @brief Constructs the object
*
* @param conf The settings object
*/
explicit utilisation_procfs(settings& conf);
/**
* @brief Performs a single raw access
*
* @param readings The vector holding raw readings
*/
void once(reading_type& readings);
/**
* @brief The main measurement function
*
* @return A vector containing raw or processed readings
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
settings conf_;
reading_type previous_readings_;
reading_type current_readings_;
return_type output_;
std::array<bool, 4> enable_flags_; /*! Array of booleans for enabling access
to certain CPU states. */
long ticks_per_second_; /*! Values reported in procfs are in units described
as ticks per second in sysconf */
const std::string filepath_{"/proc/stat"};
std::chrono::steady_clock::time_point previous_time_;
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
/**
* @brief Overload for cpu_state enumeration.
*
* @param[in] j The json object
* @param d The enum object to write data to
*/
inline void from_json(const nlohmann::json& j,
utilisation_procfs::cpu_state& d) {
if (!j.is_string()) {
throw nlohmann::json::type_error::create(
302, fmt::format("type must be a string, but was a {}", j.type_name()));
} else {
auto value = j.get<nlohmann::json::string_t>();
if (value == "user") {
d = utilisation_procfs::cpu_state::user;
} else if (value == "nice") {
d = utilisation_procfs::cpu_state::nice;
} else if (value == "system") {
d = utilisation_procfs::cpu_state::system;
} else if (value == "idle") {
d = utilisation_procfs::cpu_state::idle;
} else {
throw nlohmann::json::other_error::create(
501, fmt::format("provided cpu state value \"{}\" is not "
"featured in the enum class",
value));
}
}
}
/**
* @brief Overload for serialising cpu_state enumeration.
*
* @param[in] j The json object
* @param d The enum object to serialise
*/
inline void to_json(nlohmann::json& j, const utilisation_procfs::cpu_state& d) {
switch (d) {
case utilisation_procfs::cpu_state::user:
j = "user";
break;
case utilisation_procfs::cpu_state::nice:
j = "nice";
break;
case utilisation_procfs::cpu_state::system:
j = "system";
break;
case utilisation_procfs::cpu_state::idle:
j = "idle";
break;
}
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/utilities/debug.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/debug.h
* @author <NAME>
* @brief Debugging helpers, in global namespace
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <typeinfo>
#include <fmt/format.h>
#ifdef __GNUG__
#include <cxxabi.h>
#endif // __GNUG__
#include <exot/utilities/cache.h>
#include <exot/utilities/pagemap.h>
inline namespace debug {
/**
* @brief Produces a human-readable type description
* @details Demangling in this way works only with the GNU compiler. For
* other compilers one can always use the c++filt application.
*
* @param[in] mangled_name The mangled type name
*
* @return Demangled type name
*/
inline const char* demangle(const char* mangled_name) {
#ifdef __GNUG__
std::size_t len = 0;
int status = 0;
std::unique_ptr<char, decltype(&std::free)> ptr(
__cxxabiv1::__cxa_demangle(mangled_name, nullptr, &len, &status),
&std::free);
return ptr.get();
#else
return mangled_name;
#endif
}
template <typename T>
static inline const char* typeid_name = typeid(T).name();
template <typename T>
static inline const char* demangled_typeid_name = demangle(typeid(T).name());
/**
* @brief Print memory contents, virtual, and physical addresses
*
* @param[in] header The header to print
* @param[in] base The base pointer as a value
* @param[in] cnt The count of addresses to print
* @param[in] jmp The jump value by which the addresses are incremented
*/
static inline void print_memory(const char* header, std::uintptr_t base,
std::size_t cnt = 1, std::size_t jmp = 1) {
try {
auto translator = exot::utilities::AddressTranslator();
auto decomposer = exot::utilities::AddressDecomposer();
fmt::print(stderr, "\n-- {}\n\n", header);
fmt::print(stderr,
" idx | virt >> phys |~ contents ~|"
"\ttag\tset\toff\n");
fmt::print(stderr,
"-------|--------------------------------------|------------|"
"-------------------------------\n");
for (auto i = size_t{0}; i < cnt * jmp; i += jmp) {
auto* ptr = reinterpret_cast<void*>(base + i);
auto* buf = reinterpret_cast<const unsigned*>(ptr);
auto phys = translator(ptr);
auto [tag, set, off] = decomposer(phys);
fmt::print(stderr,
"{:0>6x} | {:>16} >> {:#16x} |~ {:>{}x} ~|\t" // 1
"{:#x}\t{:#x}\t{:#x}\n", // 2
i, ptr, phys, buf[0], 2 * sizeof(buf[0]), // -> 1
tag, set, off); // -> 2
}
} catch (const std::exception& e) {
fmt::print(stderr, "-- failed: {}", e.what());
}
}
} // namespace debug
<file_sep>/include/exot/meters/frequency_rel.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/frequency_rel.h
* @author <NAME>
* @brief Empirical frequency meter module.
*/
#pragma once
#include <atomic>
#include <chrono>
#include <memory> // for std::shared_ptr
#include <string> // for std::string
#include <thread> // for threads
#include <vector> // for variable-size arrays
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/barrier.h>
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/helpers.h>
namespace exot::modules {
namespace details {
/**
* @brief The probing function
*
* @tparam T An arithmetic type (e.g. unsigned, double)
* @tparam Iter Interaction count
* @tparam <unnamed> Template helper
*
* @return The probe duration in nanoseconds
*/
template <typename T, size_t Iter,
typename = std::enable_if_t<std::is_arithmetic_v<T>>>
inline std::chrono::nanoseconds probe() {
volatile T a = static_cast<T>(1), b = static_cast<T>(2);
auto start = std::chrono::steady_clock::now();
for (decltype(Iter) i{0}; i < Iter; ++i) {
a += b;
b *= a;
}
exot::utilities::do_not_optimise(a, b);
return (std::chrono::steady_clock::now() - start);
}
} // namespace details
/**
* @brief The empirical frequency meter
*/
struct frequency_rel : module {
using return_type = std::vector<double>;
using duration_type = std::chrono::duration<double, std::nano>;
using barrier_type = exot::utilities::Barrier;
using probe_type = int;
static const unsigned probe_iterations{1024u};
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<unsigned> cores; //! vector of cores
const char* name() const { return "frequency_rel"; }
/* @brief The JSON configuration function */
void configure() {
bind_and_describe_data(
"cores", cores,
"cores to measure relative frequency on |uint[]|, e.g. [0, 2]");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings structure
*/
explicit frequency_rel(settings&);
~frequency_rel();
/**
* @brief Perform measurement
*
* @return A vector with frequency readings
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
/**
* @brief Get the reference probe duration
*
* @param[in] repetitions The number of repeated measurements used to
* provide the average probe duration
*
* @return The average probe duration
*/
static inline duration_type reference_probe_duration(unsigned repetitions);
private:
settings conf_;
return_type readings_;
std::vector<duration_type> references_;
std::vector<std::thread> threads_;
barrier_type barrier_;
std::atomic<bool> flag_{false};
std::atomic_flag worker_flag_ = ATOMIC_FLAG_INIT;
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
} // namespace exot::modules
<file_sep>/include/exot/utilities/pagemap.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/pagemap.h
* @author <NAME>
* @brief Wrapper for Linux virtual-to-physical address resolution via
* proc/<pid>/pagemap.
*/
#pragma once
#if defined(__linux__)
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <thread>
#include <type_traits>
#include <fmt/format.h>
#include <exot/utilities/bits.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* @brief Gets the page size.
*
* @return The page size.
*/
static inline long get_page_size() {
static auto page_size = ::sysconf(_SC_PAGE_SIZE);
return page_size;
}
/**
* @brief Linux pagemap data
* @note In a page is swapped, the page_frame_number field will contain
* a value that has bits 0-4: swap type, 5-54: swap offset.
* @see Linux documentation at admin-guide/mm/pagemap.rst.
*/
struct PagemapValue {
std::uint64_t page_frame_number : 54; // 0-54
std::uint64_t page_table_entry_soft_dirty : 1; // 55
std::uint64_t page_mapped_exclusively : 1; // 56
std::uint64_t : 4; // 57-60
std::uint64_t page_is_file_or_anon : 1; // 61
std::uint64_t page_swapped : 1; // 62
std::uint64_t page_present : 1; // 63
};
/**
* @brief Utility functor that translates virtual addresses to physical
*/
struct AddressTranslator {
/**
* Constructs the functor with the calling process'es pagemap
*/
AddressTranslator() : AddressTranslator(std::string{"self"}) {}
/**
* @brief Constructs the functor for a specific PID
*
* @param[in] pid The pid
*/
explicit AddressTranslator(pid_t pid)
: AddressTranslator(std::to_string(static_cast<std::uintmax_t>(pid))) {}
/**
* @brief Destroys the object.
*/
~AddressTranslator() { ::close(fd_); }
/**
* @brief Translates a virtual address to a physical address
*
* @note In modern Linux kernel versions, the pagemap can be accessed
* only by users with admin capabilities. If the pagemap is read
* with insufficient capabilities the returned page frame number
* will be 0, and the addresses will no longer be meaningful.
*
* @param[in] virtual_address The virtual address to convert
*
* @tparam T the address type (either, void*, a pointer
* type or an integer that can hold a pointer).
* @tparam <unnamed> Template helper
*
* @return The corresponding physical address
*/
template <typename T,
typename = std::enable_if_t<
(std::is_same<T, void*>::value || std::is_pointer<T>::value ||
exot::utilities::is_convertible_d<T, std::uintptr_t>::value)>>
auto operator()(T virtual_address) -> std::uintptr_t {
std::uintptr_t virtual_address_;
if constexpr (std::is_same<T, void*>::value || std::is_pointer<T>::value) {
virtual_address_ = reinterpret_cast<std::uintptr_t>(virtual_address);
} else {
virtual_address_ = static_cast<std::uintptr_t>(virtual_address);
}
/**
* @note Workaround for soft-dirty bit being set upon first iteration.
* It seems that accessing the memory first solves the issue.
* @todo Is there a more 'proper' way to accomplish the task?
*/
volatile auto _ = *reinterpret_cast<std::uintptr_t*>(virtual_address);
auto pv = get_pagemap_value(virtual_address_);
if (!pv.has_value()) {
throw std::logic_error(
"virtual address cannot be translated to physical");
}
auto page_frame_number = pv.value().page_frame_number;
/* TODO: check if page frame returns 0, meaning that the process did not
* have the capabilities to access the pagemap. */
return page_frame_number * page_size_ + (virtual_address_ % page_size_);
}
/**
* @brief Gets the pagemap value for a given address.
*
* @param[in] virtual_address The virtual address
*
* @return The pagemap value, or nullopt if unsuccessful.
*/
auto get_pagemap_value(uintptr_t virtual_address)
-> std::optional<PagemapValue> {
using namespace exot::utilities;
std::uint64_t value = 0ull;
unsigned n = 0u;
/* Read sizeof(value) bytes from the pagemap, e.g. 8 on 64-bit CPUs. */
while (n < sizeof(value)) {
auto _ = ::pread(fd_, reinterpret_cast<void*>(&value), sizeof(value),
static_cast<off_t>(
(virtual_address / page_size_) * sizeof(value) + n));
if (_ <= 0)
return {};
else
n += _;
}
PagemapValue pv;
/* Fill the PagemapValue structure with extracted bits/bit ranges. */
pv.page_frame_number = extract_bit_range(value, 0ull, 54ull);
pv.page_table_entry_soft_dirty = get_bit(value, 55ull);
pv.page_mapped_exclusively = get_bit(value, 56ull);
pv.page_is_file_or_anon = get_bit(value, 61ull);
pv.page_swapped = get_bit(value, 62ull);
pv.page_present = get_bit(value, 63ull);
return std::move(pv);
}
private:
int fd_{-1}; //! the file descriptor to the pagemap
std::string interface_; //! the path to the pagemap
long page_size_{::sysconf(_SC_PAGE_SIZE)}; //! the system's page size
/**
* @brief Non-public constructor using a string path
*
* @param[in] proc_path The path to the proc path with the pagemap
*/
AddressTranslator(const std::string& proc_path) {
interface_ = fmt::format("/proc/{}/pagemap", proc_path);
if (fd_ = ::open(interface_.c_str(), O_RDONLY); fd_ == -1) {
throw std::logic_error(
fmt::format("{} not accessible, reason: {}", interface_,
errno != 0 ? std::strerror(errno) : "unknown"));
}
// TODO: writing to clear_refs doesn't seem to take care of soft-dirty bits
// auto cr_ = fmt::format("/proc/{}/clear_refs", proc_path);
// if (auto clear_refs_ = std::ofstream(cr_, std::ios::out);
// !clear_refs_.is_open()) {
// throw std::logic_error(fmt::format("{} not accessible", cr_));
// } else {
// clear_refs_ << 4;
// clear_refs_.close();
// }
}
};
} // namespace exot::utilities
#else
#error "The pagemap utility can only be used on Linux"
#endif
<file_sep>/include/exot/meters/thermal_sysfs.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/thermal_sysfs.h
* @author <NAME>
* @brief Thermal metering module utilising values reported in sysfs.
*/
#pragma once
#if defined(__linux__)
#include <algorithm> // for std::transform
#include <fstream> // for ifstream
#include <string> // for std::string
#include <thread> // for hardware_concurrency
#include <vector> // for variable-size arrays
#include <fmt/format.h> // for formatting strings
#include <fmt/ostream.h> // for ostream support
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/filesystem.h> // for filesystem operations
#include <exot/utilities/ostream.h> // for ostream operator overloads
namespace exot::modules {
/**
* @brief Measurement module for reading thermal information from sysfs
*/
struct thermal_sysfs : module {
using return_type = std::vector<float>;
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<unsigned> zones;
const char* name() const { return "thermal_sysfs"; }
void configure() {
bind_and_describe_data("zones", zones,
"list of zones to read |uint[]|, e.g. [0, 1]");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings
*/
explicit thermal_sysfs(settings& conf);
/**
* @brief Perform module measurement
*
* @return A vector with thermal zone temperature readings
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_;
std::vector<std::string> filenames_;
return_type readings_;
};
} // namespace exot::modules
#endif
<file_sep>/include/exot/utilities/filesystem.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/filesystem.h
* @author <NAME>
* @brief Functions for listing/grepping directories, and other
* filesystem-related activities.
*/
#pragma once
/**
* Since std::filesystem is not yet mature enough to be included in some STL
* implementations, notably on Android, we have to rely on more standard Unix
* methods. The <dirent.h> should be available on most *nix platforms.
*
* Globbing via <glob.h> is not available on Android platforms before API level
* 28, hence <regex>-based alternatives are provided.
*
* __has_include macro is part of the C++17 standard. In the case when a
* platform does not provide the header file, and the contained functions are
* called, the linker will most likely complain about the lack of defined
* symbols.
*/
#if __has_include(<dirent.h>)
#include <dirent.h>
#endif
#if __has_include(<ftw.h>)
#include <ftw.h>
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm> // for remove_if
#include <cerrno> // for errno
#include <cstring> // for strerror
#include <fstream> // for file access
#include <memory> // for unique_ptr
#include <optional> // for optional
#include <regex> // for regular expressions
#include <string> // for strings
#include <type_traits> // for type traits
#include <vector> // for variable-size arrays
#include <fmt/format.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
using stat_t = struct stat; //! alias for struct stat
/* list_directory and grep_directory require dirent.h */
#if __has_include(<dirent.h>)
/**
* @brief Lists the contents of a directory
* @details The current and parent directories ('.', and '..') are also
* present in the output.
*
* Throws an error if the directory does not exist or is otherwise
* unreadable.
*
* @param[in] directory The directory
*
* @return A vector of strings containing the paths of files and directories
* present in the listed directory.
*/
std::vector<std::string> list_directory(const std::string& directory);
/**
* @brief Lists a directory and return paths that match a regular
* expression.
*
* @param[in] directory The directory
* @param[in] regex The regular expression
*
* @return A vector of strings containing the paths of files and directories
* present in the listed directory that match the regular
* expression.
*/
std::vector<std::string> grep_directory(const std::string& directory,
const std::string& regex);
#endif
/**
* @brief Enum to indicate whether symlinks are to be followed or ignored.
*/
enum class Symlinks { Follow, Ignore };
/* Recursive listing and grepping requires ftw.h */
#if __has_include(<ftw.h>)
/**
* @brief Lists the contents of a directory recursively
*
* @param[in] directory The directory
* @param[in] symlinks Option to follow/ignore symlinked directories
*
* @return A vector of strings containing the paths of files and directories
* present in the listed directory and its subdirectories.
*/
std::vector<std::string> list_directory_r(const std::string& directory,
Symlinks symlinks = Symlinks::Ignore);
/**
* @brief Lists a directory recursively and returns paths that match a
* regular expression
*
* @param[in] directory The directory
* @param[in] regex The regular expression
* @param[in] symlinks Option to follow/ignore symlinked directories
*
* @return A vector of strings containing the paths of files and directories
* present in the listed directory that match the regular
* expression.
*/
std::vector<std::string> grep_directory_r(const std::string& directory,
const std::string& regex,
Symlinks symlinks = Symlinks::Ignore);
#endif
/**
* @brief Checks if a provided file can be read
*
* @param[in] path The path
*
* @return True if readable, False otherwise.
*/
bool is_readable(const std::string& path);
/**
* @brief Checks if a provided path exists
*
* @param[in] path The path
*
* @return True if exists, False otherwise.
*/
bool exists(const std::string& path);
/**
* @brief Determines if a path is a directory
*
* @param[in] path The path
*
* @return True if directory, False otherwise.
*/
bool is_directory(const std::string& path);
/**
* @brief Gets the sys/stat.h 'stat' struct for a path
*
* @param[in] path The path
*
* @return The stat if successful, nullopt otherwise.
*/
auto get_stat(const std::string& path) -> std::optional<stat_t>;
/**
* @brief Checks if all provided files can be accessed
*
* @param[in] paths A vector of path names
*
* @return True if all are readable
*/
bool all_readable(const std::vector<std::string>& paths);
/**
* @brief Determines if a file is empty.
*
* @param[in] file_path The file path
*
* @return True if empty, False otherwise.
*/
bool is_empty(const std::string& file_path);
/**
* @brief Removes unreadable files from a vector of paths
*
* @param paths The vector of path names
*
* @return A vector of paths that have been removed, can be empty.
*/
std::vector<std::string> remove_unreadable(std::vector<std::string>& paths);
/**
* @brief Get a value of certain type from file.
*
* The function template relies on input stream overloads being present for
* the type defined in template parameters.
*
* @param[in] path The path
*
* @tparam To The desired type
*
* @return The value from file if readable, nullopt otherwise.
*/
template <typename To>
inline auto get_value_from_file(const std::string& path) -> std::optional<To> {
try {
if (is_readable(path)) {
To output;
std::ifstream file{path};
file >> output;
return output;
} else {
return {};
}
} catch (...) { return {}; }
}
/**
* @brief Gets the long string value from file.
*
* @param[in] path The path as a const string reference
*
* @return The long string value from file if readable, nullopt otherwise.
*/
auto get_long_string_value_from_file(const std::string& path) noexcept
-> std::optional<std::string>;
/**
* @brief Gets a string value from a file
*
* @param[in] path The path as a const string reference
*
* @return The string value from file if readable, nullopt otherwise.
*/
auto get_string_value_from_file(const std::string& path) noexcept
-> std::optional<std::string>;
/**
* @brief File reader with raw data access
*/
struct file_reader {
explicit file_reader(std::string&& path) : path_{path} {
if (fd_ = ::open(path_.c_str(), O_RDONLY); fd_ == -1) {
throw std::logic_error(
fmt::format("{} not accessible, reason: {}", path_,
errno != 0 ? std::strerror(errno) : "unknown"));
}
if (!is_readable(path_)) {
throw std::logic_error(fmt::format("{} not accessible", path_));
}
}
file_reader& operator=(file_reader&& other) {
fd_ = std::move(other.fd_);
return *this;
}
~file_reader() { ::close(fd_); }
/**
* @brief Read from file into a data type T
*
* @tparam T The return data type
* @tparam <unnamed> Template helper
*
* @return The read value if successful, nullopt otherwise.
*/
template <typename T, typename = std::enable_if_t<
std::is_default_constructible<T>::value>>
auto read_raw() -> std::optional<T> {
auto value = T{};
auto bytes_read = 0u;
while (bytes_read < sizeof(value)) {
auto _ = ::pread(fd_, reinterpret_cast<void*>(&value), sizeof(value),
static_cast<off_t>(bytes_read));
if (_ <= 0)
return {};
else
bytes_read += _;
}
return value;
}
template <typename T, typename = std::enable_if_t<
(std::is_default_constructible<T>::value &&
is_readable_from_stream<T>::value)>>
auto read_stream() -> std::optional<T> {
auto value = T{};
try {
auto file = std::ifstream{path_};
file >> value;
return value;
} catch (...) { return {}; }
}
private:
int fd_;
std::string path_;
};
} // namespace exot::utilities
<file_sep>/include/exot/utilities/bits.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/bits.h
* @author <NAME>
* @brief Type-safe bit manipulation functions.
*/
#pragma once
#include <cerrno> // for setting errno and macros
#include <limits> // for numeric_limits
#include <type_traits> // for enable_if, is_integral_v, is_same_v
#include <fmt/format.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* Some of the bit manipulation functions use the compiler's builtins, which
* should be available for both GCC and LLVM compilers.
*/
/**
* @brief Makes a bitmask
* @details The function sets bits from lower_bit to upper_bit, e.g. a call
* `make_bitmask(2L, 5ULL)` will produce a number `0b11100`. Thanks
* to templating, the function should work for many types without
* implicit casting, and provides overflow checks for the shift
* operations.
*
* @param[in] lower_bit The lower set bit of the bitmask
* @param[in] upper_bit The upper set bit of the bitmask
*
* @tparam T1 Type of lower_bit
* @tparam T2 Type of upper_bit
* @tparam <unnamed> Template helper to enable the function only for
* integral types
*
* @return A bitmask with bits set from lower_bit to upper_bit
*/
template <typename T1, typename T2,
typename = std::enable_if_t<are_unsigned_integral<T1, T2>>>
inline constexpr larger_of_t<T1, T2> make_bitmask(T1 lower_bit, T2 upper_bit) {
if (lower_bit > upper_bit) {
throw std::logic_error("lower bitmask bit > upper bitmask bit");
}
if ((lower_bit > std::numeric_limits<T1>::digits) ||
(upper_bit > std::numeric_limits<T2>::digits))
throw std::overflow_error(fmt::format(
"\n\tResulf of shift operation will have undefined value due to"
"\n\tshifting by value greater or equal to the width of the "
"type.\n\t{}\n",
__PRETTY_FUNCTION__));
/* Performing a shift (2 << by) is the same as doing (1 << (by + 1)). */
auto upper_mask = (T2{2} << upper_bit) - 1;
auto lower_mask = (T1{1} << lower_bit) - 1;
/* Merge lower and upper masks via xor operation. */
return upper_mask ^ lower_mask;
}
/**
* @brief Extracts a value by applying a bitmask
* @details The function applies the bitmask, and shifts the value by the
* number of trailing zeros in the bitmask. For example, by calling
* `extract_with_bitmask(0b11011001, 0b111100)`, we obtain the
* result `0b1011`, i.e. `0b11011001 & 0b00111100`, which is
* `0b00101100`, then shifted by 2, to produce `0b1011`.
*
* @param[in] value The value
* @param[in] bitmask The bitmask
*
* @tparam T1 The type of the value
* @tparam T2 The type of the bitmask
* @tparam <unnamed> Template helper to enable the function only for
* integral types
*
* @return The extracted value, i.e. the shifted bitmasked original value
*/
template <typename T1, typename T2,
typename = std::enable_if_t<are_unsigned_integral<T1, T2>>>
inline constexpr T1 extract_with_bitmask(T1 value, T2 bitmask) {
/* Apply a bitmask and shift by the amount of the trailing zeros in the
* bitmask. */
if constexpr (are_same_size<T2, int>) {
return (value & bitmask) >> __builtin_ctz(bitmask);
} else if constexpr (are_same_size<T2, long> &&
!are_same_size<T2, long long>) {
return (value & bitmask) >> __builtin_ctzl(bitmask);
} else if constexpr (are_same_size<T2, long long>) {
return (value & bitmask) >> __builtin_ctzll(bitmask);
}
}
template <typename T1, typename T2, typename T3,
typename = std::enable_if_t<are_unsigned_integral<T1, T2, T3>>>
inline constexpr T1 extract_bit_range(T1 value, T2 lower_bit, T3 upper_bit) {
return (value & make_bitmask(lower_bit, upper_bit)) >> lower_bit;
}
template <typename T, typename B,
typename = std::enable_if_t<are_unsigned_integral<T, B>>>
inline constexpr void set_bit(T& value, B bit) {
value |= (T{1} << bit);
}
template <typename T, typename... Bs,
typename = std::enable_if_t<are_unsigned_integral<T, Bs...>>>
inline constexpr void set_bits(T& value, Bs... bits) {
(set_bit(value, bits), ...);
}
template <typename T1, typename T2, typename T3,
typename = std::enable_if_t<are_unsigned_integral<T1, T2, T3>>>
inline constexpr void set_bit_range(T1& value, T2 lower_bit, T3 upper_bit) {
value |= make_bitmask(lower_bit, upper_bit);
}
template <typename T, typename B,
typename = std::enable_if_t<are_unsigned_integral<T, B>>>
inline constexpr T get_bit(T value, B bit) {
return (value >> bit) & T{1};
}
template <typename T, typename B,
typename = std::enable_if_t<are_unsigned_integral<T, B>>>
inline constexpr void clear_bit(T& value, B bit) {
value &= ~(T{1} << bit);
}
template <typename T, typename... Bs,
typename = std::enable_if_t<are_unsigned_integral<T, Bs...>>>
inline constexpr void clear_bits(T& value, Bs... bits) {
(clear_bit(value, bits), ...);
}
template <typename T1, typename T2, typename T3,
typename = std::enable_if_t<are_unsigned_integral<T1, T2, T3>>>
inline constexpr void clear_bit_range(T1& value, T2 lower_bit, T3 upper_bit) {
value &= ~make_bitmask(lower_bit, upper_bit);
}
template <typename T, typename B,
typename = std::enable_if_t<are_unsigned_integral<T, B>>>
inline constexpr void toggle_bit(T& value, B bit) {
value ^= (T{1} << bit);
}
template <typename T, typename... Bs,
typename = std::enable_if_t<are_unsigned_integral<T, Bs...>>>
inline constexpr void toggle_bits(T& value, Bs... bits) {
(toggle_bit(value, bits), ...);
}
template <typename T1, typename T2, typename T3,
typename = std::enable_if_t<are_unsigned_integral<T1, T2, T3>>>
inline constexpr void toggle_bit_range(T1& value, T2 lower_bit, T3 upper_bit) {
value ^= make_bitmask(lower_bit, upper_bit);
}
template <typename T, typename B,
typename = std::enable_if_t<are_unsigned_integral<T, B>>>
inline bool test_bit(T value, B bit) {
return value & (T{1} << bit);
}
template <typename T, typename... Bs,
typename = std::enable_if_t<are_unsigned_integral<T, Bs...>>>
inline bool test_bits(T value, Bs... bits) {
return (test_bit(value, bits) && ...);
}
template <typename T1, typename T2, typename T3,
typename = std::enable_if_t<are_unsigned_integral<T1, T2, T3>>>
inline constexpr bool test_bit_range(T1 value, T2 lower_bit, T3 upper_bit) {
auto mask = make_bitmask(lower_bit, upper_bit);
auto extracted = extract_with_bitmask(value, mask);
return extracted != decltype(extracted){0};
}
/**
* @brief Return the hamming weight of a number, the count of bits set to 1
*
* @param[in] value The evaluated value
*
* @tparam T The type of the value
* @tparam <unnamed> Template helper
*
* @return The count of individual bits set to 1
*/
template <typename T, typename = std::enable_if_t<are_unsigned_integral<T>>>
inline constexpr int hamming_weight(T value) {
if constexpr (are_same_size<T, int>) {
return __builtin_popcount(value);
} else if constexpr (are_same_size<T, long> &&
!are_same_size<long, long long>) {
return __builtin_popcountl(value);
} else if constexpr (are_same_size<T, long long>) {
return __builtin_popcountll(value);
}
}
/**
* @brief Return the parity of the value (evenness/oddness of an integer)
*
* @param[in] value The evaluated value
*
* @tparam T The type of the value
* @tparam <unnamed> Template helper
*
* @return The parity of the value
*/
template <typename T, typename = std::enable_if_t<are_unsigned_integral<T>>>
inline constexpr int parity(T value) {
if constexpr (are_same_size<T, int>) {
return __builtin_parity(value);
} else if constexpr (are_same_size<T, long> &&
!are_same_size<long, long long>) {
return __builtin_parityl(value);
} else if constexpr (are_same_size<T, long long>) {
return __builtin_parityll(value);
}
}
/**
* @brief Gets the number of trailing zero bits in an unsigned integer
* @note Takes care of the case when 0 is given, for which BSR or BSF
* operations are undefined. In such case the number of digits in
* the type T is returned.
*
* @param[in] value The evaluated value
*
* @tparam T The type of the value
* @tparam <unnamed> Template helper
*
* @return The number of trailing bits in the value
*/
template <typename T, typename = std::enable_if_t<are_unsigned_integral<T>>>
inline constexpr int trailing_zero_bits(T value) {
if constexpr (are_same_size<T, int>) {
return value ? __builtin_ctz(value) : std::numeric_limits<T>::digits;
} else if constexpr (are_same_size<T, long> &&
!are_same_size<long, long long>) {
return value ? __builtin_ctzl(value) : std::numeric_limits<T>::digits;
} else if constexpr (are_same_size<T, long long>) {
return value ? __builtin_ctzll(value) : std::numeric_limits<T>::digits;
}
}
/**
* @brief Gets the number of leading zero bits in an unsigned integer
* @note Takes care of the case when 0 is given, for which BSR or BSF
* operations are undefined. In such case the number of digits in
* the type T is returned.
*
* @param[in] value The evaluated value
*
* @tparam T The type of the value
* @tparam <unnamed> Template helper
*
* @return The number of leading bits in the value
*/
template <typename T, typename = std::enable_if_t<are_unsigned_integral<T>>>
inline constexpr int leading_zero_bits(T value) {
if constexpr (are_same_size<T, int>) {
return value ? __builtin_clz(value) : std::numeric_limits<T>::digits;
} else if constexpr (are_same_size<T, long> &&
!are_same_size<long, long long>) {
return value ? __builtin_clzl(value) : std::numeric_limits<T>::digits;
} else if constexpr (are_same_size<T, long long>) {
return value ? __builtin_clzll(value) : std::numeric_limits<T>::digits;
}
}
/**
* @brief Gets the position of the next set bit in an unsigned integer
* @note If the 'bit' value is greater than the number of digits in the
* type T, the function returns the latter, and sets errno to EDOM.
* @details The function can be use to loop through set bits in a number,
* like so:
*
* ```cpp
* for (auto i = next_set_bit(value, 0);
i < std::numeric_limits<decltype(value)>::digits;
i = next_set_bit(value, i + 1));
* ```
*
* @param[in] value The value
* @param[in] bit The bit from which the testing is performed
*
* @tparam T The type of the value
* @tparam <unnamed> Template helper
*
* @return The bit position of the next set bit
*/
template <typename T, typename = std::enable_if_t<are_unsigned_integral<T>>>
inline constexpr std::size_t next_set_bit(T value, std::size_t bit) {
/* T{1} << bit - 1 clears the lower 'bit' bits, see clear_bit above.
*
* We also need to account for the case when the set bit is greater than the
* number of digits in the type T, because the operation T{1} << bit would be
* incorrect. Here we return the number of digits, and also set the errno
* flag. */
if (bit >= std::numeric_limits<T>::digits) {
errno = EDOM;
return std::numeric_limits<T>::digits;
}
return trailing_zero_bits(value & ~((T{1} << bit) - 1));
}
/**
* @brief Executes a callable with indeces of set bits in a value
*
* @param[in] value The value
* @param[in] callable The callable, must be invocable as void(size_t)
*
* @tparam T The type of the value
* @tparam F The callable type
* @tparam <unnamed> Template helper
*/
template <typename T, typename F,
typename = std::enable_if_t<
(are_unsigned_integral<T> &&
std::is_invocable_r<void, F, std::size_t>::value)>>
inline constexpr void loop_through_set_bits(T value, F&& callable) {
for (auto i = exot::utilities::next_set_bit(value, 0);
i < std::numeric_limits<T>::digits - 1;
i = exot::utilities::next_set_bit(value, i + 1)) {
callable(i);
}
}
} // namespace exot::utilities
<file_sep>/include/exot/components/logger.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/logger.h
* @author <NAME>
* @brief Basic logger node, logs any serialisable data structure to
* standard output and/or file.
*/
#pragma once
#include <chrono> // for durations
#include <string> // for std::string
#include <type_traits> // for enable_if_t, is_convertible_v
#include <exot/framework/all.h>
#include <exot/utilities/ostream.h>
#include <exot/utilities/timing.h>
#include <exot/utilities/types.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace exot::components {
template <typename Token>
class Logger : public exot::framework::Consumer<Token>,
public exot::framework::IProcess {
public:
using node_type = exot::framework::Consumer<Token>;
using node_type::in_; //! needed because the base class is a class template
using clock_type = std::chrono::steady_clock;
using container_pointer =
typename node_type::interface_type::container_pointer;
using input_token_type = typename node_type::interface_type::value_type;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
Logger(){};
~Logger() = default;
/**
* @brief Sets the logging header
*
* @param[in] header The header description
*
* @tparam T The data type of the header, has to be convertible
* to string or be a tuple, for which an overload is
* available
* @tparam <unnamed> Template helper to enable this template only for
* types that are convertible to std::string or are
* tuples
*/
template <typename T,
typename = std::enable_if_t<
std::is_convertible_v<std::decay_t<T>, std::string> ||
exot::utilities::is_tuple_v<std::decay_t<T>>>>
void set_header(T&& header) {
logging_header_ = fmt::format("{}", header);
}
/**
* @brief Gets the logging header
*
* @return The header.
*/
std::string get_header() const { return logging_header_; }
void process() override {
using namespace std::chrono_literals;
input_token_type token;
if (!logging_header_.empty()) application_log_->info("{}", logging_header_);
while (!local_state_->is_stopped()) {
if (in_.try_read_for(token, 100ms)) {
/* Uses the overloaded ostream `operator<<` to output any tuple or
* range-like types, separating tokens with a delimeter. */
application_log_->info("{}", token);
} else {
debug_log_->debug("[Logger] reading from input queue timed out");
}
if (global_state_->is_stopped() && !in_.is_readable()) {
debug_log_->info("[Logger] terminated & queue empty");
local_state_->stop();
} else if (global_state_->is_stopped() &&
global_state_->is_terminated()) {
debug_log_->info("[Logger] terminated & shutdown");
local_state_->stop();
}
}
};
private:
state_pointer local_state_{std::make_shared<state_type>()};
std::string logging_header_;
/**
* Pointers to debug and application loggers
*/
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
logger_pointer application_log_ =
spdlog::get("app") ? spdlog::get("app") : spdlog::stdout_color_mt("app");
};
} // namespace exot::components
<file_sep>/include/exot/utilities/thread.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/thread.h
* @author <NAME>
* @brief Utilities for configuring threads.
*/
#pragma once
#include <string> // for std::string
/**
* These headers are available on Linux, Android, and Darwin platforms. If
* Windows support is desired in the future, a different mechanism for
* converting SchedulingPolicy enum to its respective platform-specific values
* will be needed, but will not impact client code.
*/
#include <pthread.h> // for pthread_t
#include <sched.h> // for SCHED_*
namespace exot::utilities {
#ifndef SCHED_DEADLINE
#define SCHED_DEADLINE 31
#endif
#ifndef SCHED_BATCH
#define SCHED_BATCH 32
#endif
#ifndef SCHED_IDLE
#define SCHED_IDLE 33
#endif
/**
* @brief A typed enum class which holds implementation-specific scheduling
* policy values
* @details An enum is used so that users do not need to include the
* <sched.h> header, and also to make the function calls more
* explicit, since functions would take the same type `int` in
* direct succession.
*/
enum class SchedulingPolicy : int {
Other = SCHED_OTHER,
Fifo = SCHED_FIFO,
RoundRobin = SCHED_RR,
Deadline = SCHED_DEADLINE,
Batch = SCHED_BATCH,
Idle = SCHED_IDLE
};
/**
* @brief Produce an info string containing information about the current
* thread
*
* @return A string containing the following: the id of the thread, the core
* on which the thread is running, the scheduling policy and
* priority
*/
std::string thread_info();
/**
* @brief A class that holds static methods to set thread properties
* @details May have no effect on certain platforms. The functions are
* arranged in a class such that it can potentially be used, for
* example, as a template parameter, injecting behaviour in other
* classes.
*/
struct ThreadTraits {
/**
* @brief Sets the affinity of the current thread
*
* @param[in] cpu The cpu to which the thread is to be pinned
*/
static int set_affinity(unsigned int cpu);
/**
* @brief Sets the affinity of the thread via its handle
* @details Pinning `std::thread` object can be performed by calling the
* `native_handle()` member function.
*
* @param[in] native_handle The native handle of the thread
* @param[in] cpu The cpu to which the thread is to be pinned
*/
static int set_affinity(pthread_t native_handle, unsigned int cpu);
/**
* @brief Sets the scheduling policy and priority of the current thread
*
* @param[in] policy The desired scheduling policy
* @param[in] priority The desired priority
*/
static int set_scheduling(SchedulingPolicy policy, int priority);
/**
* @brief Sets the scheduling policy and priority of a thread via its
* handle
*
* @param[in] native_handle The native handle of the thread
* @param[in] policy The desired scheduling policy
* @param[in] priority The desired priority
*/
static int set_scheduling(pthread_t native_handle, SchedulingPolicy policy,
int priority);
};
} // namespace exot::utilities
<file_sep>/include/exot/primitives/perf_clock.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/perf_clock.h
* @author <NAME>
* @brief Clock source using hardware and software performance counters.
*/
#pragma once
#include <assert.h>
#include <fcntl.h>
#include <linux/perf_event.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <memory>
#include <thread>
namespace exot::primitives {
/**
* @brief Checks if a number is a valid file descriptor
*
* @param fd The file descriptor
* @return true The number represents a valid file descriptor
* @return false Otherwise.
*/
inline bool is_fd(long fd) {
return ::fcntl(fd, F_GETFD) != -1 || errno != EBADF;
}
/**
* @brief A custom deleter for file descriptors to be used with unique
* pointers
*/
struct fd_deleter {
fd_deleter() = default;
fd_deleter(fd_deleter&&) = default;
void operator()(long* fd) const {
if (is_fd(*fd)) { ::close(*fd); }
delete fd;
}
};
/**
* @brief A unique pointer to a file descriptor with a deleter/closer.
*/
using fd_ptr_t = std::unique_ptr<long, fd_deleter>;
/**
* @brief A clock source using hardware CPU cycles accessed via Linux'es
* performance counters.
*/
class perf_clock {
public:
typedef std::chrono::nanoseconds duration;
typedef duration::rep rep;
typedef duration::period period;
typedef std::chrono::time_point<perf_clock> time_point;
static constexpr bool is_steady = true;
inline static fd_ptr_t fd_ptr_ = nullptr;
/**
* @brief Reads a value from the performance events file descriptor
*
* @return duration::rep The hardware CPU cycles
*/
static duration::rep raw() noexcept {
long long value;
if (perf_clock::fd_ptr_) {
return ::read(*perf_clock::fd_ptr_, &value, sizeof(value)) < sizeof(value)
? duration::rep{0}
: static_cast<duration::rep>(value);
} else {
return duration::rep{0};
}
}
static time_point now() noexcept {
static auto init = perf_clock::init();
static auto reset = perf_clock::reset();
auto _ = raw();
return time_point{duration{_}};
}
/**
* @brief Initialises the access to performance counters.
*/
static bool init() {
static struct ::perf_event_attr _;
_.type = ::PERF_TYPE_HARDWARE;
_.config = ::PERF_COUNT_HW_CPU_CYCLES;
_.size = sizeof(_);
_.exclude_kernel = 1;
_.exclude_hv = 1;
_.exclude_callchain_kernel = 1;
// Handle the creation/destruction of the file descriptor to performance
// events.
if (perf_clock::fd_ptr_) perf_clock::fd_ptr_.reset(nullptr);
perf_clock::fd_ptr_.reset(
new long{::syscall(__NR_perf_event_open, &_, 0, -1, -1, 0)});
return (*perf_clock::fd_ptr_ >= 0);
}
/**
* @brief Resets access to performance counters.
*/
static bool reset() {
if (perf_clock::fd_ptr_) {
::ioctl(*perf_clock::fd_ptr_, PERF_EVENT_IOC_RESET, 0);
return true;
} else {
return false;
}
}
};
/**
* @brief A clock source using hardware CPU cycles accessed via Linux'es
* performance counters.
*/
class perf_sw_clock {
public:
typedef std::chrono::nanoseconds duration;
typedef duration::rep rep;
typedef duration::period period;
typedef std::chrono::time_point<perf_sw_clock> time_point;
static constexpr bool is_steady = true;
inline static fd_ptr_t fd_ptr_ = nullptr;
/**
* @brief Reads a value from the performance events file descriptor
*
* @return duration::rep The software CPU cycles
*/
static duration::rep raw() noexcept {
long long value;
if (perf_sw_clock::fd_ptr_) {
return ::read(*perf_sw_clock::fd_ptr_, &value, sizeof(value)) <
sizeof(value)
? duration::rep{0}
: static_cast<duration::rep>(value);
} else {
return duration::rep{0};
}
}
static time_point now() noexcept {
static auto init = perf_sw_clock::init();
static auto reset = perf_sw_clock::reset();
auto _ = perf_sw_clock::raw();
return time_point{duration{_}};
}
/**
* @brief Initialises the access to performance counters.
*/
static bool init() {
static struct ::perf_event_attr _;
_.type = ::PERF_TYPE_SOFTWARE;
_.config = ::PERF_COUNT_SW_CPU_CLOCK;
_.size = sizeof(_);
_.exclude_kernel = 1;
_.exclude_hv = 1;
_.exclude_callchain_kernel = 1;
if (perf_sw_clock::fd_ptr_) perf_sw_clock::fd_ptr_.reset(nullptr);
perf_sw_clock::fd_ptr_.reset(
new long{::syscall(__NR_perf_event_open, &_, 0, -1, -1, 0)});
return (*perf_sw_clock::fd_ptr_ >= 0);
}
/**
* @brief Resets access to performance counters.
*/
static bool reset() {
if (perf_sw_clock::fd_ptr_) {
::ioctl(*perf_sw_clock::fd_ptr_, PERF_EVENT_IOC_RESET, 0);
::ioctl(*perf_sw_clock::fd_ptr_, PERF_EVENT_IOC_ENABLE, 0);
return true;
} else {
return false;
}
}
};
} // namespace exot::primitives
<file_sep>/include/exot/utilities/synchronised.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/synchronised.h
* @author <NAME>
* @brief Synchronised type wrappers
*/
#pragma once
#include <mutex>
#include <type_traits>
namespace exot::utilities {
/**
* @brief Synchronised type wrapper
*
* @tparam T The wrapped type
*/
template <typename T>
struct synchronised_t {
using wrapped_type = std::decay_t<T>;
using lock_type = std::mutex;
using guard_type = std::lock_guard<lock_type>;
/**
* @brief Constructs a synchronised object with const reference
*
* @param[in] object The object
*/
synchronised_t(const T& object) : object_{object} {}
/**
* @brief Constructs a synchronised object with a move (ref or value)
*
* @param object The object
*/
synchronised_t(T&& object) : object_{std::move(object)} {}
/**
* @brief Constructs a synchronised object by copying
*
* @param[in] other The other
*/
synchronised_t(const synchronised_t& other) {
guard_type{lock_};
other.access([&](auto& _) { object_ = _; });
}
/**
* @brief Assigns wrapped contents from another passed by const ref
*
* @param[in] other The other
*
* @return The reference to the updated object
*/
synchronised_t& operator=(const synchronised_t& other) {
guard_type{lock_};
object_ = other.operator wrapped_type();
return *this;
}
/**
* @brief Assigns wrapped contents from another passed by 'mutable' ref
*
* @param[in] other The other
*
* @return The reference to the updated object
*/
synchronised_t& operator=(synchronised_t& other) {
guard_type{lock_};
other.access([&](auto& _) { object_ = _; });
return *this;
}
/**
* @brief Accesses the wrapped contents while holding a lock using a
* callable
*
* @param callable The callable
*
* @tparam Callable The type of the callable
*
* @return The return value of the callable
*/
template <typename Callable>
auto access(Callable&& callable) {
return guard_type{lock_}, std::forward<Callable>(callable)(object_);
}
/* Guarded operators for access to the wrapped object
*
* Functions below use the comma operator. When (A, B) is evaluated, the
* result of A is discarded, and it's side effects are completed before B is
* evaluated. However, if A has class type, it won't be destroyed until the
* end of the entire expression. Therefore if used with the lock guard, the
* lock will be held until the operation is finished.
*/
wrapped_type* operator->() { return guard_type{lock_}, &object_; }
wrapped_type* operator&() { return guard_type{lock_}, &object_; }
wrapped_type& operator*() { return guard_type{lock_}, object_; }
operator wrapped_type() const { return guard_type{lock_}, object_; }
private:
wrapped_type object_; //! the wrapped object
lock_type lock_; //! the guarding lock
};
} // namespace exot::utilities
<file_sep>/include/exot/primitives/msr.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/msr.h
* @author <NAME>
* @brief Module Specific Register accessor class, requires msr kernel
* module installed and loaded.
*/
#pragma once
/**
* Reading the MSRs via the file descriptors works only on Linux-based
* platforms, excluding Android.
*
* @todo On FreeBSD, `cpuctl` can be used with the associated special
* pseudo-device (and the userspace control utility `cpucontrol`) to read/write
* machine specific registers. Implementation should be easier than in the case
* of Linux.
*
* On Darwin, there is no straightforward way of accessing the registers,
* certainly not without developing a kernel extension.
*
* On some ARM architectures the performance monitoring unit could be
* potentially used.
*/
#if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
#include <fcntl.h> // for open
#include <unistd.h> // for pread, prwite
#include <algorithm> // for all_of, sort, unique
#include <cstdint> // for uint*
#include <exception> // for logic_error
#include <fstream> // for fstream
#include <initializer_list> // for initializer_list
#include <ios> // for seekdir
#include <map> // for mapping between cpu and array index
#include <numeric> // for iota
#include <string> // for std::string
#include <thread> // for hardware_concurrency
#include <vector> // for variable-size arrays
#include <fmt/format.h> // for string formatting
#include <exot/utilities/bits.h> // for bit manipulation
namespace exot::primitives {
class MSR {
public:
/**
* @brief Constructs the object with an initialiser list
*
* @param[in] cpus An initialiser list with CPU identifiers
*/
explicit MSR(std::initializer_list<unsigned> cpus);
/**
* @brief Constructs the object with a vector via const reference
*
* @param[in] cpus A const reference to a vector with CPU identifiers
*/
explicit MSR(const std::vector<unsigned>& cpus);
/**
* @brief Constructs the object with a vector via move
* @details The vector can be provided in-place, inside the call to the
* constructor.
*
* @param[in] cpus A vector with CPU identifiers
*/
explicit MSR(std::vector<unsigned>&& cpus);
/**
* @brief The default constructor
* @details Provides access to all available MSR pseudo-devices.
*/
MSR();
/**
* @brief Operator to allow reassignment
* @details Since the constructors are responsible for opening/closing file
* descriptors, a custom assignment operator is needed, to
* reinitialise the access to pseudo-devices.
*
* @param[in] other The other MSR object
*
* @return The "copied" object
*/
MSR& operator=(const MSR& other);
~MSR();
/**
* @brief Reads a value from a CPU's model specific register
*
* @param[in] cpu The cpu
* @param[in] msr The msr
*
* @return The value of the MSR
*/
std::uint64_t read(unsigned int cpu, std::uint64_t msr);
/**
* @brief Reads an MSR from the next configured CPU
* @details The helper function is given so that the user of the class does
* not necessarily need to know how many MSR interfaces are
* accessible. After each read operation the next configured CPU
* is used.
*
* @param[in] msr The msr
*
* @return The value of the MSR
*/
std::uint64_t read_any(std::uint64_t msr);
/**
* @brief Reads an MSR from the first configured CPU
*
* @param[in] msr The msr
*
* @return The value of the MSR
*/
std::uint64_t read_first(std::uint64_t msr);
/**
* @brief Writes a value to a CPU's model specific register
*
* @param[in] cpu The cpu
* @param[in] msr The msr
* @param[in] value The value
*/
void write(unsigned int cpu, std::uint64_t msr, uint64_t value);
/**
* @brief Writes an MSR for the next configured CPU
*
* @param[in] msr The msr
* @param[in] value The value
*/
void write_any(std::uint64_t msr, std::uint64_t value);
/**
* @brief Writes a value to the first configured CPU's MSR
*
* @param[in] msr The msr
* @param[in] value The value
*/
void write_first(std::uint64_t msr, std::uint64_t value);
/**
* @brief Reads a value from all CPU's model specific registers
*
* @param[in] msr The msr
*
* @return A vector holding the read values
*/
std::vector<std::uint64_t> read_all(std::uint64_t msr);
/**
* @brief Writes a value to all CPU's model specific registers
*
* @param[in] msr The msr
* @param[in] value The value
*/
void write_all(std::uint64_t msr, uint64_t value);
/**
* @brief Gets the filenames of used pseudo-devices
*
* @return The filenames.
*/
std::vector<std::string> get_filenames() const;
std::vector<int> get_file_descriptors() const;
std::vector<unsigned int> get_cpus() const;
int get_cpu_count() const;
auto get_index_to_cpu_mapping() const;
private:
std::vector<unsigned int> cpus_; //! vector of CPUs to be accessed
std::vector<std::string> filenames_; //! vector of filenames
std::vector<int> file_descriptors_; //! vector of file descriptors
std::map<unsigned int, unsigned int>
cpu_to_index_; //! map between CPU number and array index
std::vector<std::uint64_t> values;
unsigned int used_cpu_mask_{0}; //! convienience variable used for fast
//! checking if chosen cpu is available.
/**
* @brief Initialises access to pseudo-devices and makes sure they are
* readable
*/
inline void init();
/**
* @brief Sorts and removes duplicates from the vector of CPUs
*/
inline void conform();
/**
* @brief Checks if any of the provided CPUs exceeds thread count
*/
inline void check() const;
};
} // namespace exot::primitives
#endif
<file_sep>/include/exot/utilities/helpers.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/helpers.h
* @author <NAME>
* @brief Helper templates, among others for compile-time code generation,
* tuple access, and statistics.
*/
#pragma once
#include <algorithm> // for generate
#include <array> // for fixed-size arrays
#include <cmath> // for std::sqrt
#include <numeric> // for inner_product, accumulate,...
#include <tuple> // for packing into and operating on tuples
#include <utility> // for integral_constant, etc.
#include <vector> // for variable-size arrays
#include <exot/utilities/types.h>
namespace exot::utilities {
namespace details {
/**
* @brief Helper template used by `const_for`
* @details The helper uses pack expansion to construct a compile-time
* sequence of `std::size_t` integers, which are then incrementally
* provided to a callable object, also by means of parameter pack
* expansion.
*
* `std::size_t` is used because it is commonly used for array
* indexing and loop counting. Moreover, this allows the use of the
* `sizeof` operator, which return type is `size_t`.
*
* @param[in] func A callable object (e.g. lambda, functor)
* @param[in] <unnamed> A compile-time sequence of `std::size_t` integers,
* used in template pack expansion
*
* @tparam Begin First sequence number (similar to the first parameter
* in a `for` loop declaration)
* @tparam Callable A callable type
* @tparam I Sequence of `std::size_t` types
*/
template <std::size_t Begin, typename Callable, std::size_t... I>
constexpr void const_for_impl(Callable&& func, std::index_sequence<I...>) {
/* std::integral_constant<T,V> makes a static constexpr type T with value V,
* so the function `func` below is provided with a constexpr `std::size_t`
* value (Begin + I), which can later be used in templates and static
* contexts.
*
* The pack expansion over `...` produces code:
* @code{c++}
* (func(Begin), func(Begin+1), func(Begin+2), ...);
* @endcode
*/
(func(std::integral_constant<std::size_t, Begin + I>{}), ...);
};
/**
* @brief Helper template used by `for_each`
* @details The helper uses a compile-time sequence of integers and pack
* expansion to access tuple elements via `std::get`.
*
* @param[in] tuple A tuple
* @param[in] func A callable object
* @param[in] <unnamed> A compile-time sequence of `std::size_t` integers,
* used in template pack expansion
*
* @tparam Callable A callable type
* @tparam Tuple The type of the tuple
* @tparam I Sequence of `std::size_t` types
*/
template <typename Callable, typename Tuple, std::size_t... I>
constexpr void for_each_impl(Tuple&& tuple, Callable&& func,
std::index_sequence<I...>) {
/* The pack expansion produces code: `(func(get<0>(tuple)),
* func(get<1>(tuple)), ...);`. */
(func(std::get<I>(tuple)), ...);
};
/**
* @brief Makes a tuple out of values of tuples at a specific index position
*
* @tparam I The index
* @tparam Ts The tuples' types
* @param ts The tuples
* @return A tuple of values at position I
*/
template <std::size_t I, typename... Ts>
auto zip_at_idx(Ts&&... ts) {
return std::make_tuple(std::get<I>(std::forward<Ts>(ts))...);
}
/**
* @brief Zips a number of tuples
*
* @tparam Ts The tuples' types
* @tparam I The index sequence
* @param ts The tuples
* @return The zipped tupples, a tuple of tuples
*/
template <typename... Ts, std::size_t... I>
auto zip_impl(Ts&&... ts, std::index_sequence<I...>) {
return std::make_tuple(zip_at_idx<I>(std::forward<Ts>(ts)...)...);
}
/**
* @brief Makes a tuple with forwarded values of tuples at specific index
*
* @tparam I The index
* @tparam Ts The tuples' types
* @param ts The tuples
* @return A tuple with forwarded values
*/
template <std::size_t I, typename... Ts>
auto zip_fwd_at_idx(Ts&&... ts) {
return std::forward_as_tuple(std::get<I>(std::forward<Ts>(ts))...);
}
/**
* @brief Zips a number of tuples by forwarding values
*
* @tparam Ts The tuples' types
* @tparam I The index sequence
* @param ts The tuples
* @return The zipped tupples, a tuple of tuples
*/
template <typename... Ts, std::size_t... I>
auto zip_fwd_impl(Ts&&... ts, std::index_sequence<I...>) {
return std::forward_as_tuple(zip_fwd_at_idx<I>(std::forward<Ts>(ts)...)...);
}
template <std::size_t I, typename... Ts, std::size_t... Is>
auto slice_tuple(std::tuple<Ts...>&& _t, std::index_sequence<Is...>) {
return std::make_tuple(std::get<I + Is>(_t)...);
}
template <std::size_t I, typename... Ts, std::size_t... Is>
auto slice_fwd_tuple(std::tuple<Ts...>&& _t, std::index_sequence<Is...>) {
return std::forward_as_tuple(std::get<I + Is>(_t)...);
}
} // namespace details
/**
* @brief A compile-time for-loop
* @details Uses the helper above to generate a sequence of `std::size_t`
* integers from Begin to End, invokes the callable object with the
* constexpr index, e.g. `std::integral_constant<unsigned long,
* 0ul>` on a 64-bit architecture. If a lambda is provided, the call
* will be to an anonymous class' `operator() const`. Functions
* provided to the static for-loop should also be constexpr.
*
* @param[in] func A callable object
*
* @tparam Begin First sequence number (similar to the first parameter
* in a `for` loop declaration)
* @tparam End Last sequence number (similar to the second parameter
* in a `for` loop declaration, increment is implied)
* @tparam Callable A callable type
*/
template <std::size_t Begin, std::size_t End, typename Callable>
constexpr void const_for(Callable&& func) {
/* `std::make_index_sequence<N>` creates `std::size_t` sequence from 0 to N-1,
* therefore the helper generates a sequence from Begin to (End-Begin-1). */
details::const_for_impl<Begin>(std::forward<Callable>(func),
std::make_index_sequence<End - Begin>{});
};
/**
* @brief Apply a function to each tuple element
*
* @param[in] tuple The tuple
* @param[in] func A callable object
*
* @tparam Callable A callable type
* @tparam Ts Individual tuple types
*/
template <typename Callable, typename... Ts>
constexpr void for_each(std::tuple<Ts...>&& tuple, Callable&& func) {
details::for_each_impl(std::forward<decltype(tuple)>(tuple),
std::forward<Callable>(func),
std::index_sequence_for<Ts...>{});
};
/* If std::apply is available in the `<tuple>` header. */
#ifdef __cpp_lib_apply
/**
* @brief Wrapper for std::apply
* @details Applies a non-returning function to each tuple element, using
* pack expansion. The tuple elements are processed in order.
*
* @param[in] f The function to apply
* @param[in] tuple The tuple to operate on
*
* @tparam Func A callable type
* @tparam Tuple A tuple type
*/
template <typename Func, typename Tuple>
constexpr void apply(Func&& f, Tuple&& tuple) {
/* Produces same behaviour as `for_each`. */
std::apply([&f](auto&... x) { (..., f(x)); }, std::forward<Tuple>(tuple));
};
template <typename Head, typename... Tail>
auto tail(std::tuple<Head, Tail...>&& value) {
return std::apply(
[](auto&& head, auto&&... tail) {
return std::forward_as_tuple(tail...);
},
value);
}
#else
template <typename... Ts>
auto tail(std::tuple<Ts...>&& value) {
return details::slice_fwd_tuple<1ull>(
std::forward<decltype(value)>(value),
std::make_index_sequence<sizeof...(Ts) - 1ull>());
}
#endif
/**
* @brief Zips multiple tuples together
*
* @tparam T The first tuple type
* @tparam Ts The other tuples' types
* @param t The first tuple
* @param ts The other tuples
* @return The zipped tuples
*/
template <typename T, typename... Ts>
auto zip(T&& t, Ts&&... ts) {
static_assert((... && (std::tuple_size_v<std::decay_t<T>> ==
std::tuple_size_v<std::decay_t<Ts>>)),
"must be of same size");
return details::zip_impl<T, Ts...>(
std::forward<T>(t), std::forward<Ts>(ts)...,
std::make_index_sequence<std::tuple_size_v<std::decay_t<T>>>());
}
/**
* @brief Zips multiple tuples together by forwarding values
*
* @tparam T The first tuple type
* @tparam Ts The other tuples' types
* @param t The first tuple
* @param ts The other tuples
* @return The zipped tuples
*/
template <typename T, typename... Ts>
auto zip_fwd(T&& t, Ts&&... ts) {
static_assert((... && (std::tuple_size_v<std::decay_t<T>> ==
std::tuple_size_v<std::decay_t<Ts>>)),
"must be of same size");
return details::zip_fwd_impl(
std::forward<T>(t), std::forward<Ts>(ts)...,
std::make_index_sequence<std::tuple_size_v<std::decay_t<T>>>());
}
/**
* @brief Calculates the mean and standard deviation of values in a
* container
*
* @param[in] input The input container
*
* @tparam T The value type
* @tparam <unnamed> Template helper
*
* @return The mean and deviation as an array of doubles
*/
template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
auto mean_and_deviation(const std::vector<T>& input) -> std::array<double, 2> {
auto mean =
static_cast<double>(std::accumulate(input.begin(), input.end(), (T{0}))) /
input.size();
using difference_type = decltype(T{0} - T{0});
std::vector<difference_type> deviations(input.size());
std::transform(input.begin(), input.end(), deviations.begin(),
[mean](auto in) { return (in - mean); });
/* The accumulator {a} in inner_product calculates: a += *iterator1 *
* *iterator2, starts with 0.0. Computes the squared sum(x - mean)(x - mean)
* in variance computation. */
auto squared_sum = std::inner_product(deviations.begin(), deviations.end(),
deviations.begin(), difference_type{0});
double standard_deviation = std::sqrt((double)squared_sum / input.size());
return {mean, standard_deviation};
}
/**
* @brief Gets a slice of an interable container
*
* @param[in] container The container
* @param[in] lower The lower index
* @param[in] upper The upper index
*
* @tparam T The type of the container
* @tparam <unnamed> Template helper
*
* @return The slice, reversed if lower < upper
*/
template <typename T,
typename = std::enable_if_t<exot::utilities::is_iterable_v<T>>>
constexpr auto slice(const T& container, std::size_t lower, std::size_t upper)
-> T {
if (lower <= upper) {
return T(std::begin(container) + lower, std::begin(container) + upper);
} else {
T dest(std::distance(std::begin(container) + upper,
std::begin(container) + lower));
std::reverse_copy(std::begin(container) + upper,
std::begin(container) + lower, std::begin(dest));
return dest;
}
}
/**
* @brief Gets a percentile of values in a container
* @note Only arithmetic value types are supported.
*
* @param[in] container The container
* @param[in] value The percentile in range (0, 1)
*
* @tparam T The container type
* @tparam <unnamed> Template helper
*
* @return The percentile value of elements in the container.
*/
template <typename T, typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
exot::utilities::is_iterable_v<T> &&
std::is_arithmetic_v<typename T::value_type>)>>
constexpr auto percentile(T container, double value) -> typename T::value_type {
if (container.empty())
throw std::logic_error(
"Cannot calculate percentiles for an empty container.");
if ((value >= 1) || (value <= 0))
throw std::out_of_range("Percentiles must be in range (0,1).");
auto position = static_cast<std::size_t>(std::max(
0ul,
std::min(static_cast<std::size_t>(std::ceil(container.size() * value)),
container.size() - 1ul)));
if (!std::is_sorted(std::begin(container), std::end(container)))
std::sort(std::begin(container), std::end(container));
return container.at(position);
}
/**
* @brief Gets a percentile of values in a container, sorting it in place
* @note Only arithmetic value types are supported. The side effect is
* that the input container will become sorted.
*
* @param[in] container The container
* @param[in] value The percentile in range (0, 1)
*
* @tparam T The container type
* @tparam <unnamed> Template helper
*
* @return The percentile value of elements in the container.
*/
template <typename T, typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
exot::utilities::is_iterable_v<T> &&
std::is_arithmetic_v<typename T::value_type>)>>
constexpr auto percentile_sort_in_place(T& container, double value) ->
typename T::value_type {
if (container.empty())
throw std::logic_error(
"Cannot calculate percentiles for an empty container.");
if ((value >= 1) || (value <= 0))
throw std::out_of_range("Percentiles must be in range (0,1).");
auto position = static_cast<std::size_t>(std::max(
0ul,
std::min(static_cast<std::size_t>(std::ceil(container.size() * value)),
container.size() - 1ul)));
if (!std::is_sorted(std::begin(container), std::end(container)))
std::sort(std::begin(container), std::end(container));
return container.at(position);
}
/**
* @brief Gets a slice of a container in percentile limits
*
* @param[in] container The container
* @param[in] lower The lower percentile in range (0, 1]
* @param[in] upper The upper percentile in range (0, 1]
*
* @tparam T The container type
* @tparam <unnamed> Template helper
*
* @return A slice of the container within limits, reversed if lower > upper
*/
template <typename T, typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
exot::utilities::is_iterable_v<T> &&
std::is_arithmetic_v<typename T::value_type>)>>
constexpr auto percentile_range(T container, double lower, double upper) -> T {
if (container.empty())
throw std::logic_error(
"Cannot calculate percentiles for an empty container.");
if (!std::is_sorted(std::begin(container), std::end(container)))
std::sort(std::begin(container), std::end(container));
if ((lower > 1) || (lower <= 0) || (upper > 1) || (upper <= 0))
throw std::out_of_range("Percentiles must be in range (0,1].");
auto llim = static_cast<std::size_t>(std::max(
0ul,
std::min(static_cast<std::size_t>(std::ceil(container.size() * lower)),
container.size() - 1ul)));
auto ulim = static_cast<std::size_t>(std::max(
0ul,
std::min(static_cast<std::size_t>(std::ceil(container.size() * upper)),
container.size() - 1ul)));
return slice(container, llim, ulim);
}
/**
* @brief Determines if power of 2.
*
* @param[in] value The value
*
* @tparam T The type of the value (unsigned integral)
* @tparam <unnamed> Template helper
*
* @return True if power of 2, False otherwise.
*/
template <typename T, typename = std::enable_if_t<std::is_integral_v<T> &&
std::is_unsigned_v<T>>>
constexpr inline bool is_power_of_2(T value) noexcept {
return (value > 0) && ((value & (value - 1)) == 0);
}
/**
* @brief Determines if a value is within a set of other values.
*
* @param[in] t The value to compare
* @param[in] ts The set of values to compare against
*
* @tparam T The type of the value to compare
* @tparam Ts The types of the values to compare against
* @tparam <unnamed> Template helper which determines if all decayed types
* are the same
*
* @return True if t is one of ts, False otherwise.
*/
template <typename T, typename... Ts,
typename = typename std::enable_if<
(... && is_convertible_d<T, Ts>::value)>::type>
inline constexpr bool is_one_of(T&& t, Ts&&... ts) {
return (... || (t == ts));
}
/**
* @brief Determines if a value is not in a set of other values.
*
* @param[in] t The value to compare
* @param[in] ts The set of values to compare against
*
* @tparam T The type of the value to compare
* @tparam Ts The types of the values to compare against
* @tparam <unnamed> Template helper which determines if all decayed types
* are the same
*
* @return True if t isn't one of ts, False otherwise.
*/
template <typename T, typename... Ts,
typename = typename std::enable_if<
(... && is_convertible_d<T, Ts>::value)>::type>
inline constexpr bool is_none_of(T&& t, Ts&&... ts) {
return !is_one_of(std::forward<T>(t), std::forward<Ts>(ts)...);
}
/**
* @brief Check if a container contains an element
* @details The provided type T must conform to the 'is_iterable' type trait,
* the value type is obtained from a member type/alias 'value_type'.
*
* @param[in] v The value to check
* @param[in] container The container
*
* @tparam T The type of the container
* @tparam <unnamed> Template helper
*
* @return True if found, false otherwise.
*/
template <typename T, typename = std::enable_if_t<is_iterable_v<T>>>
auto contains(typename T::value_type v, const T& container) -> bool {
return std::find(std::begin(container), std::end(container), v) !=
std::end(container);
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool is_greater(T t, Ts&&... ts) {
return (... && (t > ts));
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool is_greater_or_equal(T t, Ts&&... ts) {
return (... && (t >= ts));
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool assert_is_greater(T t, Ts&&... ts) {
return (... && (t > ts))
? true
: throw std::logic_error("First operand is not larger then rest");
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool assert_is_greater_or_equal(T t, Ts&&... ts) {
return (... && (t >= ts))
? true
: throw std::logic_error(
"First operand is not larger or equal then rest");
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool is_smaller(T t, Ts&&... ts) {
return (... && (t < ts));
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool is_smaller_or_equal(T t, Ts&&... ts) {
return (... && (t <= ts));
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_lessthan_comparable_v<T>>>
constexpr bool assert_is_smaller(T t, Ts&&... ts) {
return (... && (t < ts))
? true
: throw std::logic_error("First operand is not smaller then rest");
}
template <typename T, typename... Ts,
typename = std::enable_if_t<(is_convertible_d<T, Ts>::value && ...) &&
is_comparable_v<T>>>
constexpr bool assert_is_smaller_or_equal(T t, Ts&&... ts) {
return (... && (t <= ts))
? true
: throw std::logic_error(
"First operand is not smaller or equal then rest");
}
/* The following helpers should work on all compilers that have been used
* for the project: GCC and LLVM Clang. */
/**
* @brief Helper to prevent the compiler from optimising a variable
*
* @param var The const reference to the variable
*
* @tparam T The type of the variable
*/
template <typename T>
inline __attribute__((always_inline)) void do_not_optimise(T const& var) {
asm volatile("" : : "r,m"(var) : "memory");
}
/**
* @brief Helper to prevent the compiler from optimising a variable
*
* @param var The reference to the variable
*
* @tparam T The type of the variable
*/
template <typename T>
inline __attribute__((always_inline)) void do_not_optimise(T& var) {
#if defined(__clang__)
asm volatile("" : "+r,m"(var) : : "memory");
#else
asm volatile("" : "+m,r"(var) : : "memory");
#endif
}
template <typename... Ts>
inline __attribute__((always_inline)) void do_not_optimise(Ts&&... vars) {
static_assert((std::is_lvalue_reference<Ts>::value && ...),
"all vars need to be references (or const references)");
(..., do_not_optimise(std::forward<Ts>(vars)));
}
/**
* Alias for US spelling of 'optimise'.
*/
template <typename... Ts>
inline __attribute__((always_inline)) void do_not_optimize(Ts&&... vars) {
do_not_optimise(std::forward<Ts>(vars)...);
}
/**
* @brief Determines if values or function returns are constexpr.
* @note Cannot be used on functions with signatures void(...).
*
* @param ts The values
*
* @tparam Ts The value types
*
* @return True if all are constexpr, False otherwise.
*/
template <typename... Ts>
constexpr bool is_constexpr(Ts&&... ts) {
return (noexcept(ts) && ...);
}
} // namespace exot::utilities
<file_sep>/include/exot/utilities/timing.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/timing.h
* @author <NAME>
* @brief Timing utilities, including the TimeKeeper template for running
* timing-critical code.
*/
#pragma once
#include <algorithm> // for std::generate
#include <array> // for fixed-size arrays
#include <chrono> // for clocks and durations
#include <cmath> // for std::sqrt
#include <ctime> // for std::tm and std::*time
#include <numeric> // for std::inner_product, std::accumulate
#include <string> // for std::string
#include <thread> // for std::this_thread::sleep_for
#include <type_traits> // for true/false_type and declval
#include <vector> // for variable-size arrays
/**
* On POSIX platforms, provide an STL-like wrapper for `nanosleep`.
*/
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <time.h> // for nanosleep and timespec
#endif
#include <fmt/format.h> // for string formatting
#include <spdlog/spdlog.h> // for logging
#include <exot/utilities/formatting.h> // for duration_unit
#include <exot/utilities/helpers.h> // for do_not_optimise
#include <exot/utilities/types.h> // for type traits
#include <exot/primitives/tsc.h>
namespace exot::utilities {
/**
* @brief Time the execution of a callable using timestamp counters
*
* @param callable The callable
* @param args The arguments to the callable
*
* @tparam Counter A TSC (must derive from TimeStampCounter)
* @tparam Callable A callable type
* @tparam Args Argument types to the callable
* @tparam <unnamed> Template helper
*
* @return The execution duration in TSC-specific units
*/
template <typename Counter, typename Callable, typename... Args,
typename = std::enable_if_t<
exot::primitives::is_time_stamp_counter_v<Counter>>>
auto timeit(Callable&& callable, Args&&... args) {
auto start = Counter::start();
callable(std::forward<Args>(args)...);
return Counter::stop() - start;
}
/**
* @brief Time the execution of a callable using any std::chrono-like clock
*
* @param callable The callable
* @param args The arguments to the callable
*
* @tparam Clock A Clock type, e.g. std::chrono::steady_clock
* @tparam Callable A callable type
* @tparam Args Argument types to the callable
* @tparam <unnamed> Template helper
*
* @return The execution duration as a duration, e.g. chrono::nanoseconds
*/
template <typename Clock, typename Callable, typename... Args,
typename = std::enable_if_t<is_clock_v<Clock>>>
auto timeit(Callable&& callable, Args&&... args) -> typename Clock::duration {
auto start = Clock::now();
callable(std::forward<Args>(args)...);
return Clock::now() - start;
}
namespace details {
/**
* @brief Functor to estimate the overhead of the sleeping function.
*
* @tparam Clock Evaluated clock type, e.g. std::chrono::steady_clock;
*/
template <typename Clock>
struct sleep_overhead {
using clock_type = Clock;
using duration_type = typename Clock::duration;
/**
* @brief Constructor that sets the sleep duration
*
* @param[in] duration The sleep duration
*/
explicit sleep_overhead(duration_type duration) : duration{duration} {};
/**
* @brief The default constructor, estimate the overhead of calling the
* sleep function with zero sleep duration
*/
sleep_overhead() : sleep_overhead(duration_type{0}){};
duration_type operator()() {
auto start{clock_type::now()};
std::this_thread::sleep_for(duration);
return {clock_type::now() - start};
}
private:
duration_type duration{0};
};
/**
* @brief Functor to estimate the overhead of the basic timing primitives.
*
* @tparam Clock Evaluated clock type, e.g. std::chrono::steady_clock;
*/
template <typename Clock>
struct timing_overhead {
using clock_type = Clock;
using duration_type = typename clock_type::duration;
/**
* @return Time difference between the consecutive calls to now().
*/
duration_type operator()() {
auto start(clock_type::now());
return (clock_type::now() - start);
};
};
/**
* @brief Functor to estimate the mean overhead for basic timing
* primitives.
*
* @tparam Clock Evaluated clock type, e.g. std::chrono::steady_clock;
* @tparam Overhead The particular overhead functor
*/
template <typename Clock, template <typename> typename Overhead>
struct get_overhead {
using clock_type = Clock;
using duration_type = typename clock_type::duration;
using overhead = Overhead<clock_type>;
/**
* @brief Repetitively calls timing_overhead.
*
* @param[in] iterations Number of repeated calls to timing_overhead.
* @return Mean timing overhead over all iterations.
*/
duration_type operator()(unsigned int iterations) {
std::vector<duration_type> overheads(iterations);
std::generate(overheads.begin(), overheads.end(), overhead());
return std::accumulate(overheads.begin(), overheads.end(),
(duration_type(0))) /
overheads.size();
};
};
/**
* @brief Computes mean and standard deviation from a vector of
* std::chrono::duration.
*
* @param[in] input Input vector of InputGranularity objects.
*
* @tparam InputGranularity Input duration granularity used in the vector,
* e.g. `std::chrono::nanoseconds`;
* @tparam OutputGranularity Output duration granularity;
*
* @return Tuple holding computed mean and standard deviation.
*/
template <typename InputGranularity, typename OutputGranularity>
auto chrono_statistics(const std::vector<InputGranularity>& input) {
auto mean =
std::accumulate(input.begin(), input.end(), (InputGranularity(0))) /
input.size();
/* Calculate the mean differences */
std::vector<typename InputGranularity::rep> deviations(input.size());
std::transform(input.begin(), input.end(), deviations.begin(),
[mean](InputGranularity in) { return (in - mean).count(); });
/* The accumulator {a} in inner_product calculates: a += *iterator1 *
* *iterator2, starts with 0.0. Computes the squared sum(x - mean)(x - mean)
* in variance computation. */
auto squared_sum = std::inner_product(deviations.begin(), deviations.end(),
deviations.begin(), 0.0);
auto standard_deviation_ = std::sqrt(squared_sum / input.size());
/* Average interval */
OutputGranularity average =
std::chrono::duration_cast<OutputGranularity>(mean);
/* Standard deviation */
std::chrono::duration<double, typename InputGranularity::period> tmp(
standard_deviation_);
OutputGranularity standard_deviation =
std::chrono::duration_cast<OutputGranularity>(tmp);
return std::array<OutputGranularity, 2>{average, standard_deviation};
}
} // namespace details
#ifndef TimeKeeper_OFFSET_RETURNS
#define TimeKeeper_OFFSET_RETURNS 0
#endif
namespace details {
struct TimeKeeperOptions {
static constexpr bool offset_returns =
static_cast<bool>(TimeKeeper_OFFSET_RETURNS);
};
inline constexpr TimeKeeperOptions TIME_KEEPER_OPTIONS;
} // namespace details
/**
* @brief Class used for keeping track of sleep time and offsets.
* @details The time keeper provides an interface for sleeping with offset
* and overhead accounting, can use different clock sources and
* sleep functions, and can report interval, offset, and
* differential statistics of sleep durations.
*
* @tparam Clock A clock type, which provides a `now()` method,
* e.g. `std::chrono::steady_clock`
* @tparam EnableLogging A boolean value to indicate use internal offset
* logging
* @tparam RepGranularity Chrono duration granularity used for time
* reporting
* @tparam Granularity Chrono duration granularity used for time
* keeping, e.g. `std::chrono::nanoseconds`
*/
template <typename Clock = std::chrono::steady_clock, bool EnableLogging = true,
typename RepGranularity = std::chrono::microseconds,
typename Granularity = std::chrono::nanoseconds>
class TimeKeeper {
public:
using clock_type = Clock;
using chrono_granularity = Granularity;
using reporting_granularity = RepGranularity;
using sleep_func_type = std::function<void(const chrono_granularity&)>;
using sleep_func_rep = typename chrono_granularity::rep;
using sleep_func_period = typename chrono_granularity::period;
/**
* Default values for reserved log size, overhead iterations, and minimum
* sleep duration.
*
* The storage size of most duration types is equal or less than the size of
* `unsigned long`, which is 8 bytes. A pre-reserved vector log size of
* 10000000 amounts to 80 MB of RAM used for keeping the log. While the log
* could be smaller, depending on the duration of an experiment, one might
* experience a performance drop due to the need to reallocate storage space
* for the vector.
*/
static const unsigned int default_log_size_to_reserve{10000000};
static const unsigned int default_overhead_calculations{1000};
static const typename chrono_granularity::rep default_minimum_percentage{0};
/**
* @brief Constructs the object with all options.
* @details In order to allow the use of different sleep functions (e.g.
* `nanosleep`, `std::this_thread::sleep_for`,
* `boost::this_fiber::sleep_for`, etc.) the constructor takes a
* pointer to that function, instead of using the older template
* parameter.
*
* @param[in] logger A shared pointer to application logger
* @param[in] sleep_function The address of a sleep function, by
* default uses the
* `std::this_thread::sleep_for` function.
* @param[in] minimum_percentage The minimum percentage of the passed sleep
* duration that will be passed to the
* sleeping function. The value is used in
* the call to `std::max`, which result is
* passed to the actual sleeping function.
* @param[in] log_size_to_reserve The reserved vector size for logging
* desired, actual, and offset durations
* @param[in] overhead_iterations The number of iterations used for
* calculating the offset of a sequence of
* calls to `clock_type::now()` and the
* necessary subtraction used to obtain the
* duration between the calls.
*/
explicit TimeKeeper(
std::shared_ptr<spdlog::logger> logger = nullptr,
sleep_func_type sleep_function =
&std::this_thread::sleep_for<sleep_func_rep, sleep_func_period>,
typename chrono_granularity::rep minimum_percentage =
default_minimum_percentage,
unsigned int log_size_to_reserve = default_log_size_to_reserve,
unsigned int overhead_iterations = default_overhead_calculations)
: sleep_function_(sleep_function),
logger_{std::move(logger)},
minimum_percentage_{minimum_percentage} {
logger_ = logger_ ? logger_
: (spdlog::get("log") ? spdlog::get("log")
: spdlog::default_logger());
bootstrap(overhead_iterations, log_size_to_reserve);
};
/**
* @brief Initialises the time keeping reference time.
* @details There is no need to keep a `start_` variable, because
* `desired_` is incremented with every call to the `sleep()`
* method.
*/
inline void begin() {
desired_ = clock_type::now();
now_ = desired_;
if constexpr (EnableLogging) {
actual_log_.push_back(now_);
desired_log_.push_back(desired_);
offsets_log_.emplace_back(0);
}
SPDLOG_LOGGER_TRACE(logger_, "[TimeKeeper] begin: {}",
desired_.time_since_epoch().count());
};
inline auto now() const { return now_; }
/**
* @brief Updates the offset used to compensate for the mismatch between
* the desired and the actual time point.
*/
auto update_offset() {
now_ = clock_type::now();
offset_ = now_ - desired_;
SPDLOG_LOGGER_TRACE(logger_,
"[TimeKeeper] now: {}, desired: {}, offset: {}",
now_.time_since_epoch().count(),
desired_.time_since_epoch().count(), offset_.count());
/* Push the actual, desired, and the resulting offset duration. */
if constexpr (EnableLogging) {
actual_log_.push_back(now_);
desired_log_.push_back(desired_);
offsets_log_.push_back(offset_);
}
if constexpr (details::TIME_KEEPER_OPTIONS.offset_returns) {
return std::array<reporting_granularity, 3>{
std::chrono::duration_cast<reporting_granularity>(
now_.time_since_epoch()),
std::chrono::duration_cast<reporting_granularity>(
desired_.time_since_epoch()),
std::chrono::duration_cast<reporting_granularity>(offset_)};
}
};
/**
* @brief Sleeps for the specified duration, taking account of the
* current offset.
* @details Uses the sleep function provided in the time keeper
* constructor.
*
* @param[in] duration The desired sleep duration
*/
inline void sleep(chrono_granularity duration) {
desired_ += duration;
/* Provide a lower limit for the desired sleep duration passed to the
* `sleep_for` functions. */
auto sleep_time = std::max((duration * minimum_percentage_ / 100),
duration - offset_ - clock_overhead_);
SPDLOG_LOGGER_TRACE(logger_, "[TimeKeeper] will sleep for {}.",
sleep_time.count());
/* Call the respective sleep function based on the chosen threading model.
*/
sleep_function_(sleep_time);
}
/**
* @brief Invokes a callable object repeatedly with a constant period,
* until some predicate is satisfied.
*
* @param[in] period The period at which the function is called
* @param[in] predicate A function returning true if continuing, false
* otherwise
* @param[in] callable A callable object
* @param[in] args Arguments to the callable object, optional
* (`sizeof...(args)` can be zero)
*
* @tparam Callable A callable type
* @tparam Args Argument types to the callable object
*/
template <typename Callable, typename... Args>
void run_every(chrono_granularity period,
std::function<bool(void)>&& predicate, Callable&& callable,
Args&&... args) {
begin();
while (predicate()) {
callable(args...);
sleep(period);
update_offset();
}
};
/**
* @brief Dumps the logged actual, desired, and offset durations.
*
* @return A vector of the durations arranged in a fixed-size array.
*/
std::vector<std::array<reporting_granularity, 3>> dump_log() {
offsets_log_.shrink_to_fit();
actual_log_.shrink_to_fit();
desired_log_.shrink_to_fit();
auto size = offsets_log_.size();
std::vector<reporting_granularity> offsets_report(size);
std::vector<reporting_granularity> actual_report(size);
std::vector<reporting_granularity> desired_report(size);
/* Cast the offset durations into the chosen reporting time granularity. */
std::transform(
offsets_log_.begin(), offsets_log_.end(), offsets_report.begin(),
[](auto log_item) {
return std::chrono::duration_cast<reporting_granularity>(log_item);
});
/* Actual and desired values are of type time_point, `time_since_epoch()`
* 'converts' them into durations.
*
* Durations are casted into the chosen reporting time granularity. */
std::transform(actual_log_.begin(), actual_log_.end(),
actual_report.begin(), [](auto log_item) {
return std::chrono::duration_cast<reporting_granularity>(
log_item.time_since_epoch());
});
std::transform(desired_log_.begin(), desired_log_.end(),
desired_report.begin(), [](auto log_item) {
return std::chrono::duration_cast<reporting_granularity>(
log_item.time_since_epoch());
});
std::vector<std::array<reporting_granularity, 3>> output(size);
for (size_t i{0}; i < size; ++i) {
output.at(i) = {actual_report.at(i), desired_report.at(i),
offsets_report.at(i)};
}
return std::move(output);
};
/**
* @brief Calculates the mean and standard deviation of calculated
* offsets.
*
* @return A string with formatted values using the chosen reporting
* granularity.
*/
auto offset_statistics() {
if constexpr (EnableLogging) {
offsets_log_.shrink_to_fit();
auto [offset_mean, offset_std_dev] =
exot::utilities::details::chrono_statistics<chrono_granularity,
reporting_granularity>(
offsets_log_);
return fmt::format("µ={0:.2f}{2}, σ={1:.2f}{3}",
static_cast<double>(offset_mean.count()),
static_cast<double>(offset_std_dev.count()),
exot::utilities::duration_unit(offset_mean),
exot::utilities::duration_unit(offset_std_dev));
} else {
return "";
}
};
/**
* @brief Calculates the mean and deviation of differences between actual
* and desired sleep durations, essentially an alias of
* `offset_statistics()`.
*
* @return A string with formatted values using the chosen reporting
* granularity.
*/
auto differential_statistics() {
if constexpr (EnableLogging) {
actual_log_.shrink_to_fit();
desired_log_.shrink_to_fit();
std::vector<chrono_granularity> differences(actual_log_.size());
std::transform(actual_log_.begin(), actual_log_.end(),
desired_log_.begin(), differences.begin(),
[](const auto& actual, const auto& desired) {
return (actual - desired);
});
auto [diff_mean, diff_std_dev] =
exot::utilities::details::chrono_statistics<chrono_granularity,
reporting_granularity>(
differences);
return fmt::format("µ={0:.2f}{2}, σ={1:.2f}{3}",
static_cast<double>(diff_mean.count()),
static_cast<double>(diff_std_dev.count()),
exot::utilities::duration_unit(diff_mean),
exot::utilities::duration_unit(diff_std_dev));
} else {
return "";
}
};
/**
* @brief Calculates the mean and standard deviation of the intervals
* between the consecutive actual time points.
*
* @return A string with formatted values using the chosen reporting
* granularity.
*/
auto interval_statistics() {
if constexpr (EnableLogging) {
actual_log_.shrink_to_fit();
std::vector<chrono_granularity> intervals(actual_log_.size() - 1);
for (size_t i{0}; i < intervals.size(); ++i) {
intervals.at(i) = std::chrono::duration_cast<chrono_granularity>(
actual_log_.at(i + 1) - actual_log_.at(i));
}
auto [diff_mean, diff_std_dev] =
exot::utilities::details::chrono_statistics<chrono_granularity,
reporting_granularity>(
intervals);
return fmt::format("µ={0:.2f}{2}, σ={1:.2f}{3}",
static_cast<double>(diff_mean.count()),
static_cast<double>(diff_std_dev.count()),
exot::utilities::duration_unit(diff_mean),
exot::utilities::duration_unit(diff_std_dev));
} else {
return "";
}
};
private:
typename clock_type::time_point desired_;
typename clock_type::time_point now_;
typename chrono_granularity::rep minimum_percentage_;
chrono_granularity offset_{0};
chrono_granularity clock_overhead_;
std::vector<chrono_granularity> offsets_log_;
std::vector<typename clock_type::time_point> actual_log_;
std::vector<typename clock_type::time_point> desired_log_;
std::shared_ptr<spdlog::logger> logger_;
sleep_func_type sleep_function_;
/**
* @brief Bootstraps the time keeper with overhead calculation and log
* reservation
*
* @param[in] overhead_iterations The number of iterations for overhead
* calculation
* @param[in] log_size_to_reserve The log size to reserve
*/
void bootstrap(unsigned int overhead_iterations,
unsigned int log_size_to_reserve) {
auto ovh = exot::utilities::details::get_overhead<
clock_type, exot::utilities::details::timing_overhead>();
clock_overhead_ = ovh(overhead_iterations);
if constexpr (EnableLogging) {
offsets_log_.reserve(log_size_to_reserve);
actual_log_.reserve(log_size_to_reserve);
desired_log_.reserve(log_size_to_reserve);
}
};
}; // namespace exot::utilities
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
/**
* @brief Wrapper for POSIX nanosleep that uses chrono duration
*
* @param[in] duration The sleep duration
*
* @tparam Rep Underlying type used to represent the chrono duration
* @tparam Period The ratio of the chrono duration
*
* @return Same return value as POSIX nanosleep
*/
template <typename Rep, typename Period>
static inline int nanosleep(
const std::chrono::duration<Rep, Period>& duration) {
using std::chrono::nanoseconds;
using std::chrono::seconds;
struct timespec sleep {
std::chrono::duration_cast<seconds>(duration).count(),
std::chrono::duration_cast<nanoseconds>(duration % seconds{1}).count()
};
return ::nanosleep(&sleep, nullptr);
}
#endif
/**
* @brief Busy sleep function, continuously checking if time has elapsed
*
* @param[in] duration The sleep duration
*
* @tparam Rep Underlying type used to represent the chrono duration
* @tparam Period The ratio of the chrono duration
*/
template <typename Rep, typename Period, bool Yield = true>
static inline void busysleep(
const std::chrono::duration<Rep, Period>& duration) {
auto start = std::chrono::steady_clock::now();
while (std::chrono::steady_clock::now() < start + duration) {
if constexpr (Yield) std::this_thread::yield();
}
}
/**
* @brief Gets the UTC time as a C time struct
*
* @return The UTC time.
*/
static std::tm get_utc_time() {
using clock = std::chrono::system_clock;
auto time = clock::to_time_t(clock::now());
return *std::gmtime(&time);
}
/**
* @brief Gets the local time as a C time struct
*
* @return The local time.
*/
static std::tm get_local_time() {
using clock = std::chrono::system_clock;
auto time = clock::to_time_t(clock::now());
return *std::localtime(&time);
}
} // namespace exot::utilities
<file_sep>/include/exot/components/function_nodes.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/function_nodes.h
* @author <NAME>
* @brief Convienient process network nodes wrapping a single callable
* object.
*/
#pragma once
#include <chrono> // for durations
#include <exot/framework/all.h> // for framework support
namespace exot::components {
/**
* All function_* nodes repeatedly run a function consuming and/or producing a
* token, until the global state is stopped.
*
* Functions use `try_{read,write}_for` interface methods to protect against
* potential deadlocks.
*/
using namespace exot;
/**
* @brief A convienience class for declaring nodes that repeatedly run a
* function consuming a token
*
* @tparam InputToken Input token type
*/
template <typename InputToken>
class function_consumer : public framework::IProcess,
public framework::Consumer<InputToken> {
public:
using node_type = framework::Consumer<InputToken>;
using token_type = typename node_type::interface_type::value_type;
using work_type = std::function<void(token_type)>;
using node_type::in_;
/**
* The constructor takes a callable typy with signature void(token).
*/
function_consumer() = delete;
function_consumer(work_type&& work) : work_{std::forward<work_type>(work)} {};
void process() override {
token_type token;
while (!global_state_->is_stopped()) {
if (in_.try_read_for(token, std::chrono::seconds{1})) { work_(token); }
}
}
private:
work_type work_;
};
/**
* @brief A convienience class for declaring nodes that repeatedly run a
* function producing a token
*
* @tparam Output Output token type
*/
template <typename OutputToken>
class function_producer : public framework::IProcess,
public framework::Producer<OutputToken> {
public:
using node_type = framework::Producer<OutputToken>;
using token_type = typename node_type::interface_type::value_type;
using work_type = std::function<token_type(void)>;
using node_type::out_;
/**
* The constructor takes a callable typy with signature token(void).
*/
function_producer() = delete;
function_producer(work_type&& work) : work_{std::forward<work_type>(work)} {};
void process() override {
token_type token;
while (!global_state_->is_stopped()) {
token = work_();
while (!out_.try_write_for(token, std::chrono::seconds{1}) &&
!global_state_->is_stopped()) {};
}
}
private:
work_type work_;
};
/**
* @brief A convienience class for declaring nodes that repeatedly run a
* function that first consumes a token, and then produces a token
*
* @tparam InputToken Input token type
* @tparam OutputToken Output token type
*/
template <typename InputToken, typename OutputToken>
class function_processor
: public framework::IProcess,
public framework::Processor<InputToken, OutputToken> {
public:
using node_type = framework::Processor<InputToken, OutputToken>;
using input_token_type =
typename node_type::consumer_type::interface_type::value_type;
using output_token_type =
typename node_type::producer_type::interface_type::value_type;
using work_type = std::function<output_token_type(input_token_type)>;
using node_type::in_;
using node_type::out_;
/**
* The constructor takes a callable typy with signature
* output_token(input_token).
*/
function_processor() = delete;
function_processor(work_type&& work)
: work_{std::forward<work_type>(work)} {};
void process() override {
input_token_type input_token;
output_token_type output_token;
while (!global_state_->is_stopped()) {
if (in_.try_read_for(input_token, std::chrono::seconds{1})) {
output_token = work_(input_token);
while (!out_.try_write_for(output_token, std::chrono::seconds{1}) &&
!global_state_->is_stopped()) {};
}
}
}
private:
work_type work_;
};
} // namespace exot::components
<file_sep>/include/exot/utilities/ostream.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/ostream.h
* @author <NAME>
* @brief Output stream overloads for writing complex data structures:
* iterables and tuples.
*
* @todo Provide fmt-specific template specifications of the contained
* ostream-overloads for performance gains.
*/
#pragma once
#include <chrono> // for duration
#include <type_traits> // for enable_if etc.
#include <fmt/format.h>
#include <exot/utilities/formatting.h> // for Separators
#include <exot/utilities/helpers.h> // for const_for
/**
* These have to be registered in the global namespace in order to benefit from
* fmtlib's ostream formatting.
*/
namespace std {
/**
* @brief Outputs iterable types to std::basic_ostream
*
* @param ostream The output stream
* @param[in] range The iterable range
*
* @tparam T Type of the iterable range
* @tparam CharT Character type used by basic_ostream
* @tparam CharTraitsT Character traits used by basic_ostream
*
* @return The output stream
*/
template <typename T, typename CharT, typename CharTraitsT>
typename std::enable_if<exot::utilities::is_iterable<T>::value &&
!exot::utilities::is_const_iterable<T>::value,
std::basic_ostream<CharT, CharTraitsT>&>::type&
operator<<(std::basic_ostream<CharT, CharTraitsT>& ostream, const T& range) {
exot::utilities::details::Separators<CharT, T> formatting_chars;
if (formatting_chars.prefix != '\0') ostream << formatting_chars.prefix;
for (typename T::iterator it = range.begin(); it != range.end(); ++it) {
if (it == range.begin()) {
if (std::is_floating_point_v<typename T::value_type>) {
ostream << fmt::format("{:.4f}", *it);
} else {
ostream << *it;
}
} else {
ostream << formatting_chars.delimeter;
if (std::is_floating_point_v<typename T::value_type>) {
ostream << fmt::format("{:.4f}", *it);
} else {
ostream << *it;
}
}
}
if (formatting_chars.postfix != '\0') ostream << formatting_chars.postfix;
return ostream;
};
/**
* @brief Outputs const iterable types to std::basic_ostream
* @details If the range type is const iterable, prefer this overload.
*
* @param ostream The output stream
* @param[in] range The const iterable range
*
* @tparam T Type of the const iterable range
* @tparam CharT Character type used by basic_ostream
* @tparam CharTraitsT Character traits used by basic_ostream
*
* @return The output stream
*/
template <typename T, typename CharT, typename CharTraitsT>
typename std::enable_if<exot::utilities::is_const_iterable<T>::value,
std::basic_ostream<CharT, CharTraitsT>&>::type&
operator<<(std::basic_ostream<CharT, CharTraitsT>& ostream, const T& range) {
exot::utilities::details::Separators<CharT, T> formatting_chars;
if (formatting_chars.prefix != '\0') ostream << formatting_chars.prefix;
for (typename T::const_iterator it = range.begin(); it != range.end(); ++it) {
if (it == range.begin()) {
if (std::is_floating_point_v<typename T::value_type>) {
ostream << fmt::format("{:.4f}", *it);
} else {
ostream << *it;
}
} else {
ostream << formatting_chars.delimeter;
if (std::is_floating_point_v<typename T::value_type>) {
ostream << fmt::format("{:.4f}", *it);
} else {
ostream << *it;
}
}
}
if (formatting_chars.postfix != '\0') ostream << formatting_chars.postfix;
return ostream;
};
/**
* @brief Outputs tuples to std::basic_ostream
* @details Uses a compile time for loop to iterate over tuple elements.
*
* @param ostream The output stream
* @param[in] tuple The tuple
*
* @tparam T Type of the tuple
* @tparam CharT Character type used by basic_ostream
* @tparam CharTraitsT Character traits used by basic_ostream
*
* @return The output stream
*/
template <typename T, typename CharT, typename CharTraitsT>
typename std::enable_if<exot::utilities::is_tuple<T>::value,
std::basic_ostream<CharT, CharTraitsT>>::type&
operator<<(std::basic_ostream<CharT, CharTraitsT>& ostream, const T& tuple) {
exot::utilities::details::Separators<CharT, T> formatting_chars;
if (formatting_chars.prefix != '\0') ostream << formatting_chars.prefix;
/* `const_for` generates a compile-time const index sequence which can be used
* to access tuple elements via std::get
*/
exot::utilities::const_for<0, std::tuple_size_v<T>>([&](auto I) {
if constexpr (I != 0) { ostream << formatting_chars.delimeter; }
ostream << std::get<I>(tuple);
});
if (formatting_chars.postfix != '\0') ostream << formatting_chars.postfix;
return ostream;
};
/**
* @brief Outputs durations to std::basic_ostream
* @details Simply calls the `count()` method of the duration object.
*
* @param ostream The output stream
* @param[in] duration The chrono duration object
*
* @tparam CharT Character type used by basic_ostream
* @tparam CharTraitsT Character traits used by basic_ostream
* @tparam Rep Underlying type used in the chrono duration
* @tparam Period Ratio used in the chrono duration (e.g. ns)
*
* @return The output stream
*/
template <typename CharT, typename CharTraitsT, typename Rep, typename Period>
std::basic_ostream<CharT, CharTraitsT>& operator<<(
std::basic_ostream<CharT, CharTraitsT>& ostream,
const std::chrono::duration<Rep, Period>& duration) {
ostream << duration.count();
return ostream;
};
} // namespace std
<file_sep>/include/exot/meters/cache_er.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/cache_er.h
* @author <NAME>
* @brief Evict + Reload meter, measures access time and evicts by reading
* memory mapped to the same set+slice.
*
* @note Features in [1], used on platforms which do not have cache flush
* instructions.
*
* [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>,
* “ARMageddon - Cache Attacks on Mobile Devices.,” 23rd USENIX
* Security Symposium, 2016.
*
* @todo This meter should be made cross-platform. At the moment (2019/04)
* support for cache information and address decomposing is only for
* x86.
*/
#pragma once
#include <cstdint>
#include <map>
#include <thread>
#include <utility>
#include <exot/meters/base_shared_memory.h>
#include <exot/primitives/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/eviction.h>
#include <exot/utilities/helpers.h>
#include <exot/utilities/literals.h>
#include <exot/utilities/timing.h>
#if defined(__x86_64__)
#include <exot/primitives/tsc.h>
#else
#include <exot/utilities/timing_source.h>
#endif
namespace exot::modules {
struct cache_er : public meter_shared_memory_base {
using map_type = std::map<void*, void*>;
using evicter_type = exot::utilities::Evicter;
const char* name() const override { return "cache_er"; }
struct settings : public exot::utilities::configurable<settings>,
public exot::modules::meter_shared_memory_base::settings {
/* Since settings inherits from base's settings, we need to provide a way
* to resolve to the right functions. The `set_json` and `configure` need to
* work on current structure's data as well as the derived one. The same
* pattern is used, for example, in the `meter_host`. */
using base_t = exot::utilities::configurable<settings>;
/* Eviction strategy settings. */
std::size_t addresses_per_loop = 2;
std::size_t accesses_per_loop = 2;
std::size_t overlap_parameter = 1;
const char* name() const { return "cache"; }
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
exot::modules::meter_shared_memory_base::settings::set_json(root);
}
auto describe() {
return base_t::describe() +
exot::modules::meter_shared_memory_base::settings::describe();
}
void configure() {
base_t::bind_and_describe_data(
"addresses_per_loop", addresses_per_loop,
"number of addresses accessed in an eviction "
"loop |uint|, default: 2");
base_t::bind_and_describe_data(
"accesses_per_loop", accesses_per_loop,
"number of accesses to each address |uint|, default: 2");
base_t::bind_and_describe_data(
"overlap_parameter", overlap_parameter,
"the eviction overlap parameter |uint|, default: 1");
exot::modules::meter_shared_memory_base::settings::configure();
}
};
explicit cache_er(settings& conf)
: meter_shared_memory_base(conf), lconf_{conf} {
using namespace exot::utilities;
/* Initialise the evicter. */
evicter_ = std::make_unique<evicter_type>(lconf_.addresses_per_loop,
lconf_.accesses_per_loop,
lconf_.overlap_parameter);
const auto slice_count =
#if defined(__x86_64__)
static_cast<unsigned>(std::thread::hardware_concurrency() / 2);
#else
1;
#endif
/* To get all set-slice pairs, we need at least 'line size' * 'number of
* sets' * 'number of slices' addresses. Therefore, to get at least 2
* of each set-slice pairs, we need twice that amount.
*
* For example, on a system with 64 bytes per line, 8192 sets, and 4 slices,
* we would need 0x400000 (64 * 8192 * 4 * 2) bytes of memory. */
const auto minimum_mem_size = llc_->coherency_line_size().value() *
llc_->number_of_sets().value() *
(slice_count * 2);
/* Save the line length for use with the evicter. */
line_length_ = llc_->coherency_line_size().value();
/* Verify if sufficient amout of memory has been mapped. */
if (mapping_->get_length() < minimum_mem_size) {
debug_log_->critical(
"[meter] to build an eviction set, a huge pages mapping of at least "
"{:#x} bytes is required.",
minimum_mem_size);
throw std::logic_error("Insufficient mapping size");
}
/* Loop through target addresses and find matching eviction sets. A matching
* set has the same set and slice indeces, but different address. */
for (auto i = 0; i < address_set_info_.size(); ++i) {
auto [target_addr, target_set, target_slice] = address_set_info_[i];
debug_log_->debug(
"[meter] attempting to find eviction candidate address for target "
"address {}, set: {:#x}, slice: {:#b}",
target_addr, target_set, target_slice);
/* First candidate is at least 'number of sets' * 'line size' away, i.e.
* the first address with the same set number as the target. The
* assumption here is that the mapped memory contains contiguous addresses
* and is sufficiently large. This method would surely not work otherwise;
* however, this approach greatly reduces the complexity of creating an
* eviction set. */
auto step =
llc_->coherency_line_size().value() * llc_->number_of_sets().value();
auto traversed = step; // hold the total amout of traversed memory
auto candidate = reinterpret_cast<std::uintptr_t>(target_addr) + step;
for (auto i = 0;; ++i) {
auto candidate_addr = reinterpret_cast<void*>(candidate);
auto candidate_physical_addr = resolver_(candidate_addr);
auto candidate_set = decomposer_->get_set(candidate_physical_addr);
auto candidate_slice =
#if defined(__x86_64__)
exot::primitives::slice_selection_hash(candidate_physical_addr,
slice_count);
#else
-1;
#endif
debug_log_->trace(
"[meter] candidate {} -> address: {}, set: {:#x}, slice: {:#b}", i,
candidate_addr, candidate_set, candidate_slice);
if (candidate_slice == target_slice) {
auto dist = [](auto lhs, auto rhs) {
return lhs > rhs ? lhs - rhs : rhs - lhs;
};
debug_log_->debug(
"[meter] adding address {} ({:#x}) to eviction set "
"(target: {}, distance: {:#x})",
candidate_addr, candidate_physical_addr, target_addr,
dist(candidate_physical_addr, resolver_(target_addr)));
eviction_map_.emplace(target_addr, candidate_addr);
break;
}
candidate += step;
traversed += step;
/* If amount of traversed memory is out of bounds, no eviction address
* was found, and the program will abort. */
if (traversed > mapping_->get_length()) {
debug_log_->critical(
"[meter] could not find eviction address for target: {}",
target_addr);
throw std::logic_error("Could not find required eviction addresses");
}
}
}
}
/**
* @brief Gets the eviction map.
*
* @return The eviction map.
*/
const auto& get_eviction_map() const { return eviction_map_; }
/**
* @brief Gets the eviction address.
*
* @param target The target address
*
* @return The eviction address.
*/
auto get_eviction_address(void* target) { return eviction_map_.at(target); }
/**
* @brief Measures the access time to an address and evicts the set in
* which it is located
*
* @param addr The address
*
* @return The number of cycles to access the address
*/
inline __attribute__((always_inline)) std::uint64_t perform_action_on_address(
void* addr) override {
/* Casting to uint8_t* such that eviction will happen at 1B increments. */
auto* eviction_addr = reinterpret_cast<std::uint8_t*>(eviction_map_[addr]);
#if defined(__x86_64__)
auto _ = exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
exot::primitives::access_read<std::uint8_t>, addr);
#else
auto _ = exot::utilities::default_timing_facility(
exot::primitives::access_read<>, addr);
#endif
SPDLOG_LOGGER_TRACE(debug_log_,
"Evicting address {} using {}B eviction set @{}", addr,
line_length_, fmt::ptr(eviction_addr));
evicter_->read(eviction_addr, line_length_);
return _;
}
private:
settings lconf_; //! local settings, different than parent's conf_
map_type eviction_map_; //! mapping target-addr -> eviction-addr
std::unique_ptr<evicter_type> evicter_; //! evicter as a unique ptr due to
//! the deleted default constructor
std::size_t line_length_;
};
} // namespace exot::modules
<file_sep>/include/exot/primitives/fenced_clock.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/fenced_clock.h
* @author <NAME>
* @brief Wrappers for making clock sources serialised.
*/
#pragma once
#include <atomic>
#include <chrono>
#include <exot/primitives/ordering.h>
#include <exot/utilities/types.h>
#include <exot/primitives/tsc.h>
namespace exot::primitives {
template <typename Clock,
typename = std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
struct plain_clock : public Clock {
using underlying_timing_source = Clock;
};
template <typename Clock,
typename = std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
struct fenced_clock : public Clock {
using underlying_timing_source = Clock;
/**
* @brief Wrapper of Clock's now() function with C++ memory ordering
* instructions
*
* @return The Clock's time point
*/
static inline auto now() {
std::atomic_thread_fence(std::memory_order_acquire);
auto _ = Clock::now();
std::atomic_thread_fence(std::memory_order_release);
return _;
}
};
using fenced_steady_clock = fenced_clock<std::chrono::steady_clock>;
template <typename Clock,
typename = std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
struct __fenced_clock : public Clock {
using underlying_timing_source = Clock;
static inline auto now() {
load_fence();
auto _ = Clock::now();
memory_fence();
return _;
}
};
using __fenced_steady_clock = __fenced_clock<std::chrono::steady_clock>;
template <typename Clock,
typename = std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
struct __strong_fenced_clock : public Clock {
using underlying_timing_source = Clock;
static inline auto now() {
full_fence();
auto _ = Clock::now();
full_fence();
return _;
}
};
using __strong_fenced_steady_clock =
__strong_fenced_clock<std::chrono::steady_clock>;
template <typename Counter,
typename = std::enable_if_t<is_time_stamp_counter_v<Counter>>>
struct plain_tsc : public Counter {
using underlying_timing_source = Counter;
};
template <typename Counter,
typename = std::enable_if_t<is_time_stamp_counter_v<Counter>>>
struct fenced_tsc {
using underlying_timing_source = Counter;
static inline __attribute__((always_inline)) std::uint64_t start() {
std::atomic_thread_fence(std::memory_order_acquire);
auto _ = Counter::start();
std::atomic_thread_fence(std::memory_order_release);
return _;
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::atomic_thread_fence(std::memory_order_acquire);
auto _ = Counter::stop();
std::atomic_thread_fence(std::memory_order_release);
return _;
}
};
template <typename Counter,
typename = std::enable_if_t<is_time_stamp_counter_v<Counter>>>
struct __fenced_tsc {
using underlying_timing_source = Counter;
static inline __attribute__((always_inline)) std::uint64_t start() {
load_fence();
auto _ = Counter::start();
memory_fence();
return _;
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
load_fence();
auto _ = Counter::stop();
memory_fence();
return _;
}
};
template <typename Counter,
typename = std::enable_if_t<is_time_stamp_counter_v<Counter>>>
struct __strong_fenced_tsc {
using underlying_timing_source = Counter;
static inline __attribute__((always_inline)) std::uint64_t start() {
full_fence();
auto _ = Counter::start();
full_fence();
return _;
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
full_fence();
auto _ = Counter::stop();
full_fence();
return _;
}
};
} // namespace exot::primitives
<file_sep>/src/utilities/platform_id.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/platform_id.cpp
* @author <NAME>
* @brief Implementation of the platform identifying functions from @ref
* platform_id.h.
*/
#include <exot/utilities/platform_id.h>
#include <algorithm>
#include <fstream>
#include <limits>
#include <stdexcept>
#include <thread>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <exot/utilities/bits.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/formatting.h>
#include <exot/utilities/ostream.h>
/* Local helpers */
namespace {
/**
* @brief Gets the key from key-value pairs found in cpuinfo
*
* @param[in] line The line containing the key-value pair
*
* @return The key.
*/
std::string get_key(const std::string& line) {
if (!line.empty()) {
auto split = exot::utilities::split_string(line, ':');
if (split.size() >= 1) { return exot::utilities::trim_string(split[0]); }
}
return std::string{};
}
/**
* @brief Gets the value from key-value pairs found in cpuinfo
*
* @param[in] line The line containing the key-value pair
*
* @return The value.
*/
std::string get_value(const std::string& line) {
std::string value;
if (!line.empty()) {
auto split = exot::utilities::split_string(line, ':');
/* If the split size is 1 or less, the line in /proc/cpuinfo did not contain
* a key-value pair. */
if (split.size() > 1) { value = exot::utilities::trim_string(split[1]); }
}
return value;
}
} // namespace
namespace exot::utilities {
std::optional<std::string> get_kernel_version() {
return get_long_string_value_from_file("/proc/version");
}
std::vector<std::string> get_cpuinfo_keys() {
std::vector<std::string> output;
const auto path = "/proc/cpuinfo";
std::ifstream file(path);
if (is_readable(path)) {
for (std::string line; std::getline(file, line);) {
if (auto key = get_key(line); !key.empty() && !line.empty())
output.push_back(key);
}
/* Deduplicate the results. */
std::sort(output.begin(), output.end());
output.erase(std::unique(output.begin(), output.end()), output.end());
}
return output;
}
std::vector<std::map<std::string, std::string>>
get_complete_cpuinfo_as_map_array() {
std::vector<std::map<std::string, std::string>> output;
const auto path = "/proc/cpuinfo";
std::ifstream file(path);
if (is_readable(path)) {
std::map<std::string, std::string> map;
for (std::string line; std::getline(file, line);) {
/* Empty lines in cpuinfo separate values for individual cpus. */
if (line.empty()) {
output.push_back(map); // Push the current map to the output vector.
map.clear(); // Clear the contents of the current map.
} else {
map.insert({get_key(line), get_value(line)});
}
}
}
return output;
}
std::optional<std::map<std::string, std::string>> get_cpuinfo_as_map(
unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
/* Static to make subsequent accesses faster, the function is only meant for
* the invariant parts of cpuinfo. */
static auto map = get_complete_cpuinfo_as_map_array();
static auto size = map.size();
if (size == 1) {
return map.at(0);
} else if (size != get_cpu_count()) {
/* @todo Handling cases, where the entries in cpuinfo are more/less than the
* cores available, requires additional parsing. */
return {};
} else {
return map.at(cpu);
}
}
std::optional<std::string> get_cpuinfo_value(unsigned cpu,
const std::string& key) {
auto map = get_cpuinfo_as_map(cpu);
if (!map) return {};
if (map.value().empty()) return {};
std::string value;
try {
value = map.value().at(key);
} catch (const std::out_of_range& e) {
/* @todo Somehow the arm cross-compiler does not respect this try-block, and
* throws an instance of std::out_of_range when accessing a key that does
* not exist. */
return {};
}
return value;
}
unsigned get_cpu_count() {
static auto count =
static_cast<unsigned>(std::thread::hardware_concurrency());
return count;
}
unsigned get_thread_count() {
static auto count =
static_cast<unsigned>(std::thread::hardware_concurrency());
return count;
}
unsigned get_core_count() {
std::vector<unsigned> thread_siblings;
for (unsigned idx{0}; idx < get_cpu_count(); ++idx) {
if (auto siblings_count = get_thread_siblings_count(idx))
thread_siblings.push_back(siblings_count.value());
}
/* The core count will only be meaningful if all cpus have the same number of
* thread siblings. To the best of my knowledge hyperthreading only considers
* 2 threads per core. */
if (std::equal(thread_siblings.begin(), thread_siblings.end(),
thread_siblings.begin())) {
/* The assumption is that the values in thread_siblings are powers of 2. */
return thread_siblings.size() / thread_siblings.at(0);
} else {
return 0;
}
}
unsigned get_socket_count() {
std::vector<unsigned> package_ids;
for (unsigned idx{0}; idx < get_cpu_count(); ++idx) {
if (auto id = get_physical_package_id(idx))
package_ids.push_back(id.value());
}
/* Deduplicate the vector with package ids, the number of unique ids should
* reflect the socket count on the machine. In the case of ARM big.LITTLE
* chips the two processors will be identified as distinct sockets. */
std::sort(package_ids.begin(), package_ids.end());
package_ids.erase(std::unique(package_ids.begin(), package_ids.end()),
package_ids.end());
return package_ids.size();
}
unsigned get_thread_per_core() {
/* The assumption is that these values will produce integer results. */
return get_thread_count() / get_core_count();
}
unsigned get_core_per_socket() {
/* The assumption is that these values will produce integer results. */
return get_core_count() / get_socket_count();
}
const char* get_target_architecture() noexcept {
#if defined(__i386__) || defined(__i386)
return "x86";
#elif defined(__x86_64__)
return "x86_64";
#elif defined(__ia64__) || defined(__itanium__)
return "IA-64";
#elif defined(__sparc)
return "SPARC";
#elif (defined(__arm64__) || defined(__aarch64__))
return "aarch64";
#elif defined(__arm__)
return "arm";
#else
return "unknown";
#endif
}
std::optional<std::string> get_cpu_vendor(unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
#if defined(__x86_64__)
return get_cpuinfo_value(cpu, "vendor_id");
#elif defined(__arm__) || defined(__aarch64__)
/* On ARM chips the vendor will be decoded from a value stored in
* "CPU implementer". */
auto implementer = get_cpuinfo_value(cpu, "CPU implementer");
if (implementer) {
switch (read_hex_value(implementer.value())) {
// clang-format off
case 0x41: return "ARM";
case 0x42: return "Broadcom";
case 0x43: return "Cavium";
case 0x44: return "DEC";
case 0x4e: return "Nvidia";
case 0x50: return "APM";
case 0x51: return "Qualcomm";
case 0x53: return "Samsung";
case 0x56: return "Marvell";
case 0x66: return "Faraday";
case 0x69: return "Intel";
default: return {}; // clang-format on
}
}
#endif
return {};
}
std::optional<std::string> get_cpu_model(unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
/* The way in which the cpu model is reported will differ depending on the
* architecture. */
#if defined(__x86_64__)
return fmt::format(
"name: \"{}\", vendor: \"{}\", family: {}, model: {}, stepping: {}",
get_cpuinfo_value(cpu, "model name").value_or(""),
get_cpu_vendor(cpu).value_or(""),
get_cpuinfo_value(cpu, "cpu family").value_or(""),
get_cpuinfo_value(cpu, "model").value_or(""),
get_cpuinfo_value(cpu, "stepping").value_or(""));
#elif defined(__arm__) || defined(__aarch64__)
auto get_part = [](const std::string& str) -> std::optional<std::string> {
if (str.empty()) {
return {};
} else {
/* For the most common ARM implementer the hexadecimal value will be
* transformed into a more meaningful name. */
switch (read_hex_value(str)) {
// clang-format off
case 0xc05: return "Cortex-A5";
case 0xc07: return "Cortex-A7";
case 0xc08: return "Cortex-A8";
case 0xc09: return "Cortex-A9";
case 0xc0d: return "Cortex-A17";
case 0xc0f: return "Cortex-A15";
case 0xc0e: return "Cortex-A17";
case 0xc14: return "Cortex-R4";
case 0xc15: return "Cortex-R5";
case 0xc17: return "Cortex-R7";
case 0xc18: return "Cortex-R8";
case 0xc20: return "Cortex-M0";
case 0xc21: return "Cortex-M1";
case 0xc23: return "Cortex-M3";
case 0xc24: return "Cortex-M4";
case 0xc27: return "Cortex-M7";
case 0xc60: return "Cortex-M0+";
case 0xd01: return "Cortex-A32";
case 0xd03: return "Cortex-A53";
case 0xd04: return "Cortex-A35";
case 0xd05: return "Cortex-A55";
case 0xd07: return "Cortex-A57";
case 0xd08: return "Cortex-A72";
case 0xd09: return "Cortex-A73";
case 0xd0a: return "Cortex-A75";
case 0xd13: return "Cortex-R52";
case 0xd20: return "Cortex-M23";
case 0xd21: return "Cortex-M33";
default: return str; // clang-format on
}
}
};
return fmt::format(
"arch: {}, vendor: \"{}\", variant: {}, part: \"{}\", revision: {}",
get_cpuinfo_value(cpu, "CPU architecture").value_or(""),
get_cpu_vendor(cpu).value_or(""),
get_cpuinfo_value(cpu, "CPU variant").value_or(""),
get_part(get_cpuinfo_value(cpu, "CPU part").value_or("")).value_or(""),
get_cpuinfo_value(cpu, "CPU revision").value_or(""));
#endif
return {};
}
std::optional<std::vector<std::string>> get_unique_cpu_models() {
std::vector<std::string> output;
std::vector<unsigned> cores;
auto previous = get_cpu_model(0);
/* Loop through cpus, keep track of which cores share the same model, push
* when a different model appears. */
for (unsigned idx{0}; idx < get_cpu_count(); ++idx) {
auto current = get_cpu_model(idx);
if (current && previous) {
if (current.value() != previous.value()) {
output.push_back(
fmt::format("cpus: [{}], {}", cores, previous.value()));
cores.clear();
}
cores.push_back(idx);
previous = current;
} else {
return {};
}
}
output.push_back(fmt::format("cpus: [{}], {}", cores, previous.value()));
return output;
}
std::optional<std::string> get_cpu_flags(unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
std::optional<std::string> flags;
/* @todo Although the function get_cpuinfo_value will return a nullopt for a
* non-existent key, for some reason compiling for ARM will produce an
* out_of_range exception, even though there is a try-block in the relevant
* part of the code. */
#if defined(__x86_64__)
flags = get_cpuinfo_value(cpu, "flags");
#elif defined(__arm__) || defined(__aarch64__)
flags = get_cpuinfo_value(cpu, "Features");
#endif
return flags;
}
std::optional<std::vector<std::string>> get_cpu_flags_array(unsigned cpu) {
if (auto flags = get_cpu_flags(cpu); flags.has_value()) {
return split_string(flags.value(), ' ');
} else {
return {};
}
}
std::optional<std::string> get_scaling_governor(unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
return get_string_value_from_file(fmt::format(
"/sys/devices/system/cpu/cpu{}/cpufreq/scaling_governor", cpu));
}
std::optional<unsigned long> get_min_cpu_frequency(unsigned cpu) {
if (cpu >= get_cpu_count()) { return {}; }
if (auto frequency = get_string_value_from_file(fmt::format(
"/sys/devices/system/cpu/cpu{}/cpufreq/cpuinfo_min_freq", cpu))) {
return std::stoul(frequency.value()) * 1000ul;
} else {
return {};
}
}
std::optional<unsigned long> get_max_cpu_frequency(unsigned cpu) {
if (!is_cpu_online(cpu) || cpu >= get_cpu_count()) { return {}; }
if (auto frequency = get_string_value_from_file(fmt::format(
"/sys/devices/system/cpu/cpu{}/cpufreq/cpuinfo_max_freq", cpu))) {
return std::stoul(frequency.value()) * 1000ul;
} else {
return {};
}
}
std::optional<std::array<unsigned long, 2>> get_cpu_frequencies(unsigned cpu) {
if (!is_cpu_online(cpu) || cpu >= get_cpu_count()) { return std::nullopt; }
auto min = get_min_cpu_frequency(cpu);
auto max = get_max_cpu_frequency(cpu);
if (!(min && max)) return std::nullopt;
return {{min.value(), max.value()}};
}
std::string get_online_cpus() {
return get_string_value_from_file("/sys/devices/system/cpu/online")
.value_or("");
}
std::string get_offline_cpus() {
return get_string_value_from_file("/sys/devices/system/cpu/offline")
.value_or("");
}
std::string get_possible_cpus() {
return get_string_value_from_file("/sys/devices/system/cpu/possible")
.value_or("");
}
std::vector<bool> get_online_cpus_array() {
std::vector<bool> output;
for (unsigned idx{0}; idx < get_cpu_count(); ++idx) {
try {
output.push_back(is_cpu_online(idx));
} catch (const std::exception& e) {
/* In case an unsuccessful access to cpu/online fds, clear the output and
* return an empty vector. This should be enough of an indication that the
* operation was not completed. */
output.clear();
break;
}
}
return output;
}
bool is_cpu_online(unsigned cpu) {
if (cpu >= get_cpu_count()) { return false; }
auto online_fd = fmt::format("/sys/devices/system/cpu/cpu{}/online", cpu);
auto readable = is_readable(online_fd);
/* On some machines, especially Intel, cpu0 does not have an /online fd in
* sysfs. Therefore we need to parse the complete online description to
* determine if cpu0 is online. */
if (!readable && cpu == 0) {
auto tmp = get_string_value_from_file("/sys/devices/system/cpu/online");
if (!tmp) {
/* If the fallback fd is still missing, the error is unrecoverable. */
throw std::logic_error("sysfs cpu/online is not accessible");
} else if (tmp.value().empty()) {
/* There should be some value reported by the cpu/online fd. */
throw std::logic_error("sysfs cpu/online string is empty");
} else {
if (tmp.value()[0] == '0') {
return true;
} else {
return false;
}
}
} else if (!readable) {
/* Since out of range errors are taken care of, an inaccessible fd is an
* unrecoverable error. */
throw std::logic_error("sysfs cpu/online is not readable");
} else {
std::ifstream stream{online_fd};
bool tmp;
stream >> tmp;
return tmp;
}
}
std::optional<std::string> get_topology_value(unsigned cpu,
const std::string& key) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
/* Only accept valid keys, some of which might not exist on all machines, in
* particular the book_id, drawer_id, and book_siblings, drawer_siblings. */
if (key == "core_id" || key == "core_siblings" ||
key == "physical_package_id" || key == "thread_siblings" ||
key == "core_siblings_list" || key == "thread_siblings_list" ||
key == "book_id" || key == "drawer_id" || key == "book_siblings" ||
key == "drawer_siblings") {
/* get_string_value_from_file can still return nullopt. */
return get_string_value_from_file(
fmt::format("/sys/devices/system/cpu/cpu{}/topology/{}", cpu, key));
} else {
return {};
}
}
std::optional<unsigned> get_core_id(unsigned cpu) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
if (auto core_id = get_topology_value(cpu, "core_id")) {
return static_cast<unsigned>(std::stoul(core_id.value()));
} else {
return {};
}
}
std::optional<unsigned> get_core_siblings(unsigned cpu) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
if (auto core_siblings = get_topology_value(cpu, "core_siblings")) {
return read_hex_value(split_string(core_siblings.value(), ',').back());
} else {
return {};
}
}
std::optional<std::vector<unsigned>> get_core_siblings_array(unsigned cpu) {
std::vector<unsigned> siblings;
auto core_siblings = get_core_siblings(cpu);
if (!core_siblings) { return std::nullopt; }
auto value = core_siblings.value();
unsigned idx{0};
while (value != 0) {
if (value & 1) { siblings.push_back(static_cast<unsigned>(idx)); }
++idx;
value >>= 1;
}
if (siblings.empty()) {
return std::nullopt;
} else {
return siblings;
}
}
std::optional<unsigned> get_core_siblings_count(unsigned cpu) {
if (auto core_siblings = get_core_siblings(cpu)) {
return hamming_weight(core_siblings.value());
} else {
return {};
}
}
std::optional<unsigned> get_physical_package_id(unsigned cpu) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
if (auto physical_package_id =
get_topology_value(cpu, "physical_package_id")) {
return static_cast<unsigned>(std::stoul(physical_package_id.value()));
} else {
return {};
}
}
std::optional<unsigned> get_thread_siblings(unsigned cpu) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
if (auto thread_siblings = get_topology_value(cpu, "thread_siblings")) {
return read_hex_value(split_string(thread_siblings.value(), ',').back());
} else {
return {};
}
}
std::optional<std::vector<unsigned>> get_thread_siblings_array(unsigned cpu) {
std::vector<unsigned> siblings;
auto thread_siblings = get_thread_siblings(cpu);
if (!thread_siblings) { return std::nullopt; }
auto value = thread_siblings.value();
unsigned idx{0};
while (value != 0) {
if (value & 1) { siblings.push_back(static_cast<unsigned>(idx)); }
++idx;
value >>= 1;
}
if (siblings.empty()) {
return std::nullopt;
} else {
return siblings;
}
}
std::optional<unsigned> get_thread_siblings_count(unsigned cpu) {
/* The values in *_siblings are bitsets, therefore the hamming weight gives
* the total count of 1's in the bitset. */
if (auto thread_siblings = get_thread_siblings(cpu)) {
return hamming_weight(thread_siblings.value());
} else {
return {};
}
}
std::optional<std::map<std::string, std::string>> get_cpu_topology_map(
unsigned cpu) {
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return std::nullopt; }
std::map<std::string, std::string> map;
auto topo_fds = list_directory(
fmt::format("/sys/devices/system/cpu/cpu{}/topology", cpu));
/* Remove the "." and ".." directories from the listing. */
topo_fds.erase(topo_fds.begin(), topo_fds.begin() + 2);
for (decltype(topo_fds)::iterator it = topo_fds.begin(); it != topo_fds.end();
++it) {
std::ifstream stream{*it};
std::string value;
stream >> value;
map.insert({split_string(*it, '/').back(), value});
}
return map;
} // namespace exot::utilities
std::optional<std::string> get_cpu_topology(unsigned cpu) {
std::string description;
if (cpu >= get_cpu_count() || !is_cpu_online(cpu)) { return {}; }
std::vector<std::string> topo_fds;
try {
topo_fds = list_directory(
fmt::format("/sys/devices/system/cpu/cpu{}/topology", cpu));
} catch (const std::exception& e) {
/* Directory not accessible. */
return {};
}
if (topo_fds.empty()) return {};
/* Remove the "." and ".." directories from the listing. */
topo_fds.erase(topo_fds.begin(), topo_fds.begin() + 2);
description = "{ ";
for (decltype(topo_fds)::iterator it = topo_fds.begin(); it != topo_fds.end();
++it) {
std::ifstream stream{*it};
std::string value;
stream >> value;
description +=
it != topo_fds.end() - 1
? fmt::format("{}: {}, ", split_string(*it, '/').back(), value)
: fmt::format("{}: {} }}", split_string(*it, '/').back(), value);
}
return description;
}
std::vector<std::string> get_complete_topology() {
std::string sysfs_dir{"/sys/devices/system/cpu"};
std::string regex{".*/cpu/cpu\\d+"};
std::vector<std::string> descriptions;
auto dirs = grep_directory_r(sysfs_dir, regex);
unsigned idx{0};
for (const auto& dir : dirs) {
try {
descriptions.push_back(fmt::format(
"{{ core: {}, online: {}, topology: {} }}", idx, is_cpu_online(idx),
get_cpu_topology(idx).value_or("{}")));
++idx;
} catch (std::logic_error& e) {
descriptions.clear();
break;
}
}
return descriptions;
}
} // namespace exot::utilities
<file_sep>/cmake/modules/add_fiber_dependency.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file add_fiber_dependency.cmake
# @author <NAME>
# @brief Function to add a boost::fiber dependency to a cmake target.
#
# If EXOT_USE_FIBERS is set during CMake configuration step, link the
# appropriate library, provide include directories, and
# add a compile definition (equivalent to setting a preprocessor value)
# to the selected target.
function(add_fiber_dependency target)
if(${exot_use_fibers})
find_package(Boost 1.67 COMPONENTS fiber REQUIRED)
target_link_libraries(${target} PUBLIC Boost::fiber)
target_include_directories(${target} PUBLIC Boost::fiber)
target_compile_definitions(${target} PUBLIC "EXOT_USE_FIBERS")
endif(${exot_use_fibers})
endfunction()
<file_sep>/src/utilities/logging.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/logging.cpp
* @author <NAME>
* @brief Implementation of the core logging configurator from @ref
* logging.h.
*/
#include <exot/utilities/logging.h>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <type_traits>
#include <vector>
#include <spdlog/async.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/stdout_sinks.h>
#ifdef __ANDROID__
#include <spdlog/sinks/android_sink.h>
#endif
#include <exot/utilities/formatting.h>
#include <exot/utilities/helpers.h>
#include <exot/utilities/ostream.h>
#include <exot/utilities/platform_id.h>
/* TODO: create a macro to reduce conditional statements' depth */
namespace exot::utilities {
void append_to_filename(std::string& file_path, const std::string& to_append) {
using clock = std::chrono::system_clock;
using exot::utilities::join_strings;
using exot::utilities::split_string;
/* Split the file path to get the basename */
auto split_file_path = split_string(file_path, '/');
/* Split the file name and extension */
auto split_file_name = split_string(split_file_path.back(), '.');
auto size = split_file_name.size();
/* Append string to the file */
if (size < 2) {
split_file_path.back() = split_file_name.at(size - 1) + "_" + to_append;
} else {
split_file_path.back() = split_file_name.at(size - 2) + "_" + to_append +
"." + split_file_name.at(size - 1);
}
/* Join the split path back together */
file_path = join_strings(split_file_path, '/');
}
void append_timestamp_to_filename(std::string& file_path) {
using clock = std::chrono::system_clock;
/* Get the current wall clock time and format it to a string*/
auto time = clock::to_time_t(clock::now());
auto timestamp = fmt::format("{:%Y-%m-%d_%H-%M-%S}", *std::localtime(&time));
append_to_filename(file_path, timestamp);
}
Logging::Logging(settings& conf) : conf_{conf} {
/* Remove the "app" and "log" loggers from the registry */
spdlog::drop("app");
spdlog::drop("log");
if (conf_.async) {
if (!is_power_of_2(conf_.async_size))
throw std::invalid_argument(
fmt::format("[{}:{}] async_size has to be non-zero and a power of 2. "
"Value of {} was provided.",
__FUNCTION__, __LINE__, conf_.async_size));
spdlog::init_thread_pool(conf_.async_size, conf_.async_thread_count);
}
/* Application log -------------------------------------------------------- */
if (conf_.app_log_filename.has_value() &&
!conf_.app_log_filename.value().empty()) {
/* If a filename was provided */
if (conf_.append_governor_to_files) {
auto governor = exot::utilities::get_scaling_governor(0);
if (governor) {
append_to_filename(conf_.app_log_filename.value(), governor.value());
}
}
if (conf_.timestamp_files) {
append_timestamp_to_filename(conf_.app_log_filename.value());
}
if (conf_.rotating_logs) {
if (conf_.async) {
spdlog::rotating_logger_st<spdlog::async_factory>(
"app", conf_.app_log_filename.value(), conf_.rotating_logs_size,
conf_.rotating_logs_count);
} else {
spdlog::rotating_logger_st<spdlog::default_factory>(
"app", conf_.app_log_filename.value(), conf_.rotating_logs_size,
conf_.rotating_logs_count);
}
} else {
if (conf_.async) {
spdlog::basic_logger_st<spdlog::async_factory>(
"app", conf_.app_log_filename.value());
} else {
spdlog::basic_logger_st<spdlog::default_factory>(
"app", conf_.app_log_filename.value());
}
}
} else {
/* If no filename was provided */
#if defined(__ANDROID__)
if (conf_.async) {
spdlog::android_logger_st<spdlog::async_factory>("app", "app");
} else {
spdlog::android_logger_st<spdlog::default_factory>("app", "app");
}
#else
if (conf_.async) {
spdlog::stdout_logger_st<spdlog::async_factory>("app");
} else {
spdlog::stdout_logger_st<spdlog::default_factory>("app");
}
#endif
}
/* configure loglevel and pattern */
spdlog::get("app")->set_level(spdlog::level::trace);
spdlog::get("app")->set_pattern("%v");
/* Debug log -------------------------------------------------------------- */
if (conf_.debug_log_filename.has_value() &&
!conf_.debug_log_filename.value().empty()) {
/* If a filename was provided */
if (conf_.append_governor_to_files) {
auto governor = exot::utilities::get_scaling_governor(0);
if (governor) {
append_to_filename(conf_.debug_log_filename.value(), governor.value());
}
}
if (conf_.timestamp_files) {
append_timestamp_to_filename(conf_.debug_log_filename.value());
}
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>(
conf_.debug_log_filename.value()));
#if defined(__ANDROID__)
sinks.push_back(std::make_shared<spdlog::sinks::android_sink_mt>());
#else
sinks.push_back(
std::make_shared<spdlog::sinks::ansicolor_stderr_sink_mt>());
#endif
if (conf_.async) {
spdlog::register_logger(std::make_shared<spdlog::async_logger>(
"log", sinks.begin(), sinks.end(), spdlog::thread_pool(),
spdlog::async_overflow_policy::block));
} else {
spdlog::register_logger(
std::make_shared<spdlog::logger>("log", sinks.begin(), sinks.end()));
}
} else {
/* If no filename was provided */
#if defined(__ANDROID__)
if (conf_.async) {
spdlog::android_logger_mt<spdlog::async_factory>("log", "log");
} else {
spdlog::android_logger_mt<spdlog::default_factory>("log", "log");
}
#else
if (conf_.async) {
spdlog::stderr_color_mt<spdlog::async_factory>("log");
} else {
spdlog::stderr_color_mt<spdlog::default_factory>("log");
}
#endif
}
spdlog::get("log")->set_level(conf_.log_level);
#if !defined(SPDLOG_NO_THREAD_ID)
spdlog::get("log")->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [%t] %v");
#else
spdlog::get("log")->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] %v");
#endif
spdlog::get("log")->flush_on(spdlog::level::err);
spdlog::get("log")->info(
"[Logging] using app logfile: {}, debug logfile: {}",
conf_.app_log_filename.has_value() ? conf_.app_log_filename.value()
: "none",
conf_.debug_log_filename.has_value() ? conf_.debug_log_filename.value()
: "none");
if (conf_.rotating_logs) {
spdlog::get("log")->info("[Logging] rotating logs, size: {}, count: {}",
conf_.rotating_logs_size,
conf_.rotating_logs_count);
}
if (conf_.provide_platform_identification) {
spdlog::get("log")->info("[Platform] target architecture: \"{}\"",
exot::utilities::get_target_architecture());
spdlog::get("log")->info(
"[Platform] threads: {}, cores: {}, sockets: {}, online: [{}]",
exot::utilities::get_thread_count(), exot::utilities::get_core_count(),
exot::utilities::get_socket_count(),
exot::utilities::get_online_cpus_array());
for (unsigned idx{0}; idx < exot::utilities::get_cpu_count(); ++idx) {
spdlog::get("log")->info(
"[Platform] cpu: {}, online: {}, frequencies: [{}], governor: \"{}\"",
idx, exot::utilities::is_cpu_online(idx),
exot::utilities::get_cpu_frequencies(idx).value_or(
std::array<unsigned long, 2>{}),
exot::utilities::get_scaling_governor(idx).value_or(""));
}
for (const auto& model : exot::utilities::get_unique_cpu_models().value_or(
std::vector<std::string>{})) {
spdlog::get("log")->info("[Platform] cpu models: {}", model);
}
spdlog::get("log")->info("[Platform] topology: {}",
exot::utilities::get_complete_topology());
spdlog::get("log")->info(
"[Platform] kernel: {}",
exot::utilities::get_kernel_version().value_or("n/a"));
}
}
} // namespace exot::utilities
<file_sep>/src/meters/frequency_rel.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/frequency_rel.cpp
* @author <NAME>
* @brief Implementation of the empirical frequency metering module.
*/
#include <exot/meters/frequency_rel.h>
#include <type_traits>
#include <fmt/ostream.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/ostream.h>
#include <exot/utilities/thread.h>
using Thread = exot::utilities::ThreadTraits;
using namespace exot::modules;
using namespace std::chrono_literals;
namespace details {
// const unsigned std_iter = 1024;
// const unsigned std_iter = 2048;
const unsigned std_iter = 4096;
/**
* Helper to bootstrap cores in the constructor initialiser list, needed for
* initialising the barrier, which copy/assignment constructors are deleted.
*/
frequency_rel::settings bootstrap(frequency_rel::settings& conf) {
/* If the cores vector is empty, choose every other core on x86 architectures
* (which likely have hyperthreading), and every core on ARM-based platforms.
*/
if (conf.cores.empty()) {
for (unsigned i{0}; i < std::thread::hardware_concurrency();) {
conf.cores.push_back(i);
#if defined(__ANDROID__) || defined(__arm__) || defined(__aarch64__)
++i;
#else
++++i;
#endif
}
} else {
exot::utilities::bootstrap_cores(conf.cores);
}
return conf;
}
} // namespace details
/* The order of variables in the initialiser list matters, and is defined from
* last to first. */
frequency_rel::frequency_rel(frequency_rel::settings& conf)
: barrier_(conf_.cores.size() + 1), conf_{::details::bootstrap(conf)} {
readings_.resize(conf_.cores.size());
references_.resize(conf_.cores.size());
unsigned idx{0};
/* Spawn threads and obtain the reference probe durations */
for (auto core : conf_.cores) {
threads_.emplace_back(
[idx, core, this](barrier_type& barrier) {
Thread::set_affinity(core);
Thread::set_scheduling(exot::utilities::SchedulingPolicy::RoundRobin,
90);
debug_log_->debug("[frequency_rel] worker {}: {}", idx,
exot::utilities::thread_info());
{
worker_flag_.test_and_set(std::memory_order_acquire);
references_.at(idx) = reference_probe_duration(10);
worker_flag_.clear(std::memory_order_release);
}
barrier.wait();
while (!flag_.load(std::memory_order_acquire)) {
barrier.wait();
{
auto current_value =
references_.at(idx) /
details::probe<probe_type, probe_iterations>();
worker_flag_.test_and_set(std::memory_order_acquire);
readings_.at(idx) = std::move(current_value);
worker_flag_.clear(std::memory_order_release);
}
barrier.wait();
}
},
std::ref(barrier_));
++idx;
}
barrier_.wait();
debug_log_->info("[frequency_rel] reference probes: {}", references_);
}
frequency_rel::~frequency_rel() {
/* Set termination flag to true and go past barriers. */
flag_.store(true, std::memory_order_release);
barrier_.wait();
barrier_.wait();
for (auto& thread : threads_) {
barrier_.force_progress(); /* force progress just in case */
thread.join();
}
}
typename frequency_rel::duration_type frequency_rel::reference_probe_duration(
unsigned repetitions) {
typename frequency_rel::duration_type reference{0};
for (unsigned i{0}; i < repetitions; ++i) {
reference += details::probe<probe_type, probe_iterations>();
std::this_thread::sleep_for(10ms);
}
return (reference / repetitions);
}
typename frequency_rel::return_type frequency_rel::measure() {
/* Make progress on workers */
barrier_.wait();
barrier_.wait();
return readings_;
}
std::vector<std::string> frequency_rel::header() {
std::vector<std::string> descriptions;
for (auto core : conf_.cores) {
descriptions.push_back(
exot::utilities::generate_header(conf_.name(), "empirical", core, ""));
}
return descriptions;
}
<file_sep>/src/meters/cache_l1.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/cache_l1.cpp
* @author <NAME>
* @brief Implementation of the L1 cache meter.
*/
#include <exot/meters/cache_l1.h>
#include <cmath>
#include <type_traits>
#include <exot/utilities/allocator.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/literals.h>
#include <exot/utilities/thread.h>
#include <exot/utilities/timing.h>
#if defined(__x86_64__)
#include <exot/primitives/tsc.h>
#else
#include <exot/utilities/timing_source.h>
#endif
using Thread = exot::utilities::ThreadTraits;
using namespace exot::modules;
using namespace exot::utilities::literals;
using namespace std::chrono_literals;
namespace details {
/**
* Helper to bootstrap cores in the constructor initialiser list, needed for
* initialising the barrier, which copy/assignment constructors are deleted.
*/
cache_l1::settings bootstrap(cache_l1::settings& conf) {
/* If the cores vector is empty, choose every other core on x86 architectures
* (which likely have hyperthreading), and every core on ARM-based platforms.
*/
if (conf.cores.empty()) {
for (unsigned i{0}; i < std::thread::hardware_concurrency();) {
conf.cores.push_back(i);
#if defined(__ANDROID__) || defined(__arm__) || defined(__aarch64__)
++i;
#else
++++i;
#endif
}
} else {
exot::utilities::bootstrap_cores(conf.cores);
}
return conf;
}
} // namespace details
/* Allocate at 32_KiB boundaries to prevent false sharing. */
using allocator = exot::utilities::AlignedAllocator<std::uint8_t, 32_KiB>;
using buffer_type = std::vector<std::uint8_t, allocator>;
/* Timed access functions with different optimisation levels. */
inline __attribute__((always_inline, optimize("-O0"))) std::uint64_t
timed_access_O0(buffer_type& buffer, typename buffer_type::value_type& read,
int n, int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
inline __attribute__((always_inline, optimize("-O1"))) std::uint64_t
timed_access_O1(buffer_type& buffer, typename buffer_type::value_type& read,
int n, int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
inline __attribute__((always_inline, optimize("-O2"))) std::uint64_t
timed_access_O2(buffer_type& buffer, typename buffer_type::value_type& read,
int n, int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
inline __attribute__((always_inline, optimize("-O3"))) std::uint64_t
timed_access_O3(buffer_type& buffer, typename buffer_type::value_type& read,
int n, int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
inline __attribute__((always_inline, optimize("-Og"))) std::uint64_t
timed_access_Og(buffer_type& buffer, typename buffer_type::value_type& read,
int n, int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
inline __attribute__((always_inline, optimize("-Os"))) std::uint64_t
timed_access_Os(buffer_type& buffer, buffer_type::value_type& read, int n,
int os) {
#if defined(__x86_64__)
return exot::utilities::timeit<exot::primitives::MemoryFencedTSC>(
[&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#else
return exot::utilities::default_timing_facility([&]() mutable {
for (auto i = 0; i < n; ++i) { read += buffer[(1 << os) * i]; }
exot::utilities::do_not_optimise(read);
});
#endif
}
/* The order of variables in the initialiser list matters, and is defined from
* last to first. */
cache_l1::cache_l1(cache_l1::settings& conf)
: barrier_(conf_.cores.size() + 1), conf_{::details::bootstrap(conf)} {
readings_.resize(conf_.cores.size());
#if !defined(__x86_64__)
/* Call now() for 1-time initialisation of the perf_clock. */
// exot::primitives::fenced_clock<exot::primitives::perf_clock>::now();
#endif
auto l1 = (conf_.cache_info.has_value()
? exot::utilities::CPUCacheInfo(0, conf_.cache_info.value())
: exot::utilities::CPUCacheInfo(0))
.at(1, static_cast<int>(exot::utilities::CacheType::Data));
n_ = static_cast<int>(l1.ways_of_associativity().value());
o_ = static_cast<int>(std::log2(l1.coherency_line_size().value()));
s_ = static_cast<int>(std::log2(l1.number_of_sets().value()));
b_ = static_cast<int>(n_ * (1 << (o_ + s_)));
debug_log_->info("[cache_l1] using n: {:#x}, o: {:#x}, s: {:#x}, b: {:#x}",
n_, o_, s_, b_);
unsigned idx{0};
for (auto core : conf_.cores) {
threads_.emplace_back(
[idx, core, b = b_, this](barrier_type& barrier) {
Thread::set_affinity(core);
Thread::set_scheduling(exot::utilities::SchedulingPolicy::RoundRobin,
90);
debug_log_->debug("[cache_l1] worker {}: {}", idx,
exot::utilities::thread_info());
buffer_type buffer(b, 0);
typename buffer_type::value_type read = 0ul;
static thread_local auto local_n = n_;
static thread_local auto local_o_s = (o_ + s_);
/* At the first barrier, all buffers are allocated and memset'ed. */
barrier.wait();
while (flag_.load(std::memory_order_acquire)) {
/* At the seconds barrier, threads wait for master thread to
* initiate the measurement. */
barrier.wait();
/* Once passed, the timed access is executed. */
volatile auto current_value =
timed_access_Os(buffer, read, local_n, local_o_s);
/* Workers write the current value to the readings vector while
* holding a lock, to prevent race conditions. Vector writing
* is/might not be thread-safe. */
worker_flag_.test_and_set(std::memory_order_acquire);
readings_.at(idx) = std::move(current_value);
worker_flag_.clear(std::memory_order_release);
/* After passing the last barrier values are guaranteed to have been
* written into the readings vector. */
barrier.wait();
}
},
std::ref(barrier_));
++idx;
}
barrier_.wait();
}
cache_l1::~cache_l1() {
flag_.store(false, std::memory_order_release);
barrier_.wait();
barrier_.wait();
for (auto& thread : threads_) {
barrier_.force_progress();
thread.join();
}
}
typename cache_l1::return_type cache_l1::measure() {
/* Make progress on workers */
barrier_.wait(); // measurements are being made
barrier_.wait(); // measurements are wrtten back
return readings_;
}
std::vector<std::string> cache_l1::header() {
std::vector<std::string> descriptions;
for (auto core : conf_.cores) {
descriptions.push_back(exot::utilities::generate_header(
conf_.name(), "access_time", core, "cycles"));
}
return descriptions;
}
<file_sep>/include/exot/primitives/ordering.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/ordering.h
* @author <NAME>
* @brief Platform specific ordering primitives (fences, etc.).
*/
#pragma once
namespace exot::primitives {
#if defined(__x86_64__)
inline __attribute__((always_inline)) void load_fence() {
asm volatile("lfence" : : : "memory");
}
inline __attribute__((always_inline)) void store_fence() {
asm volatile("lfence" : : : "memory");
}
inline __attribute__((always_inline)) void memory_fence() {
asm volatile("mfence" : : : "memory");
}
inline __attribute__((always_inline)) void full_fence() {
asm volatile(
"cpuid \n\t"
"mfence "
:
:
: "memory", "%rax", "%rbx", "%rcx", "%rdx");
}
#elif defined(__arm__) || defined(__aarch64__)
inline __attribute__((always_inline)) void load_fence() {
asm volatile("dmb ishld" : : : "memory");
}
inline __attribute__((always_inline)) void store_fence() {
asm volatile("dmb ishst" : : : "memory");
}
inline __attribute__((always_inline)) void memory_fence() {
asm volatile("dmb ish" : : : "memory");
}
inline __attribute__((always_inline)) void full_fence() {
asm volatile(
"dsb sy \n\t" // full system reads and writes
"isb" // instruction synchronisation barrier
:
:
: "memory");
}
#endif
} // namespace exot::primitives
<file_sep>/include/exot/utilities/enum.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/enum.h
* @author <NAME>
* @brief Helpers to allow operations on typed enums.
*/
#pragma once
#include <type_traits>
namespace exot::utilities {
/**
* @brief Type trait to enable bit-wise operations for an Enum
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper (is enum?)
*/
template <typename Enum, typename = std::enable_if_t<std::is_enum<Enum>::value>>
struct enum_operations_enabled : std::false_type {};
/**
* @brief Bit-wise "or" operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return The or'ed enum result
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum operator|(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
return static_cast<Enum>(static_cast<T>(lhs) | static_cast<T>(rhs));
}
/**
* @brief Bit-wise "or" assignment operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return A reference to the or'ed lhs enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum& operator|=(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
lhs = static_cast<Enum>(static_cast<T>(lhs) | static_cast<T>(rhs));
return lhs;
}
/**
* @brief Bit-wise "and" operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return The and'ed enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum operator&(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
return static_cast<Enum>(static_cast<T>(lhs) & static_cast<T>(rhs));
}
/**
* @brief Bit-wise "and" assignment operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return A reference to the and'ed lhs enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum& operator&=(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
lhs = static_cast<Enum>(static_cast<T>(lhs) & static_cast<T>(rhs));
return lhs;
}
/**
* @brief Bit-wise "xor" operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return The xor'ed enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum operator^(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
return static_cast<Enum>(static_cast<T>(lhs) ^ static_cast<T>(rhs));
}
/**
* @brief Bit-wise "xor" assignment operator overload
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return A reference to the xor'ed lhs enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum& operator^=(Enum lhs, Enum rhs) {
using T = typename std::underlying_type_t<Enum>;
lhs = static_cast<Enum>(static_cast<T>(lhs) ^ static_cast<T>(rhs));
return lhs;
}
/**
* @brief Bit-wise "not" operator overload
*
* @param[in] e The enum
*
* @tparam Enum The enum
* @tparam <unnamed> Template helper
*
* @return The not'ed enum
*/
template <typename Enum,
typename = std::enable_if_t<(enum_operations_enabled<Enum>::value &&
std::is_enum<Enum>::value)>>
inline constexpr Enum& operator~(Enum e) {
using T = typename std::underlying_type_t<Enum>;
return static_cast<Enum>(~static_cast<T>(e));
}
}; // namespace exot::utilities
<file_sep>/include/exot/components/generator_ffb.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/generator_ffb.h
* @author <NAME>
* @brief Generator host component.
*/
#pragma once
#include <algorithm> // for std::distance
#include <atomic> // for atomic types and operations
#include <bitset> // for bitsets
#include <chrono>
#include <cstdlib> // for std::rand
#include <memory> // for std::shared_ptr
#include <mutex>
#include <set>
#include <shared_mutex>
#include <stdexcept> // for throwing
#include <string> // for std::string
#include <thread>
#include <tuple>
#include <type_traits>
#include <vector> // for variable-size arrays
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
//#include <covert/modules/base.h>
#include <exot/framework/all.h> // for framework support
#include <exot/generators/base.h> // for generators base class
#include <exot/utilities/barrier.h> // for barriers
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/ostream.h> // for ostream overloading
#include <exot/utilities/thread.h> // for ThreadTraits
#include <exot/utilities/timing.h> // for TimeKeeper
#include <exot/utilities/workers.h> // for TemplatedWorker
#ifndef GENERATOR_HOST_PERFORM_VALIDATION
#define GENERATOR_HOST_PERFORM_VALIDATION false
#endif
#ifndef GENERATOR_HOST_PROVIDE_TIMING_STATISTICS
#define GENERATOR_HOST_PROVIDE_TIMING_STATISTICS false
#endif
namespace exot::components {
/**
* @brief Template type alias for generator token types.
*/
template <typename Duration, typename Generator>
using generator_token_type =
std::tuple<Duration, typename Generator::subtoken_type>;
/**
* @brief Timed generator host.
*
* @tparam Duration The duration type
* @tparam Generator The generator class, must conform to
*/
template <typename Duration, typename Generator>
class generator_ffb : public Generator,
public exot::framework::IProcess,
public exot::framework::Consumer<
generator_token_type<Duration, Generator>> {
public:
struct host_options {
static constexpr bool perform_validation{
static_cast<bool>(GENERATOR_HOST_PERFORM_VALIDATION)};
static constexpr bool provide_timing_statistics{
static_cast<bool>(GENERATOR_HOST_PROVIDE_TIMING_STATISTICS)};
static constexpr bool set_affinity{true};
};
/* Type aliases. */
using node_type =
exot::framework::Consumer<generator_token_type<Duration, Generator>>;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using token_type = typename node_type::interface_type::value_type;
using subtoken_type = typename Generator::subtoken_type;
using clock_type = std::chrono::steady_clock;
using duration_type = Duration;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using policy_type = exot::utilities::SchedulingPolicy;
using barrier_type = exot::utilities::Barrier;
using timer_duration = std::chrono::nanoseconds;
using timer_type = exot::utilities::TimeKeeper<
clock_type, host_options::provide_timing_statistics, timer_duration>;
using worker_type =
exot::utilities::TemplatedWorker<exot::utilities::BarrierSynchronisation,
exot::utilities::SpecialisedThreads>;
using node_type::in_;
static_assert(exot::utilities::is_duration_v<Duration>,
"Must be a valid chrono duration type");
static_assert(exot::modules::is_generator_module<Generator>::value,
"Must be a conforming generator module");
struct settings : public exot::utilities::configurable<settings>,
public Generator::settings {
using base_t = exot::utilities::configurable<settings>;
/// @defgroup gen_worker_settings Generator host's worker settings
/// @{
unsigned core; //! worker' allocated core
std::vector<unsigned> cores; //! workers' allocated cores
bool should_pin_workers{true}; //! should pin the worker threads?
policy_type worker_policy{policy_type::Other}; //! workers' sched. policy
unsigned worker_priority{90u}; //! workers' scheduling priority
unsigned threshold{100}; //! worker measurement threshold
unsigned num_hits{20}; //! worker number of necessary measurement hits
unsigned num_probes{5}; //! worker number of necessary measurement hits
unsigned host_timeout_s{
60}; //! worker number of necessary measurement hits
/// @}
/// @defgroup gen_host_settings Generator host's master thread settings
/// @{
unsigned host_pinning{//! cpu to pin host's master thread to
std::thread::hardware_concurrency() - 1};
bool should_pin_host{true}; //! should pin the master thread?
policy_type host_policy{policy_type::Other}; //! this node's policy
unsigned host_priority{99u}; //! this node's priority
/// @}
bool use_busy_sleep{false}; //! does the host use busy sleep?
bool busy_sleep_yield{false}; //! busy sleep yields calling thread
unsigned start_check_period{1}; //! how often to check if started in µs
static_assert(
exot::utilities::is_configurable_v<typename Generator::settings>,
"Generator modules must satisfy is_configurable to be used with JSON "
"configuration.");
/* @brief The combining settings structure needs to overload this to allow
* initialising JSON configs in inherited classes. */
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
Generator::settings::set_json(root);
}
const char* name() const { return "generator"; }
auto describe() {
return base_t::describe() + Generator::settings::describe();
}
/* @brief The JSON configuration function */
void configure() {
base_t::bind_and_describe_data(
"cores", cores,
"cores to pin worker to |uint|, e.g. [0]"
"further cores will be ignored - this is for compatibility reasons");
base_t::bind_and_describe_data(
"should_pin_workers", should_pin_workers,
"should pin the workers? |bool|, default 'true'");
base_t::bind_and_describe_data("worker_policy", worker_policy,
"scheduling policy of the workers |str, "
"policy_type|, e.g. \"round_robin\"");
base_t::bind_and_describe_data(
"worker_priority", worker_priority,
"scheduling priority of the workers |uint|, "
"in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"threshold", threshold,
"measurement threshold used to detect a frequency change"
"|uint|");
base_t::bind_and_describe_data(
"num_probes", num_probes,
"number of necessary probes for one measurement"
"|uint|");
base_t::bind_and_describe_data(
"num_hits", num_hits,
"number of necessary measurement hits to detect a frequency change"
"|uint|");
base_t::bind_and_describe_data(
"host_timeout_s", host_timeout_s,
"generator host timeout in seconds |uint|, e.g. 20");
base_t::bind_and_describe_data(
"host_pinning", host_pinning,
"generator host core pinning |uint|, e.g. 5");
base_t::bind_and_describe_data(
"should_pin_host", should_pin_host,
"should pin the host? |bool|, default 'true'");
base_t::bind_and_describe_data("host_policy", host_policy,
"scheduling policy of the host |str, "
"policy_type|, e.g. \"round_robin\"");
base_t::bind_and_describe_data(
"host_priority", host_priority,
"scheduling priority of the host |uint|, in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"start_check_period", start_check_period,
"state change detection update period |uint, µs|, e.g. 100");
base_t::bind_and_describe_data("use_busy_sleep", use_busy_sleep,
"should use busy sleep loop? |bool|");
base_t::bind_and_describe_data(
"busy_sleep_yield", busy_sleep_yield,
"should yield thread in busy sleep loop? |bool|");
Generator::settings::configure();
}
};
/**
* @brief The probing function
*
* @tparam T An arithmetic type (e.g. unsigned, double)
* @tparam Iter Interaction count
* @tparam <unnamed> Template helper
*
* @return The probe duration in nanoseconds
*/
template <typename T, unsigned Iter,
typename = std::enable_if_t<std::is_arithmetic_v<T>>>
inline std::chrono::nanoseconds probe() {
volatile T a = std::rand(), b = std::rand();
auto start = std::chrono::steady_clock::now();
for (unsigned i{0}; i < Iter; ++i) {
a += b + static_cast<T>(i);
b *= a;
}
return (std::chrono::steady_clock::now() - start);
}
/**
* @brief Constructor
*
* @param[in] conf The configuration structure
*/
explicit generator_ffb(settings& conf)
: Generator(conf),
barrier_{static_cast<unsigned int>(1)},
conf_{validate_settings(conf)},
global_state_{exot::framework::GLOBAL_STATE->get()} {
worker_count_ = static_cast<unsigned int>(1);
local_state_ = std::make_shared<state_type>();
if constexpr (host_options::set_affinity) {
if (conf_.host_pinning >= std::thread::hardware_concurrency()) {
throw std::logic_error("Supplied wrong CPU to pin the generator_ffb");
}
}
if (conf_.use_busy_sleep && !conf_.busy_sleep_yield) {
debug_log_->info("[generator_ffb] using busy sleep w/o thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, false>);
} else if (conf_.use_busy_sleep && conf_.busy_sleep_yield) {
debug_log_->info("[generator_ffb] using busy sleep with thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, true>);
} else {
timer_ = timer_type(debug_log_);
}
/* Create a worker. */
debug_log_->debug("[generator_ffb] creating worker on core: {}", //
conf_.core);
auto core = conf_.cores.front();
conf_.core = conf_.cores.front();
auto num_probes = conf_.num_probes;
std::chrono::nanoseconds threshold{conf_.threshold};
auto num_hits = conf_.num_hits;
worker_threads_.emplace_back(worker_type(
local_state_->get(),
// config for SynchronisationPolicy->BarrierSynchronisation
{std::ref(barrier_)},
// config for ThreadingPolicy->SpecialisedThreads
{conf_.core, conf_.should_pin_workers, conf_.worker_policy,
conf_.worker_priority},
/* Take core and index by value, this object by reference. */
[this, core, num_probes, threshold, num_hits] {
unsigned int cnt_hit = 0;
//! One utilisation cycle should be 100us long. This way sleep is not
//! called too often but the loagen_bc is still sampling way faster
//! (>10x) than the governor.
std::chrono::nanoseconds old_measurement,
new_measurement = probe<double, 1024>();
unsigned int num_probes =
std::chrono::microseconds(100) / new_measurement + 1;
auto sleep_duration =
this->get_sleep_time(subtoken_, new_measurement);
int change_count = 0;
//! While no timeout has occured try to change the frequency until the
//! desired number of frequency changes have been reached
while (enable_flag_ || subtoken_ != change_count) {
old_measurement = new_measurement;
timer_.sleep(sleep_duration);
new_measurement = std::chrono::nanoseconds(0);
for (unsigned int cnt = 0; cnt < num_probes; cnt++) {
new_measurement += probe<double, 1024>();
}
new_measurement /= num_probes;
auto difference =
std::chrono::duration_cast<std::chrono::nanoseconds>(
new_measurement - old_measurement);
//! If the difference between two measurements is bigger than the
//! threshold, increase the hit count
if ((difference >= difference.zero()) ? (difference > threshold)
: (-difference > threshold)) {
cnt_hit++;
if (cnt_hit == num_hits) {
(difference >= difference.zero()) ? (change_count += 1)
: (change_count -= 1);
}
} else {
cnt_hit = 0;
}
}
enable_flag_ = false;
worker_done_.notify_one(); // Release main threat from wait
},
debug_log_));
}
~generator_ffb() {
debug_log_->debug("[generator_ffb] joining worker threads");
/* Join worker threads. */
for (auto& thread : worker_threads_) {
if (thread.joinable()) thread.join();
}
debug_log_->info("[generator_ffb] shutting down");
if constexpr (host_options::provide_timing_statistics) {
/* Dump timpestamped offset characteristics {actual, desired, offset}. */
auto dump = std::move(timer_.dump_log());
application_log_->info(
"{},{},{}",
exot::utilities::generate_header(
conf_.name(), "timestamp", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})),
exot::utilities::generate_header(
conf_.name(), "desired", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})),
exot::utilities::generate_header(
conf_.name(), "offset", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})));
for (auto& row : dump) {
if constexpr (std::is_floating_point_v<
typename timer_type::reporting_granularity::rep>) {
application_log_->info("{:.2f},{:.2f},{:.2f}", //
row[0].count(), row[1].count(),
row[2].count());
} else {
application_log_->info("{},{},{}", //
row[0].count(), row[1].count(),
row[2].count());
}
}
/* Log mean and deviation timing statistics */
debug_log_->info("[{}] offset: {}", conf_.name(),
timer_.offset_statistics());
}
}
/**
* @brief The main process
*/
void process() override {
token_type token;
std::once_flag once;
if constexpr (host_options::set_affinity) {
if (conf_.should_pin_host)
exot::utilities::ThreadTraits::set_affinity(conf_.host_pinning);
}
exot::utilities::ThreadTraits::set_scheduling(conf_.host_policy,
conf_.host_priority);
debug_log_->info("[generator_ffb] running on {}",
exot::utilities::thread_info());
const auto check_p = std::chrono::microseconds{conf_.start_check_period};
/**
* Starting conditions:
* - Wait until the global state is started.
*/
while (!global_state_->is_started()) {
std::this_thread::sleep_for(check_p);
}
debug_log_->info("[generator_ffb] starting");
std::chrono::seconds timeout_s(conf_.host_timeout_s);
while (!local_state_->is_stopped()) {
in_.read(token); // read token from the input queue
SPDLOG_LOGGER_TRACE(debug_log_, "[generator_ffb] read token {}", token);
/* Decompose the input token into duration and subtoken. */
duration_ = std::get<duration_type>(token);
subtoken_ = std::get<subtoken_type>(token);
if constexpr (host_options::perform_validation) {
if (!this->validate_subtoken(subtoken_)) {
debug_log_->critical(
"[generator_ffb] Subtoken validation failed with value: {}. "
"Aborting.",
subtoken_);
debug_log_->flush();
throw std::out_of_range(fmt::format(
"Subtoken valudation failed with value: {}", subtoken_));
}
}
std::unique_lock<std::mutex> timeout_lock(timeout_mutex_);
/* Init timing once after the first successful read from the queue. */
std::call_once(once, [this] { timer_.begin(); });
enable_flag_ = true; // Workers start processing...
barrier_.wait(); // ... after passing the first randezvous
worker_done_.wait_for(
timeout_lock,
timeout_s); //! TODO check if wait_for or similar function timed-out;
//! the return value can be accessed as type
//! std::cv_status e.g. with value of
//! std::cv_status::timeout -> use this to replace the
//! enable_flag_?
if (enable_flag_) {
debug_log_->info("[generator_ffb] Stopping due to timeout");
enable_flag_ = false; // Workers finish processing.
global_state_->terminate(); //! Abort exection due to an error...
}
timer_.update_offset();
if (global_state_->is_stopped() && !in_.is_readable()) {
local_state_->stop();
} else if (global_state_->is_stopped() &&
global_state_->is_terminated()) {
token_type dummy;
while (!in_.is_readable()) { in_.read(dummy); }
local_state_->stop();
}
barrier_.wait(); // Second randezvous point
}
}
/**
* @brief Check if supplied configuration conforms to sensible values
*/
settings validate_settings(settings& conf) {
auto core_valid = [](auto el) {
return el >= 0 && el < std::thread::hardware_concurrency();
};
return conf;
}
private:
settings conf_;
state_pointer local_state_;
state_pointer global_state_;
barrier_type barrier_;
timer_type timer_;
duration_type duration_;
subtoken_type subtoken_;
logger_pointer application_log_ =
spdlog::get("app") ? spdlog::get("app") : spdlog::stdout_color_mt("app");
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
std::atomic_bool enable_flag_{false};
mutable std::shared_mutex subtoken_mtx_;
std::vector<std::thread> worker_threads_;
unsigned worker_count_;
std::mutex timeout_mutex_;
std::condition_variable worker_done_;
}; // generator_ffb
} // namespace exot::components
<file_sep>/include/exot/utilities/alignment.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/alignment.h
* @author <NAME>
* @brief An allocator and a type wrapper for explicitly allocated vectors
* and simple arithmetic data types.
*/
#pragma once
#include <type_traits>
namespace exot::utilities {
/**
* @brief Determines if a number is a valid alignment.
*
* @param[in] value The alignment
*
* @return True if a value is a power of 2, False otherwise.
*/
constexpr inline bool is_valid_alignment(std::size_t value) noexcept {
return (value > 0) && ((value & (value - 1)) == 0);
}
/**
* @brief Aligned type wrapper
*
* @tparam T The value type to wrap
* @tparam A The desired alignment
* @tparam <unnamed> Template helper (only fundamental types allowed)
*/
template <typename T, std::size_t A,
typename = std::enable_if_t<(
std::is_arithmetic_v<T> || std::is_pointer_v<T> ||
std::is_same_v<std::remove_cv_t<T>, void*>)>>
struct aligned_t {
/* Type aliases */
using value_type = T;
using this_type = aligned_t<T, A>;
/* The aligned value */
alignas(A) T _value;
/* Verify that alignment is achieved */
static_assert(is_valid_alignment(A));
/**
* Default constructor
*/
aligned_t() = default;
/**
* @brief Copy constructor for value types
*
* @param value The value
*/
aligned_t(value_type&& value) : _value(value) {}
/**
* @brief Proxy to the value
*/
operator T() { return _value; }
/**
* @brief Proxy to the pointer to the value
*/
T* operator&() __attribute__((assume_aligned(A))) { return &_value; }
};
/**
* @brief Makes an aligned version of a value
*
* @param[in] t The value to make aligned
*
* @tparam A The alignment
* @tparam T The value type
*
* @return An aligned value
*/
template <std::size_t A, typename T>
constexpr auto make_aligned(T t) -> aligned_t<T, A> {
return aligned_t<T, A>{t};
}
} // namespace exot::utilities
<file_sep>/include/exot/framework/state.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/state.h
* @author <NAME>
* @brief State holder and the global state object.
*/
#pragma once
#include <atomic> // for atomic variables and operations
#include <csignal> // for intercepting signals
#include <memory> // for shared pointers
#include <fmt/format.h>
namespace exot::framework {
/**
* @brief Holds global (or local) execution state.
* @details Atomic operations ensure safe access and order. They also allow
* the class objects to be used in signal handlers.
*/
class State : public std::enable_shared_from_this<State> {
public:
using state_type = State;
using state_pointer = std::shared_ptr<state_type>;
/**
* @brief Set state to started
*/
inline void start() { started_.store(true); };
inline bool is_started() { return started_.load(); };
/**
* @brief Set state to stopped
*/
inline void stop() { stopped_.store(true); };
inline bool is_stopped() { return stopped_.load(); };
/**
* @brief Stop and terminate
*/
inline void terminate() {
stopped_.store(true);
terminated_.store(true);
};
inline bool is_terminated() { return terminated_.load(); };
/**
* @brief Reset to original values
*/
inline void reset() {
started_.store(false);
stopped_.store(false);
terminated_.store(false);
}
constexpr State() = default;
~State() = default;
/**
* Cannot be copied.
*/
State(const State&) = delete;
State& operator=(const State&) = delete;
/**
* @brief Get a shared pointer to state object.
*
* @return Shared pointer to specific object instance.
*/
auto get() { return shared_from_this(); };
private:
volatile std::atomic<bool> started_{false};
volatile std::atomic<bool> stopped_{false};
volatile std::atomic<bool> terminated_{false};
};
/**
* Global state used for managing execution. Can be used in signal handlers.
*/
static State::state_pointer GLOBAL_STATE{std::make_shared<State>()};
/**
* @brief Handlers for Unix signals
*/
static void interrupt_handler(int) {
GLOBAL_STATE->stop();
}
static void terminate_handler(int) {
GLOBAL_STATE->terminate();
}
static void start_handler(int) {
GLOBAL_STATE->start();
}
/**
* @brief Convienience wrapper for setting up global state
*/
static void init_global_state_handlers() {
std::signal(SIGINT, interrupt_handler);
std::signal(SIGQUIT, terminate_handler);
std::signal(SIGUSR1, start_handler);
}
} // namespace exot::framework
<file_sep>/include/exot/components/domain_adapter.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/domain_adapter.h
* @author <NAME>
* @brief Simple node classes to bridge system and userland thread domains.
*/
#pragma once
#ifdef EXOT_USE_FIBERS
#include <chrono> // for durations
#include <exot/framework/all.h> // for framework support
using namespace std::chrono_literals;
namespace exot::components {
/**
* Node classes to bridge the system and userland thread domains.
*/
inline namespace domain_adapters {
template <typename Token>
class FiberToThread : public exot::framework::IProcess,
public exot::framework::IProcessor<
Token, exot::framework::FiberTimeoutLockingQueue,
exot::framework::ExtendedQueueReader, Token,
exot::framework::TimeoutLockingQueue,
exot::framework::ExtendedQueueWriter> {
public:
using node_type =
exot::framework::Processor<Token,
exot::framework::FiberTimeoutLockingQueue,
exot::framework::ExtendedQueueReader, Token,
exot::framework::TimeoutLockingQueue,
exot::framework::ExtendedQueueWriter>;
using token_type = Token;
using consumer_type = typename node_type::consumer_type;
using producer_type = typename node_type::producer_type;
using node_type::in_;
using node_type::out_;
FiberToThread(
typename consumer_type::interface_type::container_pointer input,
typename producer_type::interface_type::container_pointer output)
: node_type(input, output){};
FiberToThread() : node_type(){};
void process() override {
while (!global_state_->is_stopped()) {
token_type token;
if (in_.try_read_for(token, 200ms)) { out_.write(token); }
}
};
};
template <typename Token>
class ThreadToFiber : public exot::framework::IProcess,
public exot::framework::IProcessor<
Token, exot::framework::TimeoutLockingQueue,
exot::framework::ExtendedQueueReader, Token,
exot::framework::FiberTimeoutLockingQueue,
exot::framework::ExtendedQueueWriter> {
public:
using node_type =
exot::framework::Processor<Token, exot::framework::TimeoutLockingQueue,
exot::framework::ExtendedQueueReader, Token,
exot::framework::FiberTimeoutLockingQueue,
exot::framework::ExtendedQueueWriter>;
using token_type = Token;
using consumer_type = typename node_type::consumer_type;
using producer_type = typename node_type::producer_type;
using node_type::in_;
using node_type::out_;
ThreadToFiber(
typename consumer_type::interface_type::container_pointer input,
typename producer_type::interface_type::container_pointer output)
: node_type(input, output){};
ThreadToFiber() : node_type(){};
void process() override {
while (!global_state_->is_stopped()) {
token_type token;
if (in_.try_read_for(token, 200ms)) { out_.write(token); }
}
};
};
} // namespace domain_adapters
} // namespace exot::components
#endif
<file_sep>/include/exot/generators/cache_st.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
#pragma once
#include <memory>
#include <exot/generators/base_shared_memory.h>
#include <exot/primitives/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/eviction.h>
namespace exot::modules {
/**
* @brief Generator that accesses addresses by performing reads
*/
struct generator_cache_read_st : public shared_memory_generator_base {
using shared_memory_generator_base::shared_memory_generator_base;
inline __attribute__((always_inline)) void perform_action_on_address(
void* addr) override {
exot::primitives::access_read<>(addr);
}
};
/**
* @brief Generator that accesses addresses by performing writes
*/
struct generator_cache_write_st : public shared_memory_generator_base {
using shared_memory_generator_base::shared_memory_generator_base;
inline __attribute__((always_inline)) void perform_action_on_address(
void* addr) override {
exot::primitives::access_write<>(addr);
}
};
/**
* @brief Generator that accesses addresses with eviction patterns
*/
struct generator_cache_evict_st : public shared_memory_generator_base {
using evicter_type = exot::utilities::Evicter;
struct settings
: public exot::utilities::configurable<settings>,
public exot::modules::shared_memory_generator_base::settings {
using base_t = exot::utilities::configurable<settings>;
/* Eviction strategy settings. */
std::size_t addresses_per_loop{2};
std::size_t accesses_per_loop{2};
std::size_t overlap_parameter{1};
std::size_t eviction_length{64};
const char* name() const { return "generator"; }
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
exot::modules::shared_memory_generator_base::settings::set_json(root);
}
auto describe() {
return base_t::describe() +
exot::modules::shared_memory_generator_base::settings::describe();
}
void configure() {
base_t::bind_and_describe_data(
"addresses_per_loop", addresses_per_loop,
"number of addresses accessed in an eviction "
"loop |uint|, default: 2");
base_t::bind_and_describe_data(
"accesses_per_loop", accesses_per_loop,
"number of accesses to each address |uint|, default: 2");
base_t::bind_and_describe_data(
"overlap_parameter", overlap_parameter,
"the eviction overlap parameter |uint|, default: 1");
base_t::bind_and_describe_data(
"eviction_length", eviction_length,
"number of bytes to evict |uint|, default: 64");
exot::modules::shared_memory_generator_base::settings::configure();
}
};
explicit generator_cache_evict_st(settings& conf)
: shared_memory_generator_base(conf), lconf_{conf} {
evicter_ = std::make_unique<evicter_type>(lconf_.addresses_per_loop,
lconf_.accesses_per_loop,
lconf_.overlap_parameter);
}
inline __attribute__((always_inline)) void perform_action_on_address(
void* addr) override {
evicter_->read(reinterpret_cast<std::uint8_t*>(addr),
lconf_.eviction_length);
}
private:
settings lconf_; //! local settings (not base's)
std::unique_ptr<evicter_type> evicter_; //! evicter as a unique ptr due to
//! the deleted default constructor
};
} // namespace exot::modules
<file_sep>/include/exot/components/schedule_reader.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/schedule_reader.h
* @author <NAME>
* @brief Schedule reader node, outputs user-defined tokens based on file
* or console input.
*/
#pragma once
#include <chrono>
#include <fstream>
#include <ios>
#include <iostream>
#include <istream>
#include <optional>
#include <string>
#include <thread>
#include <fmt/format.h> // for string formatting
#include <fmt/ostream.h> // for ostream support
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/framework/all.h> // for framework support
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/istream.h> // for reading tuples via >>
#include <exot/utilities/ostream.h> // for printing tuples
#include <exot/utilities/thread.h>
namespace exot::components {
/**
* @brief Class for reading schedule files
*
* @tparam Token Token type required by the receiving node
*/
template <typename Token>
class schedule_reader : public exot::framework::IProcess,
public exot::framework::Producer<Token> {
public:
using node_type = exot::framework::Producer<Token>;
using token_type = typename node_type::interface_type::value_type;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using clock_type = std::chrono::steady_clock;
using node_type::out_;
/**
* @brief Structure holding module settings
* @todo REFACTOR with std::optional for `input_file`
*/
struct settings : public exot::utilities::configurable<settings> {
std::string input_file; /*! path to schedule file */
bool reading_from_file{false}; /*! flag set when reading from file */
bool read_as_hex{false}; /*! interpret input as hexadecimal? */
std::optional<unsigned> cpu_to_pin;
const char* name() const { return "schedule_reader"; }
/* @brief The JSON configuration function */
void configure() {
/* "this->" required for fixing an error that appears only in templated
* components where declarations in dependent base are not found by
* unqualified lookup, "'bind_and_describe_data' was not declared in this
* scope, and no declarations were found by argument-dependent lookup at
* the point of instantiation" (G++ 8.2.0). */
this->bind_and_describe_data(
"input_file", input_file,
"the input schedule file |string|, e.g. \"input.sched\"");
this->bind_and_describe_data(
"reading_from_file", reading_from_file,
"reading from file? |bool|, reads from stdin if false");
this->bind_and_describe_data("read_as_hex", read_as_hex,
"read hexadecimal values? |bool|");
this->bind_and_describe_data("cpu_to_pin", cpu_to_pin,
"schedule reader pinning |uint|, e.g. 7");
}
};
/**
* @brief Constructs the schedule reader
*
* @param conf The settings structure
*/
schedule_reader(settings& conf) : conf_{conf} {
if (!conf_.reading_from_file) {
debug_log_->info("[schedule_reader] reading from standard input");
input_ = std::make_unique<std::istream>(std::cin.rdbuf());
} else {
debug_log_->info("[schedule_reader] reading from file: {}",
conf_.input_file);
input_ = std::make_unique<std::ifstream>(conf_.input_file);
}
if (conf_.cpu_to_pin.has_value()) {
if (conf_.cpu_to_pin.value() >= std::thread::hardware_concurrency()) {
throw std::logic_error("Supplied wrong CPU to pin the schedule_reader");
}
}
}
/**
* @brief Main process
*/
void process() override {
if (conf_.cpu_to_pin.has_value()) {
exot::utilities::ThreadTraits::set_affinity(conf_.cpu_to_pin.value());
}
debug_log_->info("[schedule_reader] running on {}",
exot::utilities::thread_info());
for (std::string line;
std::getline(*input_, line) && !global_state_->is_stopped();) {
std::istringstream internal(line);
token_type current;
if (conf_.read_as_hex) {
internal >> std::hex >> current;
} else {
internal >> current;
}
debug_log_->debug("[schedule_reader] received and formatted tuple: {}",
current);
while (!out_.try_write_for(current, std::chrono::seconds{1}) &&
!global_state_->is_stopped()) {}
}
if (input_->eof()) {
debug_log_->info(
"[schedule_reader] reached end of file/stream, stopping global "
"state");
global_state_->stop();
}
}
private:
state_pointer global_state_{exot::framework::GLOBAL_STATE->get()};
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_;
std::unique_ptr<std::istream> input_;
}; // namespace exot::components
} // namespace exot::components
<file_sep>/src/utilities/thread.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/thread.cpp
* @author <NAME>
* @brief Implementation of the thread traits from @ref thread.h.
*/
#include <exot/utilities/thread.h>
#if defined(__linux__)
#include <sys/syscall.h> // for SYS_gettid
#include <sys/types.h> // for pid_t
#include <unistd.h> // for syscall
#elif defined(__APPLE__)
#include <thread> // for this_thread::get_id
#include <fmt/ostream.h>
#include <exot/utilities/x86_64.h> // for logical_id
#endif
#include <algorithm> // for std::clamp
#include <fmt/format.h> // for fmt::format
#include <exot/utilities/types.h> // for to_underlying_type
namespace exot::utilities {
std::string thread_info() {
int policy;
struct sched_param param;
pthread_getschedparam(pthread_self(), &policy, ¶m);
#if !defined(__APPLE__)
return fmt::format("id: {}, cpu: {}, policy: {}, priority: {}",
static_cast<unsigned long>(pthread_self()), sched_getcpu(),
policy, param.sched_priority);
#else
return fmt::format("id: {}, cpu: {}, policy: {}, priority: {}",
std::this_thread::get_id(), exot::utilities::logical_id(),
policy, param.sched_priority);
#endif
};
int ThreadTraits::set_affinity(unsigned int cpu) {
#if !defined(__APPLE__)
/* CPU_* macros manipulate the bitmask cpu_mask, are available only on
* Linux-based platforms. */
cpu_set_t cpu_mask;
CPU_ZERO(&cpu_mask);
CPU_SET(cpu, &cpu_mask);
/* The syscall `gettid()` is used in conjunction with sched_setaffinity as it
* seems to be more portable than pthread_setaffinity_np.
*/
pid_t tid = syscall(SYS_gettid);
return sched_setaffinity(tid, sizeof(cpu_set_t), &cpu_mask);
#else
return -1;
#endif
};
int ThreadTraits::set_affinity(pthread_t native_handle, unsigned int cpu) {
#if !defined(__ANDROID__) && !defined(__APPLE__)
cpu_set_t cpu_mask;
CPU_ZERO(&cpu_mask);
CPU_SET(cpu, &cpu_mask);
return pthread_setaffinity_np(native_handle, sizeof(cpu_set_t), &cpu_mask);
#else
return -1;
#endif
};
/**
* @details The chosen priority will be clamped to the allowed range for a
* specific scheduling policy (e.g. [0] only for default policy,
* [0,99] for FIFO and round robin). Unexpected behaviour can happen
* when the implementation defines lower granularity of priorities,
* since in POSIX only a certain minimum number of steps has to be
* available.
*/
int ThreadTraits::set_scheduling(SchedulingPolicy policy, int priority) {
#if !defined(__APPLE__)
/* "Cast" the scoped enum to its underlying type `int`. */
auto policy_ = to_underlying_type(policy);
/* Get minimum and maximum priority values for given policy. */
auto min = sched_get_priority_min(policy_);
auto max = sched_get_priority_max(policy_);
/* Clamp given priority to the allowed value range. */
int priority_ = std::clamp(priority, min, max);
const struct sched_param param = {priority_};
pid_t tid = syscall(SYS_gettid);
return sched_setscheduler(tid, policy_, ¶m);
#else
return ThreadTraits::set_scheduling(pthread_self(), policy, priority);
#endif
};
int ThreadTraits::set_scheduling(pthread_t native_handle,
SchedulingPolicy policy, int priority) {
/* "Cast" the scoped enum to its underlying type `int`. */
auto policy_ = to_underlying_type(policy);
/* Get minimum and maximum priority values for given policy. */
auto min = sched_get_priority_min(policy_);
auto max = sched_get_priority_max(policy_);
/* Clamp given priority to the allowed value range. */
int priority_ = std::clamp(priority, min, max);
const struct sched_param param = {priority_};
return pthread_setschedparam(native_handle, policy_, ¶m);
};
} // namespace exot::utilities
<file_sep>/cmake/modules/print_build_info.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file print_build_info.cmake
# @author <NAME>
# @brief Function that prints current build info, including flags, and
# directory properties.
#
include(colour_message)
include(print_directory_properties)
function(print_build_info)
colour_message(STATUS NONE BOLD "Build info ⤵")
if (DEFINED CMAKE_TOOLCHAIN_FILE)
get_filename_component(toolchain ${CMAKE_TOOLCHAIN_FILE} NAME)
message(STATUS "Using toolchain file: " ${Bold}${toolchain}${Reset})
endif ()
message(STATUS "Using Boost::fiber: " ${Bold}${exot_use_fibers}${Reset})
message(STATUS "Exporting compile commands: " ${Bold}${CMAKE_EXPORT_COMPILE_COMMANDS}${Reset})
message(STATUS "Using static analysis: " ${Bold}${enable_clang_tidy}${Reset})
message(STATUS ${Bold} "Build type: " ${Reset} ${CMAKE_BUILD_TYPE})
colour_message(STATUS NONE BOLD "CXX flags:")
message(STATUS ${Bold} " Common: "
${Reset} ${CMAKE_CXX_FLAGS})
message(STATUS ${Bold}${Red} " Debug: "
${Reset} ${CMAKE_CXX_FLAGS_DEBUG})
message(STATUS ${Bold}${Green} " Release: "
${Reset} ${CMAKE_CXX_FLAGS_RELEASE})
message(STATUS ${Bold}${Yellow} " RelWithDebInfo: "
${Reset} ${CMAKE_CXX_FLAGS_RELWITHDEBINFO})
colour_message(STATUS NONE BOLD "Linker flags:")
message(STATUS ${Bold} " Common: "
${Reset} ${CMAKE_EXE_LINKER_FLAGS})
message(STATUS ${Bold}${Red} " Debug: "
${Reset} ${CMAKE_EXE_LINKER_FLAGS_DEBUG})
message(STATUS ${Bold}${Green} " Release: "
${Reset} ${CMAKE_EXE_LINKER_FLAGS_RELEASE})
message(STATUS ${Bold}${Yellow} " RelWithDebInfo: "
${Reset} ${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO})
print_directory_properties(COMPILE_DEFINITIONS)
print_directory_properties(COMPILE_OPTIONS)
print_directory_properties(CXX_STANDARD)
print_directory_properties(CXX_STANDARD_REQUIRED)
colour_message(STATUS NONE BOLD "Build info ⤴")
endfunction()
<file_sep>/include/exot/utilities/allocator.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/alignment.h
* @author <NAME>
* @brief Custom allocators complying with STL requirements, for aligned
* storage, storage with advices to the kernel, huge pages storage,
* and aligned & advised storage.
*/
#pragma once
#if defined(__linux__)
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <string>
#include <type_traits>
#include <fmt/format.h>
#include <exot/utilities/alignment.h>
#include <exot/utilities/enum.h>
namespace exot::utilities {
struct bad_alloc : public std::exception {
bad_alloc(std::string err) : what_{err} {}
bad_alloc(const char* err) : what_{err} {}
bad_alloc() : what_{""} {}
const char* what() const noexcept override { return what_.c_str(); }
private:
std::string what_;
};
/**
* @brief Enumeration for madvice(2) advice bits.
* @note Prevents invalid use and establishes strong types.
*/
enum class Advice : int {
normal = MADV_NORMAL,
random = MADV_RANDOM,
sequential = MADV_SEQUENTIAL,
willneed = MADV_WILLNEED,
dontneed = MADV_DONTNEED,
remove = MADV_REMOVE,
dontfork = MADV_DONTFORK,
dofork = MADV_DOFORK,
hwpoison = MADV_HWPOISON,
mergeable = MADV_MERGEABLE,
unmergeable = MADV_UNMERGEABLE,
hugepage = MADV_HUGEPAGE,
nohugepage = MADV_NOHUGEPAGE,
dontdump = MADV_DONTDUMP,
dodump = MADV_DODUMP,
free = MADV_FREE,
keeponfork = MADV_KEEPONFORK
};
/**
* @brief Overload of enum_operations_enabled for Advice
* @details Enables bitwise operators on the Advice enum.
*/
template <>
struct enum_operations_enabled<Advice> : std::true_type {};
/**
* @brief Advises the kernel about how a memory range is used
*
* @param address The address
* @param[in] length The length
* @param[in] advice The advice
*/
inline void advise(void* address, std::size_t length, Advice advice) {
if (::madvise(address, length, static_cast<int>(advice)) != 0)
throw std::logic_error(
fmt::format("madvice failed with error: {}",
errno != 0 ? std::strerror(errno) : "unknown"));
}
/**
* @brief Aligned allocator to use with STL containers
*
* @tparam T The value type
* @tparam Al The desired alignment
*/
template <typename T, std::size_t Al = alignof(T)>
struct AlignedAllocator {
/* Required typedefs/aliases */
using value_type = T;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::true_type;
/* Can only align on alignments that are powers of 2. */
static_assert(is_valid_alignment(Al), "Alignment must be a power of 2");
static_assert(alignof(T) <= Al, "Alignment must be at least the default");
/* Constructors */
AlignedAllocator() = default;
AlignedAllocator(const AlignedAllocator& other) = default;
AlignedAllocator& operator=(const AlignedAllocator& other) = delete;
template <typename U>
AlignedAllocator(const AlignedAllocator<U, Al>&) noexcept {};
~AlignedAllocator() = default;
/* Deprecated */
template <class U>
struct rebind {
using other = AlignedAllocator<U, Al>;
};
/**
* @brief Allocates memory
* @details Uses the `posix_memalign` function from cstdlib.
*
* @param[in] n The size to allocate
*/
[[nodiscard]] T* allocate(std::size_t n) const {
if (n == 0) { return nullptr; }
if (n > std::numeric_limits<size_type>::max() / sizeof(T)) {
throw bad_alloc(
"AlignedAllocator failed: requested more bytes than possible.");
}
/* Allocate memory. posix_memalign returns non-zero if failed. */
void* aligned = nullptr;
if (::posix_memalign(&aligned, Al, n * sizeof(T))) {
throw bad_alloc(fmt::format(
"AlignedAllocator failed: posix_memalign failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
}
if (aligned != nullptr) {
return reinterpret_cast<T*>(aligned);
} else {
throw bad_alloc("AlignedAllocator failed: null pointer");
}
}
/**
* @brief Frees memory
*
* @param p The pointer to memory to deallocate
* @param[in] n The count to deallocate (unused)
*/
void deallocate(T* p, std::size_t n) const {
std::free(reinterpret_cast<void*>(p));
}
};
/**
* @brief Checks if allocators are not the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Al1 The lhs alignment
* @tparam T2 The rhs value type
* @tparam Al2 The rhs alignment
*
* @return Always false (stateless allocator)
*/
template <typename T1, std::size_t Al1, typename T2, std::size_t Al2>
bool operator!=(const AlignedAllocator<T1, Al1>& lhs,
const AlignedAllocator<T2, Al2>& rhs) noexcept {
return false;
}
/**
* @brief Checks if allocators are the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Al1 The lhs alignment
* @tparam T2 The rhs value type
* @tparam Al2 The rhs alignment
*
* @return Always true (stateless allocator)
*/
template <typename T1, std::size_t Al1, typename T2, std::size_t Al2>
bool operator==(const AlignedAllocator<T1, Al1>& lhs,
const AlignedAllocator<T2, Al2>& rhs) noexcept {
return true;
}
#if defined(__linux__)
/**
* @brief Allocator using anonymous mmap mappings with allocation advices
*
* @tparam T The value type
* @tparam Ad Advice flags
*/
template <typename T, Advice Ad = Advice::normal>
struct AdvisedAllocator {
/* Required typedefs/aliases */
using value_type = T;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::true_type;
/* Constructors */
AdvisedAllocator() = default;
AdvisedAllocator(const AdvisedAllocator& other) = default;
AdvisedAllocator& operator=(const AdvisedAllocator& other) = delete;
template <typename U>
AdvisedAllocator(const AdvisedAllocator<U, Ad>&) noexcept {};
~AdvisedAllocator() = default;
/* Deprecated */
template <class U>
struct rebind {
using other = AdvisedAllocator<U, Ad>;
};
/**
* @brief Allocates memory
*
* @param[in] n The size to allocate
*/
[[nodiscard]] T* allocate(std::size_t n) const {
if (n == 0) { return nullptr; }
if (n > std::numeric_limits<size_type>::max() / sizeof(T)) {
throw bad_alloc(
"AdvisedAllocator failed: requested more bytes than possible.");
}
void* mem =
::mmap(nullptr, n * sizeof(T), PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
if (mem == (void*)(-1))
throw bad_alloc(
fmt::format("AdvisedAllocator failed: mmap failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
/* Advise the kernel about the use of the mmap'ed memory. */
if (::madvise(mem, n * sizeof(T), static_cast<int>(Ad)) != 0)
throw bad_alloc(
fmt::format("AdvisedAllocator failed: madvise failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
if (mem != nullptr) {
return reinterpret_cast<T*>(mem);
} else {
throw bad_alloc("AdvisedAllocator failed: null pointer");
}
}
/**
* @brief Frees memory
*
* @param p The pointer to memory to deallocate
* @param[in] n The size to deallocate
*/
void deallocate(T* p, std::size_t n) const {
::munmap(reinterpret_cast<void*>(p), n);
}
};
/**
* @brief Checks if allocators are not the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Ad2 The rhs advice
*
* @return Always false (stateless allocator)
*/
template <typename T1, Advice Ad1, //
typename T2, Advice Ad2>
bool operator!=(const AdvisedAllocator<T1, Ad1>& lhs,
const AdvisedAllocator<T2, Ad2>& rhs) noexcept {
return false;
}
/**
* @brief Checks if allocators are the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Ad2 The rhs advice
*
* @return Always true (stateless allocator)
*/
template <typename T1, Advice Ad1, //
typename T2, Advice Ad2>
bool operator==(const AdvisedAllocator<T1, Ad1>& lhs,
const AdvisedAllocator<T2, Ad2>& rhs) noexcept {
return true;
}
/**
* @brief Allocator using Linux huge pages facilities
* @details The use of the Advice is optional, but can be helpful if one
* wants to create transparent hugepages (by setting Ad to
* Advice::hugepage), or to advise the kernel about page preloading,
* etc.
*
* @tparam T The value type
* @tparam Ad Allocation advice flags
*/
template <typename T, Advice Ad = Advice::normal>
struct HugePagesAllocator {
/* Required typedefs/aliases */
using value_type = T;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::true_type;
/* Constructors */
HugePagesAllocator() = default;
HugePagesAllocator(const HugePagesAllocator& other) = default;
HugePagesAllocator& operator=(const HugePagesAllocator& other) = delete;
template <typename U>
HugePagesAllocator(const HugePagesAllocator<U, Ad>&) noexcept {};
~HugePagesAllocator() = default;
/* Deprecated */
template <class U>
struct rebind {
using other = HugePagesAllocator<U, Ad>;
};
/**
* @brief Allocates memory
*
* @param[in] n The size to allocate
*/
[[nodiscard]] T* allocate(std::size_t n) const {
if (n == 0) { return nullptr; }
if (n > std::numeric_limits<size_type>::max() / sizeof(T)) {
throw bad_alloc(
"HugePagesAllocator failed: requested more bytes than possible.");
}
void* mem =
::mmap(nullptr, n * sizeof(T), PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_HUGETLB | MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
if (mem == (void*)(-1)) {
throw bad_alloc(
fmt::format("HugePagesAllocator failed: mmap failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
}
if (::madvise(mem, n * sizeof(T), static_cast<int>(Ad))) {
throw bad_alloc(fmt::format(
"HugePagesAllocator failed: madvise failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
}
if (mem != nullptr) {
return reinterpret_cast<T*>(mem);
} else {
fmt::print("NULL\n");
throw bad_alloc("HugePagesAllocator failed: null pointer");
}
}
/**
* @brief Frees memory
*
* @param p The pointer to memory to deallocate
* @param[in] n The size to deallocate
*/
void deallocate(T* p, std::size_t n) const {
::munmap(reinterpret_cast<void*>(p), n);
}
};
/**
* @brief Checks if allocators are not the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Ad2 The rhs advice
*
* @return Always false (stateless allocator)
*/
template <typename T1, Advice Ad1, typename T2, Advice Ad2>
bool operator!=(const HugePagesAllocator<T1, Ad1>& lhs,
const HugePagesAllocator<T2, Ad2>& rhs) noexcept {
return false;
}
/**
* @brief Checks if allocators are the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Ad2 The rhs advice
*
* @return Always true (stateless allocator)
*/
template <typename T1, Advice Ad1, typename T2, Advice Ad2>
bool operator==(const HugePagesAllocator<T1, Ad1>& lhs,
const HugePagesAllocator<T2, Ad2>& rhs) noexcept {
return true;
}
template <typename T, std::size_t Al = alignof(T), Advice Ad = Advice::normal>
struct AdvisedAlignedAllocator {
/* Required typedefs/aliases */
using value_type = T;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::true_type;
/* Constructors */
AdvisedAlignedAllocator() = default;
AdvisedAlignedAllocator(const AdvisedAlignedAllocator& other) = default;
AdvisedAlignedAllocator& operator=(const AdvisedAlignedAllocator& other) =
delete;
template <typename U>
AdvisedAlignedAllocator(
const AdvisedAlignedAllocator<U, Al, Ad>&) noexcept {};
~AdvisedAlignedAllocator() = default;
/* Deprecated */
template <class U>
struct rebind {
using other = AdvisedAlignedAllocator<U, Al, Ad>;
};
/**
* @brief Allocates memory
*
* @param[in] n The size to allocate
*/
[[nodiscard]] T* allocate(std::size_t n) const {
if (n == 0) { return nullptr; }
if (n > std::numeric_limits<size_type>::max() / sizeof(T)) {
throw bad_alloc(
"AdvisedAlignedAllocator failed: requested more bytes than "
"possible.");
}
/* Get aligned storage. */
void* mem = nullptr;
if (::posix_memalign(&mem, Al, n * sizeof(T)))
throw bad_alloc(
fmt::format("AdvisedAlignedAllocator failed: posix_memalign failed "
"with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
if (mem == (void*)(-1))
throw bad_alloc("AdvisedAlignedAllocator failed: bad pointer");
/* Advise the kernel about the use of the mmap'ed memory. */
if (::madvise(mem, n * sizeof(T), static_cast<int>(Ad)) != 0)
throw bad_alloc(fmt::format(
"AdvisedAlignedAllocator failed: madvise failed with error: {}.",
errno != 0 ? std::strerror(errno) : "unknown"));
if (mem != nullptr) {
return reinterpret_cast<T*>(mem);
} else {
throw bad_alloc("AdvisedAlignedAllocator failed: null pointer");
}
}
/**
* @brief Frees memory
*
* @param p The pointer to memory to deallocate
* @param[in] n The size to deallocate (unused)
*/
void deallocate(T* p, std::size_t n) const {
std::free(p);
}
};
/**
* @brief Checks if allocators are not the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Al1 The lhs alignment
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Al1 The rhs alignment
* @tparam Ad2 The rhs advice
*
* @return Always false (stateless allocator)
*/
template <typename T1, std::size_t Al1, Advice Ad1, //
typename T2, std::size_t Al2, Advice Ad2>
bool operator!=(const AdvisedAlignedAllocator<T1, Al1, Ad1>& lhs,
const AdvisedAlignedAllocator<T2, Al2, Ad2>& rhs) noexcept {
return false;
}
/**
* @brief Checks if allocators are the same
*
* @param[in] lhs The left hand side
* @param[in] rhs The right hand side
*
* @tparam T1 The lhs value type
* @tparam Al1 The lhs alignment
* @tparam Ad1 The lhs advice
* @tparam T2 The rhs value type
* @tparam Al2 The rhs alignment
* @tparam Ad2 The rhs advice
*
* @return Always true (stateless allocator)
*/
template <typename T1, std::size_t Al1, Advice Ad1, //
typename T2, std::size_t Al2, Advice Ad2>
bool operator==(const AdvisedAlignedAllocator<T1, Al1, Ad1>& lhs,
const AdvisedAlignedAllocator<T2, Al2, Ad2>& rhs) noexcept {
return true;
}
#endif
} // namespace exot::utilities
<file_sep>/include/exot/utilities/formatting.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/formatting.h
* @author <NAME>
* @brief Utilities for string manipulation and serialisation.
*/
#pragma once
#include <algorithm> // for copy
#include <chrono> // for durations
#include <ratio> // for ratios
#include <sstream> // for stringstream
#include <string> // for std::string
#include <type_traits> // for enable_if
#include <vector> // for variable-size arrays
#include <fmt/format.h> // for formatting strings
#include <exot/utilities/types.h> // for type traits
namespace exot::utilities {
/**
* @brief Splits a string using a delimeter
*
* @param[in] string The string
* @param[in] delimiter The delimiter
*
* @tparam CharT Character type (e.g. char, wchar_t)
*
* @return A vector with the tokenized string
*/
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::vector<std::basic_string<CharT>> split_string(
const std::basic_string<CharT>& string, CharT delimiter) {
using string_type = std::basic_string<CharT>;
string_type token;
std::vector<string_type> tokenised;
std::basic_istringstream<CharT> tstream(string);
while (std::getline(tstream, token, delimiter)) {
tokenised.push_back(token);
}
return tokenised;
}
/**
* @brief Joins a vector of strings into a single delimited string
*
* @param[in] strings The strings
* @param[in] delimiter The delimiter
*
* @tparam CharT Character type used by basic_string
*
* @return The joined string
*/
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::basic_string<CharT> join_strings(
const std::vector<std::basic_string<CharT>>& strings, CharT delimiter) {
std::basic_string<CharT> joined;
bool first{true};
for (const auto& string : strings) {
if (first) {
joined += string;
first = false;
} else {
joined += delimiter + string;
}
}
return joined;
}
/**
* @brief Wraps a string to a desired number of columns
*
* @param[in] to_wrap String to wrap
* @param[in] width The width of the column in characters
* @param[in] indent The indentation of the next lines
*
* @return The wrapped string
*/
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string wrap(const std::basic_string<CharT>& to_wrap, size_t width,
size_t indent = 0) {
std::basic_istringstream<CharT> in(to_wrap);
std::basic_ostringstream<CharT> out;
std::basic_string<CharT> current_word;
size_t current_position{indent};
std::basic_string<CharT> indent_string(indent, CharT{' '});
out << indent_string;
while (in >> current_word) {
if (current_position + current_word.size() > width) {
out << CharT{'\n'} << indent_string;
current_position = indent;
}
out << current_word << ' ';
current_position += current_word.size() + 1;
}
return out.str();
}
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string indent(const std::basic_string<CharT>& to_indent, size_t indent,
bool wrap = true) {
auto lines = split_string(to_indent, CharT{'\n'});
auto indent_string = std::basic_string<CharT>(indent, CharT{' '});
for (auto& line : lines) {
line =
wrap ? exot::utilities::wrap(line, 80, indent) : indent_string + line;
}
return join_strings(lines, CharT{'\n'});
}
/**
* @brief Trim characters at front and back of the string, mostly for
* whitespace.
*
* @param[in] to_trim The string to trim
* @param[in] trim_characters A string with characters to be trimmed
*
* @tparam CharT Character type use by basic_string
* @tparam _ Template helper
*
* @return A trimmed string
*/
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string trim_string(const std::basic_string<CharT>& to_trim,
const std::basic_string<CharT>& trim_characters =
std::basic_string<CharT>{" \t"}) {
const auto front = to_trim.find_first_not_of(trim_characters);
if (front == std::basic_string<CharT>::npos) {
return std::basic_string<CharT>{""};
}
const auto back = to_trim.find_last_not_of(trim_characters);
const auto range = back - front + 1;
return to_trim.substr(front, range);
}
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string trim_string(const std::basic_string<CharT>& to_trim,
const CharT* trim_characters) {
return trim_string(std::forward<decltype(to_trim)>(to_trim),
std::basic_string<CharT>{trim_characters});
}
/**
* @brief Collapse characters present in a string, preferably whitespace.
*
* @param[in] to_collapse The string to collapse
* @param[in] collapse_characters A string with characters to
*
* @tparam CharT The character tupe
* @tparam _ Template helper
*
* @return The collapsed string
*/
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string collapse_string(
const std::basic_string<CharT>& to_collapse,
const std::basic_string<CharT>& fill_characters =
std::basic_string<CharT>{" "},
const std::basic_string<CharT>& collapse_characters =
std::basic_string<CharT>{" \t"}) {
auto output = trim_string(to_collapse, collapse_characters);
auto front = output.find_first_of(collapse_characters);
while (front != std::basic_string<CharT>::npos) {
const auto back = output.find_first_not_of(collapse_characters, front);
const auto range = back - front;
output.replace(front, range, fill_characters);
front = output.find_first_of(collapse_characters,
front + fill_characters.length());
}
return output;
}
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string collapse_string(const std::basic_string<CharT>& to_collapse,
const std::basic_string<CharT>& fill_characters,
const CharT* collapse_characters) {
return collapse_string(
std::forward<decltype(to_collapse)>(to_collapse),
std::forward<decltype(fill_characters)>(fill_characters),
std::basic_string<CharT>{collapse_characters});
}
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string collapse_string(const std::basic_string<CharT>& to_collapse,
const CharT* fill_characters,
const CharT* collapse_characters) {
return collapse_string(std::forward<decltype(to_collapse)>(to_collapse),
std::basic_string<CharT>{fill_characters},
std::basic_string<CharT>{collapse_characters});
}
template <typename CharT, typename _ = std::enable_if_t<is_character_v<CharT>>>
std::string collapse_string(
const std::basic_string<CharT>& to_collapse, const CharT* fill_characters,
const std::basic_string<CharT>& collapse_characters =
std::basic_string<CharT>{" \t"}) {
return collapse_string(
std::forward<decltype(to_collapse)>(to_collapse),
std::basic_string<CharT>{fill_characters},
std::forward<decltype(collapse_characters)>(collapse_characters));
}
/**
* @brief Extract the first occurence of a positive number from a string
*
* @param[in] string The string
*
* @return The extracted number
*/
inline unsigned extract_number(const std::string& string) {
std::string extracted;
size_t const f = string.find_first_of("0123456789");
if (f != std::string::npos) {
size_t const e = string.find_first_not_of("0123456789", f);
extracted = string.substr(f, e != std::string::npos ? e - f : e);
}
if (!extracted.empty()) {
/* A string-to-integer conversion for unsigned numbers seems to exist only
* for unsigned long data type */
return static_cast<unsigned>(std::stoul(extracted));
} else {
throw std::logic_error(fmt::format(
"Extraction failed, the string {} does not contain a number.", string));
}
}
/**
* @brief Extract the all occurences of positive numbers from a string
*
* @param[in] in The string
*
* @return The extracted number
*/
inline std::vector<unsigned> extract_numbers(const std::string& in) {
size_t f = 0;
size_t e = 0;
std::string string{in};
std::vector<unsigned> numbers;
while (true) {
std::string extracted;
f = string.find_first_of("0123456789");
if (f != std::string::npos) {
e = string.find_first_not_of("0123456789", f);
extracted = string.substr(f, e != std::string::npos ? e - f : e);
if (!extracted.empty()) {
numbers.push_back(static_cast<unsigned>(std::stoul(extracted)));
} else {
throw std::logic_error(fmt::format(
"Extraction failed, the string {} does not contain a number.",
string));
}
if (e == std::string::npos) {
break;
} else {
string = string.substr(e);
}
} else {
break;
}
};
return numbers;
}
/**
* @brief Helper function for obtaining an unsigned number from a
* hexadecimal string notation, also without the leading '0x'.
*
* @param[in] str The string
*
* @return The converted value
*/
inline unsigned read_hex_value(const std::string& string) {
unsigned x;
std::stringstream ss;
ss << std::hex << string;
ss >> x;
return x;
}
namespace details {
/**
* A hack to allow constructing ratio strings at compile time
*/
template <char Pre, char Post, char Sep, std::intmax_t Num, std::intmax_t Den>
static const auto ratio_string = fmt::format("{}{}{}{}{}", Pre, Num, Sep, Den,
Post);
} // namespace details
/**
* @brief Get a string description of a ratio
* @details The SI unit prefixes of {yocto, zepto, zetta, yotta} cannot yet
* be represented in any of the standard built-in types (value
* exceeds size limit).
*
* @param[in] ratio The ratio
*
* @tparam Num Value of the numerator
* @tparam Den Value of the denominator
*
* @return A string with the SI prefix
*/
template <std::intmax_t Num, std::intmax_t Den>
std::string ratio_to_string(std::ratio<Num, Den> ratio) noexcept {
/* SI prefixes */
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::atto>)
return "a";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::femto>)
return "f";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::pico>)
return "p";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::nano>)
return "n";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::micro>)
return "µ";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::milli>)
return "m";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::centi>)
return "c";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::deci>)
return "d";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::deca>)
return "da";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::hecto>)
return "h";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::kilo>)
return "k";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::mega>)
return "M";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::giga>)
return "G";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::tera>)
return "T";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::peta>)
return "P";
if constexpr (std::is_same_v<std::decay_t<decltype(ratio)>, std::exa>)
return "E";
if constexpr (Num == 1 && Den == 1) return "";
/* Catch-all */
return details::ratio_string<'[', ']', '/', Num, Den>;
}
/**
* @brief Get a unit prefix of a duration period
*
* @param[in] duration The duration
*
* @tparam Rep Type used to store the duration
* @tparam Period The duration period
*
* @return Time unit string with prefixes
*/
template <typename Rep, typename Period>
std::string duration_unit(std::chrono::duration<Rep, Period>) {
if constexpr (Period::num == 60 && Period::den == 1) return "min";
if constexpr (Period::num == 3600 && Period::den == 1) return "h";
return ratio_to_string(Period{}) + "s";
};
/**
* @brief Print a duration with its unit
*
* @param[in] duration The duration
*
* @tparam Rep Type used to store the duration
* @tparam Period The duration period
*
* @return String with the duration and its unit with prefixes
*/
template <typename Rep, typename Period>
std::string duration_to_string(std::chrono::duration<Rep, Period> duration) {
return std::to_string(duration.count()) + duration_unit(duration);
}
namespace details {
/**
* @brief Prefix, postfix, and delimeter used in serialising ranges.
* @details Characters can be chosen individually for different types,
* using the type trait functions from <type_traits> or "types.h".
*
* @tparam CharT Character type (e.g. char, wchar_t)
* @tparam T Range type
* @tparam Enable Used for `std::enable_if`-based polymorphism
*/
template <typename CharT, class T, typename Enable = void>
struct Separators {
const CharT prefix;
const CharT postfix;
const CharT delimeter;
constexpr Separators() : prefix{'\0'}, postfix{'\0'}, delimeter{','} {};
};
template <typename CharT, class T>
struct Separators<CharT, T,
typename std::enable_if_t<is_iterable_v<T>>::value> {
const CharT prefix;
const CharT postfix;
const CharT delimeter;
constexpr Separators() : prefix{'\0'}, postfix{'\0'}, delimeter{','} {};
};
template <typename CharT, class T>
struct Separators<CharT, T,
typename std::enable_if_t<is_const_iterable_v<T>>::value> {
const CharT prefix;
const CharT postfix;
const CharT delimeter;
constexpr Separators() : prefix{'\0'}, postfix{'\0'}, delimeter{','} {};
};
template <typename CharT, class T>
struct Separators<CharT, T, typename std::enable_if_t<is_tuple_v<T>>::value> {
const CharT prefix;
const CharT postfix;
const CharT delimeter;
constexpr Separators() : prefix{'\0'}, postfix{'\0'}, delimeter{','} {};
};
} // namespace details
} // namespace exot::utilities
<file_sep>/src/meters/thermal_sysfs.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/thermal_sysfs.cpp
* @author <NAME>
* @brief Implementation of the sysfs thermal metering module.
*/
#if defined(__linux__)
#include <exot/meters/thermal_sysfs.h>
namespace exot::modules {
thermal_sysfs::thermal_sysfs(settings& conf) : conf_{conf} {
std::string dir{"/sys/devices/virtual/thermal"};
std::string regex{".*zone\\d+/temp$"}; //! regular expression that matches
//! valid thermal zone access files
filenames_ = exot::utilities::grep_directory_r(dir, regex);
/* Since thermal zones are counted from 0, (size - 1) should provide the
* last available zone. */
auto max_zone = filenames_.size() - 1;
if (!conf_.zones.empty()) {
/* If zones have been provided via CLI...
* Sort and remove duplicate zones. */
std::sort(conf_.zones.begin(), conf_.zones.end());
conf_.zones.erase(std::unique(conf_.zones.begin(), conf_.zones.end()),
conf_.zones.end());
/* If any of the provided zones are not available... */
if (std::any_of(conf_.zones.begin(), conf_.zones.end(), [=](unsigned zone) {
auto larger = zone > max_zone;
if (larger)
debug_log_->warn("Thermal zone {} is not available.", zone);
return larger;
})) {
/* Limit the zones vector to available zones. */
conf_.zones.erase(
std::find_if(conf_.zones.begin(), conf_.zones.end(),
[max_zone](unsigned zone) { return zone > max_zone; }),
conf_.zones.end());
}
filenames_ = {};
for (auto zone : conf_.zones) {
filenames_.emplace_back(fmt::format(
"/sys/devices/virtual/thermal/thermal_zone{}/temp", zone));
}
} else {
/* ...otherwise, initialise zones vector to available zones. */
conf_.zones.resize(filenames_.size());
std::iota(conf_.zones.begin(), conf_.zones.end(), 0);
}
debug_log_->info("[thermal_sysfs] using zones: {}", conf_.zones);
readings_.resize(filenames_.size());
if (!exot::utilities::all_readable(filenames_))
throw std::logic_error("At least one thermal zone is not readable.");
}
typename thermal_sysfs::return_type thermal_sysfs::measure() {
for (decltype(filenames_.size()) i = 0; i < filenames_.size(); ++i) {
std::ifstream zone(filenames_.at(i));
unsigned int value;
zone >> value;
readings_.at(i) = (value > 1000) ? static_cast<float>(value) / 1000
: static_cast<float>(value);
zone.close();
}
return readings_;
}
std::vector<std::string> thermal_sysfs::header() {
std::vector<std::string> description;
for (auto zone : conf_.zones) {
description.push_back(exot::utilities::generate_header(
conf_.name(), "zone", zone, DefaultUnits::temperature));
}
return description;
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/primitives/x86_64.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/x86_64.h
* @author <NAME>
* @brief Low-level functions relevant on IA-64 architectures.
*/
#pragma once
#if defined(__x86_64__)
#include <array> // for fixed-size arrays
#include <cstdint> // for std::uint*
namespace exot::primitives {
inline namespace x86_64 {
/**
* @brief Access the CPUID instruction
*
* @param[in] eax The initial eax register value
* @param[in] ecx The initial ecx register value (rarely used)
*
* @return An array of register values eax, ebx, ecx, edx, holding the
* result of the CPUID instruction
*/
std::array<std::uint32_t, 4> cpuid(std::uint32_t eax, std::uint32_t ecx = 0);
/**
* @brief Get the logical affinity of the current thread
* @details The value returned in CPUID.0BH:EDX reports the "2APIC ID of the
* current logical processor" ID, see Extended Topology Enumeration
* Leaf in
* "Intel® 64 and IA-32 Architectures Software Developer’s Manual",
* Volume 2, September 2016, p. 3-195.
*
* The lower 16 bits hold the id of the logical processor in a
* cluster.
*
* @return The logical core on which the current thread is running
*/
unsigned int logical_id();
/**
* @brief Get the cluster ID of the current thread
* @details The upper 16 bits hold the cluster id.
*
* @return The id of the cluster on which the current thread is running
*/
unsigned int cluster_id();
/**
* @brief Get the number of logical processors per physical core
* @details The value reported in CPUID.0BH:EBX states the number of logical
* processors per core/level.
*
* @return The number of logical processors per core
*/
unsigned int logical_processors_per_core();
} // namespace x86_64
} // namespace exot::primitives
#endif
<file_sep>/include/exot/utilities/logging.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/logging.h
* @author <NAME>
* @brief Main logging configuration class.
*/
#pragma once
#include <optional>
#include <string>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/time.h>
#include <spdlog/spdlog.h>
#include <exot/utilities/configuration.h> // for configurable
namespace exot::utilities {
/**
* @brief Appends a string to the filename.
*
* @param file_path The file path
* @param[in] to_append To string to append
*/
void append_to_filename(std::string& file_path, const std::string& to_append);
/**
* @brief Appends a timestamp to a filename.
*
* @param file_path The path to the file
*/
void append_timestamp_to_filename(std::string& file_path);
/**
* @brief Class that encapsulates all logging options and is responsible
* for creating loggers.
*/
class Logging {
public:
using logger_pointer = std::shared_ptr<spdlog::logger>;
struct settings : public exot::utilities::configurable<settings> {
std::optional<std::string> debug_log_filename;
std::optional<std::string> app_log_filename;
spdlog::level::level_enum log_level{spdlog::level::info};
size_t async_size{1024 * 8};
bool async{false};
size_t async_thread_count{1};
bool timestamp_files{false};
bool rotating_logs{false};
bool provide_platform_identification{true};
bool append_governor_to_files{false};
size_t rotating_logs_size{1024 * 1024 * 100}; /* 100 MiB */
size_t rotating_logs_count{10};
const char* name() const { return "logging"; }
/* @brief The JSON configuration function */
void configure() {
bind_and_describe_data("debug_log_filename", debug_log_filename,
"the debug log filename |str|, optional");
bind_and_describe_data("app_log_filename", app_log_filename,
"the app log filename |str|, optional");
bind_and_describe_data(
"log_level", log_level,
"the log level |str|, one of \"trace\", \"debug\", "
"\"info\", \"warn\", \"err\", \"critical\", \"off\"");
bind_and_describe_data("async_size", async_size,
"async logger buffer size |uint|, power of 2");
bind_and_describe_data("async", async, "use the async logger? |bool|");
bind_and_describe_data("async_thread_count", async_thread_count,
"async logger thread count |uint|");
bind_and_describe_data("timestamp_files", timestamp_files,
"should timestamp the log files? |bool|");
bind_and_describe_data("rotating_logs", rotating_logs,
"should rotate the logs? |bool|");
bind_and_describe_data("provide_platform_identification",
provide_platform_identification,
"should provide platform info? |bool|");
bind_and_describe_data(
"append_governor_to_files", append_governor_to_files,
"should append the frequency governor to filenames? |bool|");
bind_and_describe_data("rotating_logs_size", rotating_logs_size,
"the size of rotating logs in MiB |uint|");
bind_and_describe_data(
"rotating_logs_count", rotating_logs_count,
"the maximum number of rotating logs to keep |uint|");
}
};
Logging(settings& conf);
private:
settings conf_;
};
} // namespace exot::utilities
<file_sep>/include/exot/primitives/tsc.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/tsc.h
* @author <NAME>
* @brief Wrapper for accessing the time stamp counter.
*/
#pragma once
#include <cstdint> // for uint*
#include <type_traits> // for type traits
namespace exot::primitives {
/**
* @brief Base class for timestamp counters
*/
struct TimeStampCounter {};
/**
* @brief Is the provided type a time stamp counter?
*
* @tparam T A type to check
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_time_stamp_counter : public std::false_type {};
template <typename T>
struct is_time_stamp_counter<T,
std::void_t<decltype(T::start), decltype(T::stop)>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_time_stamp_counter_v = is_time_stamp_counter<T>::value;
#ifdef __x86_64__
inline namespace x86_64 {
/**
* @brief Wrapper for time-measurement functions accessing the time stamp
* counter
* @details The functions use the improved benchmarking method outlined in
* <NAME>., "How to Benchmark Code Execution Times on Intel®
* IA-32 and IA-64 Instruction Set Architectures", Intel
* Corporation, September 2010.
*
* The difficulty in using the time stamp counter for profiling and
* doing high precision time measurement arises from the fact that
* in out-of-order execution these functions are not guaranteed to
* execute before/after the code to be profiled/measured.
*
* With the instructions `cpuid` and `rdtscp` we obtain guarantees
* that all previous instructions have been executed before the time
* stamp counter is read.
*/
struct SerialisingTSC : TimeStampCounter {
/**
* @brief Performs the first read operation from time stamp counter
*
* @return The value of the time stamp counter
*/
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"cpuid # EXOT->tsc \n\t" //
"rdtsc # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return (std::uint64_t)high << 32 | (std::uint64_t)low;
}
/**
* @brief Performs the subsequent read operation from the time stamp
* counter
*
* @return The value of the time stamp counter
*/
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return (std::uint64_t)high << 32 | (std::uint64_t)low;
}
};
/**
* @brief Simple TSC without cpuid serialisation
*/
struct SimpleTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"rdtsc # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return (std::uint64_t)high << 32 | (std::uint64_t)low;
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
/**
* @brief Serialising TSC wrapped in load fences
*/
struct LoadFencedTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"lfence # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"rdtsc # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"lfence # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
/**
* @brief Serialising TSC wrapped in memory fences
*/
struct MemoryFencedTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"rdtsc # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"mfence # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
/**
* @brief Serialising TSC used in prefetch exot channel
*/
struct MemoryFencedPrefetchTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"cpuid # EXOT->tsc \n\t" //
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"mfence # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
/**
* @brief Serialising TSC used in flush-flush exot channel
*/
struct MemoryFencedFlushTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"rdtscp # EXOT->tsc \n\t" //
"mfence # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"rdtscp # EXOT->tsc \n\t" //
"mfence # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
/**
* @brief Another serialising TSC used in flush-flush exot channel
*/
struct MemoryFencedSerialisingFlushTSC : TimeStampCounter {
static inline __attribute__((always_inline)) std::uint64_t start() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"rdtsc # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"mfence # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
static inline __attribute__((always_inline)) std::uint64_t stop() {
std::uint32_t low, high;
asm volatile(
"mfence # EXOT->tsc \n\t" //
"rdtscp # EXOT->tsc \n\t" //
"movl %%eax, %0 # EXOT->tsc \n\t" //
"movl %%edx, %1 # EXOT->tsc \n\t" //
"cpuid # EXOT->tsc \n\t" //
"mfence # EXOT->tsc " //
: "=r"(low), "=r"(high) // output
: // input
: "%rax", "%rbx", "%rcx", "%rdx"); // clobber
return static_cast<std::uint64_t>(high) << 32 |
static_cast<std::uint64_t>(low);
}
};
} // namespace x86_64
#endif
} // namespace exot::primitives
<file_sep>/include/exot/generators/base_bitset.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/base_bitset.h
* @author <NAME>
* @brief Generator base class using the bitset parsing method.
*/
#pragma once
#include <atomic>
#include <bitset>
#include <set>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/ostream.h>
namespace exot::modules {
/**
* @brief The bitset generator base class.
* @note Many generators share the same input interface: the activation is
* "binary", and determined by a bit value set on an unsigned
* number.
*/
struct bitset_generator_base {
using subtoken_type = unsigned; // converted to bitset
using core_type = unsigned; // core number
using decomposed_type = bool; // determines if thread will be busy
using index_type = std::size_t; // thread index
using enable_flag_type = std::atomic_bool;
using logger_pointer = std::shared_ptr<spdlog::logger>;
struct settings : public exot::utilities::configurable<settings> {
std::set<unsigned> cores;
const char* name() const { return "generator"; }
void configure() {
bind_and_describe_data(
"cores", cores, "cores to run workers on |uint[]|, e.g. [1, 2, 3]");
}
};
explicit bitset_generator_base(settings& conf) : conf_{conf} {
SPDLOG_LOGGER_DEBUG(logger_, "[generator] cores: {}", conf_.cores);
}
inline decomposed_type decompose_subtoken(const subtoken_type& subtoken,
core_type core, index_type index) {
bitset_ = subtoken;
SPDLOG_LOGGER_TRACE(logger_,
"[generator->decompose_subtoken] c: {}, i: {} -> "
"decomposed subtoken: {}, enable: {}",
core, index, subtoken, bitset_[index]);
return static_cast<bool>(bitset_[index]);
}
inline bool validate_subtoken(const subtoken_type& subtoken) {
static unsigned int validator = conf_.cores.size() > 0
? (1 << conf_.cores.size()) - 1
: std::numeric_limits<unsigned>::max();
return subtoken <= validator;
}
/**
* @note Must be implemented by inheriting classes.
*/
virtual inline void generate_load(const decomposed_type& decomposed_subtoken,
const enable_flag_type& flag,
core_type core, index_type index) = 0;
protected:
std::bitset<16> bitset_;
settings conf_;
logger_pointer logger_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
} // namespace exot::modules
<file_sep>/include/exot/framework/queue.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/queue.h
* @author <NAME>
* @brief Thread-safe queues with and without timeouts, used for
* communicating between process network nodes.
*/
#pragma once
#include <chrono> // for time_point and duration
#include <condition_variable> // for std::condition_variable
#include <limits> // for getting upper capacity limit
#include <mutex> // for mutexes
#include <queue> // for underlying queue container
/**
* For debugging with a console
*/
#ifdef DEBUG_INTERACTIVE
#include <fmt/format.h> // for formatting strings
/**
* @brief Print debugging info
*
* @param[in] function Pass the __FUNCTION__ via this parameter
* @param[in] message The message to print
*/
inline void queue_debug_print(const char* function, const char* message) {
fmt::print("[queue] [{}] {}\n", function, message);
}
#define DEBUG_queue(function, message) queue_debug_print(function, message)
#else
#define DEBUG_queue(function, message)
#endif
namespace exot::framework {
/**
* @brief Thread-safe bounded queue
* @details The queue provides a thread-safe queue suitable for concurrent
* producer-consumer application scenarios. The queue utilises two
* condition variables, which allow threads operating on the queue
* to efficiently wait on empty/full queue.
*
* Threads pushing values onto the queue wait until the queue is
* writeable, and notify threads waiting to pop a value.
*
* Threads popping values from the queue wait if the queue is empty,
* and notify threads waiting on a full queue.
*
* By default the queue is effectively unbounded, with the default
* capacity being the upper limit of the system-specific `size_t`
* type.
*
* @tparam Token Data type stored in the queue.
* @tparam Mutex Mutex type
* @tparam CV Condition variable type
*/
template <typename Token, typename Mutex = std::mutex,
typename CV = std::condition_variable>
class LockingQueue {
public:
using value_type = Token;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = size_t;
using container = std::queue<value_type>;
using mutex_type = Mutex;
using cv_type = CV;
static const size_type default_capacity{
std::numeric_limits<size_type>::max()};
LockingQueue(size_type capacity) : capacity_{capacity} {};
LockingQueue() : LockingQueue(default_capacity){};
/**
* Copy operations/constructors not required and/or not meaningful.
*/
LockingQueue(const LockingQueue& other) = delete;
LockingQueue(LockingQueue&& other) = default;
LockingQueue& operator=(const LockingQueue& other) = delete;
LockingQueue& operator=(LockingQueue&& other) = default;
/**
* Virtual destructor necessary if the class is going to be subclassed.
*/
virtual ~LockingQueue() = default;
/**
* @brief Locking wrapped for front()
*
* @return A reference to the front item in the queue.
*/
reference front() {
/**
* @brief Unique lock in conjunction with a condition variable allow
* blocking until a token is available in the queue. */
std::unique_lock<mutex_type> lock(queue_mutex_);
/* The wait statement in the CV is somewhat equivalent to
*
* @code{C++}
* while(!predicate()) {
* lock.lock();
* }
* @endcode
*
* The CV will be notified when a value is pushed onto the queue. */
queue_empty_cv_.wait(lock, [this] { return !empty_(); });
return queue_.front();
}
/**
* @brief Locking wrapper for pop()
*/
void pop() {
{
std::unique_lock<mutex_type> lock(queue_mutex_);
/// Cannot pop an empty queue.
DEBUG_queue(__FUNCTION__, "locked, waiting on empty ...");
queue_empty_cv_.wait(lock, [this] { return !empty_(); });
DEBUG_queue(__FUNCTION__, "was notified or condition set, empty...");
queue_.pop();
}
/* Send a 'notification' via the CV to those waiting on a full queue. */
DEBUG_queue(__FUNCTION__, "will notify waiting on full!");
notify_waiting_on_full_();
}
/**
* @brief Locking wrapper for push() (via reference)
*
* @param[in] value Token to push onto the queue.
*/
void push(const_reference value) {
{
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
queue_full_cv_.wait(lock, [this] { return !full_(); });
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.push(value);
}
/* Send a 'notification' via the CV to those waiting on an empty queue. */
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
}
/**
* @brief Locking wrapper for push() (via move)
*
* @param[in] value Token to push onto the queue.
*/
void push(value_type&& value) {
{
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
queue_full_cv_.wait(lock, [this] { return !full_(); });
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.push(std::forward<decltype(value)>(value));
}
/* Send a 'notification' via the CV to those waiting on an empty queue. */
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
}
/**
* @brief Locking wrapper for emplace().
* @details Constructs an element in place, without copying/moving.
*
* @tparam Args Forwarded arguments to the constructor of Token. */
template <class... Args>
decltype(auto) emplace(Args&&... args) {
{
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
queue_full_cv_.wait(lock, [this] { return !full_(); });
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.emplace(std::forward<Args>(args)...);
}
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
}
/**
* @brief Locking wrapper for empty()
* @details The attribute specified `[[nodiscard]]` instructs the compiler
* to issue a warning if the function's return value is used in a
* discarded-value expression (C++ Standard [dcl.attr.nodiscard]
* "10.6.8 Nodiscard attribute"). Essentially it means that the
* function's return value should not be ignored.
*
* The function has no side effects.
*
* @return Returns true if empty.
*/
[[nodiscard]] bool empty() {
std::lock_guard<mutex_type> lg(queue_mutex_);
return empty_();
}
/**
* @brief Checks if queue is full.
* @details The function has no side effects.
*
* @return Returns true if full
*/
[[nodiscard]] bool full() {
std::lock_guard<mutex_type> lg(queue_mutex_);
return full_();
}
/**
* @brief Locking wrapper for size()
* @details In concurrent queue access the size is only approximate,
* unless a mechanism is provided to lock the queue for after
* the size() operation.
*
* @return Number of elements in the queue.
*/
size_type size() {
std::lock_guard<mutex_type> lg(queue_mutex_);
return queue_.size();
}
/**
* @brief Returns the capacity of the queue.
*
* @return The capacity of the queue.
*/
size_type capacity() const { return capacity_; }
protected:
container queue_; //! Underlying queue container
mutex_type queue_mutex_; //! Mutex protecting operations on the container
cv_type queue_empty_cv_; //! Condition variable for waiting on empty
cv_type queue_full_cv_; //! Condition variable for waiting on full
size_type capacity_; //! Capacity of the queue
/**
* @brief Non-thread-safe check if underlying container is equal or
* exceeds the desired capacity
*
* @return True if underlying container's size is less than capacity
*/
inline bool full_() const { return queue_.size() >= capacity_; }
/**
* @brief Non-thread-safe check if underlying container is empty.
*
* @return True if underlying container is empty
*/
inline bool empty_() const { return queue_.empty(); }
/**
* @brief Wrapper for nofitying threads waiting on a full queue
*/
inline void notify_waiting_on_full_() { queue_full_cv_.notify_one(); }
/**
* @brief Wrapper for notifying threads waiting on an empty queue
*/
inline void notify_waiting_on_empty_() { queue_empty_cv_.notify_one(); }
};
/**
* @brief Concurrent locking queue with timeout functionality
* @details Extends the locking queue with try_{pop,push}_{,for,until}
* operations, which provide extended functionality and new
* opportunities for structuring program flow and preventing
* deadlocks.
*
* @tparam Token Data type stored in the queue.
* @tparam Mutex Mutex type used for locking.
* @tparam CV Condition variable type used for notifying.
*/
template <typename Token, typename Mutex = std::mutex,
typename CV = std::condition_variable>
class TimeoutLockingQueue : public LockingQueue<Token, Mutex, CV> {
public:
/**
* Since base class is a class template, typedefs cannot be simply
* 'inherited'. For details, see C++ standard [temp.dep]/3 ("17.7.2 Dependent
* names"), which states that in "the definition of a class or class template,
* the scope of a dependent base class is not examined during unqualified name
* lookup either at the point of definition of the class template or member or
* during an instantiation of the class template or member."
*/
using value_type = typename LockingQueue<Token, Mutex, CV>::value_type;
using reference = typename LockingQueue<Token, Mutex, CV>::reference;
using const_reference =
typename LockingQueue<Token, Mutex, CV>::const_reference;
using size_type = typename LockingQueue<Token, Mutex, CV>::size_type;
using container = typename LockingQueue<Token, Mutex, CV>::container;
using mutex_type = typename LockingQueue<Token, Mutex, CV>::mutex_type;
using cv_type = typename LockingQueue<Token, Mutex, CV>::cv_type;
/**
* Use the base class' constructor.
*/
using LockingQueue<Token, Mutex, CV>::LockingQueue;
/**
* Since base class is a class template, also the protected members cannot be
* directly accessed as in the case of simple inheritance.
*/
using LockingQueue<Token, Mutex, CV>::queue_;
using LockingQueue<Token, Mutex, CV>::queue_mutex_;
using LockingQueue<Token, Mutex, CV>::queue_empty_cv_;
using LockingQueue<Token, Mutex, CV>::queue_full_cv_;
/**
* Same declarations are necessary for base class member functions.
*/
using LockingQueue<Token, Mutex, CV>::push;
using LockingQueue<Token, Mutex, CV>::full_;
using LockingQueue<Token, Mutex, CV>::empty_;
using LockingQueue<Token, Mutex, CV>::notify_waiting_on_empty_;
using LockingQueue<Token, Mutex, CV>::notify_waiting_on_full_;
virtual ~TimeoutLockingQueue() = default;
/**
* Copy and move operations/constructors not required and not /
* meaningful. */
TimeoutLockingQueue(const TimeoutLockingQueue& other) = delete;
TimeoutLockingQueue(TimeoutLockingQueue&& other) noexcept = delete;
TimeoutLockingQueue& operator=(const TimeoutLockingQueue& other) = delete;
TimeoutLockingQueue& operator=(TimeoutLockingQueue&& other) = delete;
/**
* @brief Pop a value if the queue is not empty
* @details Unlike `pop()`, this function will never block on an empty
* queue.
*
* This function is preferred to the 'traditional' sequence of
* operations `front()` and `pop()`, bacause it does not require
* the lock to be held twice.
*
* If the queue is empty, the function has no side effects, i.e.
* it will not modify the underlying container.
*
* @param value The value to pop
*
* @return true if succeeded, false if queue is empty.
*/
bool try_pop(reference value) {
{
std::lock_guard<mutex_type> lg(queue_mutex_);
if (empty_()) { return false; }
value = queue_.front();
queue_.pop();
/* Lock guard destroyed after leaving this scope, releasing the lock. */
}
DEBUG_queue(__FUNCTION__, "will notify waiting on full!");
notify_waiting_on_full_();
return true;
}
/**
* @brief Tries to pop a value with a timeout
* @details This and the following functions use the functionality provided
* by the condition variable, which allows waiting on the lock
* only for a specified duration.
*
* @param value The value to pop
* @param[in] timeout Timeout duration
*
* @tparam Rep Storage type used for std::chrono::duration
* @tparam Period Period type used for std::chrono::duration
* (std::ratio)
*
* @return true if could pop within the timeout duration, otherwise false.
*/
template <typename Rep, typename Period>
bool try_pop_for(reference value,
const std::chrono::duration<Rep, Period>& timeout) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on empty...");
/* Wait on an empty queue. */
if (queue_empty_cv_.wait_for(lock, timeout, [this] { return !empty_(); })) {
value = queue_.front();
queue_.pop();
/* Release the lock before notifying waiting threads. */
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on full!");
notify_waiting_on_full_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
/**
* @brief Tries to pop a value until some time point is reached
*
* @param value The value to pop
* @param[in] time Timeout time point
*
* @tparam Clock Clock type used for the time point
* @tparam Duration Duration type used for the time point
*
* @return true if could pop before the time point, otherwise false.
*/
template <typename Clock, typename Duration>
bool try_pop_until(reference value,
const std::chrono::time_point<Clock, Duration>& time) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on empty...");
if (queue_empty_cv_.wait_until(lock, time, [this] { return !empty_(); })) {
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
value = queue_.front();
queue_.pop();
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on full!");
notify_waiting_on_full_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
/**
* Push operations via const reference
*/
/**
* @brief Tries to push a value unless the queue is full
*
* @param[in] value The value to push
*
* @return true if queue was not full and the value was pushed, false
* otherwise.
*/
inline bool try_push(const_reference value) {
{
std::lock_guard<mutex_type> lg(queue_mutex_);
if (full_()) { return false; }
queue_.push(value);
}
notify_waiting_on_empty_();
return true;
}
/**
* @brief Tries to push a value with a timeout
*
* @param[in] value The value to push
* @param[in] timeout The timeout duration
*
* @tparam Rep Storage type used for std::chrono::duration
* @tparam Period Period type used for std::chrono::duration
* (std::ratio)
*
* @return true if could push within the timeout duration, otherwise
* false.
*/
template <typename Rep, typename Period>
inline bool try_push_for(const_reference value,
const std::chrono::duration<Rep, Period>& timeout) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
if (queue_full_cv_.wait_for(lock, timeout, [this] { return !full_(); })) {
DEBUG_queue(__FUNCTION__, "was notified or condition set,...");
queue_.push(value);
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
/**
* @brief Tries to push a value until some time point is reached
*
* @param value The value to push
* @param[in] time Timeout time point
*
* @tparam Clock Clock type used for the time point
* @tparam Duration Duration type used for the time point
*
* @return true if could push before the time point, otherwise false.
*/
template <typename Clock, typename Duration>
inline bool try_push_until(
const_reference value,
const std::chrono::time_point<Clock, Duration>& time) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
if (queue_full_cv_.wait_until(lock, time, [this] { return !full_(); })) {
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.push(value);
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
/**
* Push operations via move
*/
/**
* @brief Tries to push a value unless the queue is full via a move
* operation
*
* @param[in] value The value to push
*
* @return true if queue was not full and the value was pushed, false
* otherwise.
*/
inline bool try_push(value_type&& value) {
{
std::lock_guard<mutex_type> lg(queue_mutex_);
if (full_()) { return false; }
queue_.push(std::move(value));
}
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
return true;
}
/**
* @brief Tries to push a value with a timeout via a move operation
*
* @param[in] value The value to push
* @param[in] timeout The timeout duration
*
* @tparam Rep Storage type used for std::chrono::duration
* @tparam Period Period type used for std::chrono::duration
* (std::ratio)
*
* @return true if could push within the timeout duration, otherwise
* false.
*/
template <typename Rep, typename Period>
inline bool try_push_for(value_type&& value,
const std::chrono::duration<Rep, Period>& timeout) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
if (queue_full_cv_.wait_for(lock, timeout, [this] { return !full_(); })) {
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.push(std::move(value));
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
/**
* @brief Tries to push a value until some time point is reached via a
* move operation
*
* @param[in] time Timeout time point
* @param value The value to push
*
* @tparam Clock Clock type used for the time point
* @tparam Duration Duration type used for the time point
*
* @return true if could push before the time point, otherwise false.
*/
template <typename Clock, typename Duration>
inline bool try_push_until(
value_type&& value,
const std::chrono::time_point<Clock, Duration>& time) {
std::unique_lock<mutex_type> lock(queue_mutex_);
DEBUG_queue(__FUNCTION__, "locked, waiting on full...");
if (queue_full_cv_.wait_until(lock, time, [this] { return !full_(); })) {
DEBUG_queue(__FUNCTION__, "was notified or condition set...");
queue_.push(std::move(value));
lock.unlock();
DEBUG_queue(__FUNCTION__, "will notify waiting on empty!");
notify_waiting_on_empty_();
return true;
} else {
DEBUG_queue(__FUNCTION__, "timed out!");
return false;
}
}
};
#ifdef EXOT_USE_FIBERS
#include <boost/fiber/all.hpp>
/**
* Since the node interface type accepts the container as a template-template
* parameter, these aliases are required, because the only type passed to the
* template-template parameter is the token type.
*
* The aliases below use the userspace thread mutexes and condition variables,
* instead of those in the STL.
*/
template <typename Token>
using FiberLockingQueue = LockingQueue<Token, boost::fibers::mutex,
boost::fibers::condition_variable>;
template <typename Token>
using FiberTimeoutLockingQueue =
TimeoutLockingQueue<Token, boost::fibers::mutex,
boost::fibers::condition_variable>;
#endif
} // namespace exot::framework
<file_sep>/src/utilities/filesystem.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/filesystem.cpp
* @author <NAME>
* @brief Implementation of the filesystem listing and access utilities
* from @ref filesystem.h.
*/
#include <exot/utilities/filesystem.h>
#if __has_include(<dirent.h>)
std::vector<std::string> exot::utilities::list_directory(
const std::string& directory) {
DIR* current_directory;
struct dirent* entry;
std::vector<std::string> output;
if ((current_directory = opendir(directory.c_str())) != NULL) {
/* print all the files and directories within directory */
while ((entry = readdir(current_directory)) != NULL) {
output.push_back(directory + ((directory.back() != '/') ? "/" : "") +
std::string(entry->d_name));
}
closedir(current_directory);
} else {
throw std::logic_error("Could not access the directory");
}
std::sort(output.begin(), output.end());
return output;
}
std::vector<std::string> exot::utilities::grep_directory(
const std::string& directory, const std::string& regex) {
std::vector<std::string> list = list_directory(directory);
std::regex matcher(regex);
list.erase(std::remove_if(list.begin(), list.end(),
[&matcher](std::string element) -> bool {
return !std::regex_match(element, matcher);
}),
list.end());
std::sort(list.begin(), list.end());
return list;
}
#endif
#if __has_include(<ftw.h>)
std::vector<std::string> exot::utilities::list_directory_r(
const std::string& directory, Symlinks symlinks) {
/* @note Why are the variables below declared static and why unique
* pointers to them are created?
*
* This 'trick' is required to make it possible for the lambda to be passed as
* function pointer to the `nftw` function. Not all closure types can
* converted or statically casted to a pointer to a function. Specifically,
* the C++ standard states [expr.prim.lambda.closure:7] that "The closure type
* for a non-generic lambda-expression with no lambda-capture whose
* constraints (if any) are satisfied has a conversion function to pointer to
* function with C++ language linkage having the same parameter and return
* types as the closure type's function call operator."
*
* Therefore it is not possible to directly use a capturing lambda with a
* C-like function pointer. While a wrapper, and even a generic wrapper can be
* provided via a trick where we define a static lambda without captures that
* forwards same arguments to the capturing lambda, it is more straightforward
* to declare variables to have static storage duration instead of capturing.
* However, to achieve the expected original behaviour of we would need to
* reset the static variable to its original value upon every function entry.
* Below, we declare as static only a unique pointer to a type, and assign it
* a unique value every time. Unique pointers should take care for us of
* storage duration and object destruction.
*/
static std::unique_ptr<std::vector<std::string>> output;
output = std::make_unique<std::vector<std::string>>();
static std::unique_ptr<std::string> dir;
dir = std::make_unique<std::string>(directory);
auto pusher = [](const char* path, const struct stat*, int,
struct FTW*) -> int {
output->emplace_back(path);
return 0;
};
int flags = 0;
/* Do not follow symbolic links (directories). `ftw` will not report any file
* twice, which can lead to some possibly unexpected behaviour, where a fileis
* reported in the symlinked directory, but not in the symlink's target. For
* example, in a directory structure:
*
* .
* |_ a
* |_a.txt
* |_b.txt
* |_ b -> a // symbolic link
*
* file tree walk may produce output:
*
* ./b
* ./b/a.txt
* ./b/b.txt
*
*/
if (symlinks == Symlinks::Ignore) flags |= FTW_PHYS;
/* The third argument states the maximum number of file descriptors that
* `nftw` can have opened at any time.
*/
::nftw(directory.c_str(), pusher, 20, flags);
std::sort(output->begin(), output->end());
return *output;
}
std::vector<std::string> exot::utilities::grep_directory_r(
const std::string& directory, const std::string& regex, Symlinks symlinks) {
std::vector<std::string> list = list_directory_r(directory);
std::regex matcher(regex);
list.erase(std::remove_if(list.begin(), list.end(),
[&matcher](std::string element) -> bool {
return !std::regex_match(element, matcher);
}),
list.end());
std::sort(list.begin(), list.end());
return list;
}
#endif
bool exot::utilities::is_readable(const std::string& path) {
std::ifstream file{path};
return file.is_open();
}
bool exot::utilities::exists(const std::string& path) {
std::ifstream file{path};
return file.good();
}
bool exot::utilities::is_directory(const std::string& path) {
struct stat stat_result;
if (::stat(path.c_str(), &stat_result) == -1) {
return false;
} else if (S_ISDIR(stat_result.st_mode)) {
return true;
} else {
return false;
}
}
auto exot::utilities::get_stat(const std::string& path)
-> std::optional<struct stat> {
struct stat stat_result;
if (::stat(path.c_str(), &stat_result) == -1) {
return {};
} else {
return stat_result;
}
}
bool exot::utilities::all_readable(const std::vector<std::string>& paths) {
return std::all_of(paths.begin(), paths.end(),
[](const auto& path) { return is_readable(path); });
}
bool exot::utilities::is_empty(const std::string& file_path) {
std::ifstream file(file_path);
return file.peek() == std::ifstream::traits_type::eof();
}
std::vector<std::string> exot::utilities::remove_unreadable(
std::vector<std::string>& paths) {
std::vector<std::string> removed;
for (auto it = paths.begin(); it != paths.end();) {
if (!is_readable(*it)) {
removed.push_back(*it);
it = paths.erase(it);
} else {
++it;
}
}
return removed;
}
auto exot::utilities::get_long_string_value_from_file(
const std::string& path) noexcept -> std::optional<std::string> {
try {
if (is_readable(path)) {
std::string output;
std::string tmp;
std::ifstream file{path};
while (file >> tmp) { output += tmp + " "; }
return output;
} else {
return {};
}
} catch (...) { return {}; }
}
auto exot::utilities::get_string_value_from_file(
const std::string& path) noexcept -> std::optional<std::string> {
try {
if (is_readable(path)) {
std::string output;
std::ifstream file{path};
file >> output;
return output;
} else {
return {};
}
} catch (...) { return {}; }
}
<file_sep>/src/generators/cache_maurice_mt.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/cache_maurice_mt.cpp
* @author <NAME>
* @brief Multi-threaded generator causing LLC cache eviction.
*/
#include <exot/generators/cache_maurice_mt.h>
#include <cmath>
#include <spdlog/spdlog.h>
#include <exot/utilities/cache.h>
using namespace exot::modules;
generator_cache_maurice_mt::generator_cache_maurice_mt(
generator_cache_maurice_mt::settings& conf)
: bitset_generator_base(conf), lconf_{conf} {
using namespace exot::utilities;
using std::log2;
/* Get information about the cache. */
auto cache_info = (lconf_.cache_info.has_value()
? CPUCacheInfo(0, lconf_.cache_info.value())
: CPUCacheInfo(0));
auto llc = cache_info.llc();
auto llc_associativity = llc.ways_of_associativity().value();
auto llc_line_size = llc.coherency_line_size().value();
auto llc_number_of_sets = llc.number_of_sets().value();
logger_->info(
"[generator->generator_cache_maurice_mt] LLC associativity: {}, "
"line size: {}, number of sets: {}",
llc_associativity, llc_line_size, llc_number_of_sets);
n_ = static_cast<int>(llc_associativity); //! LLC ways
o_ = static_cast<int>(log2(llc_line_size)); //! offset field
s_ = static_cast<int>(log2(llc_number_of_sets)); //! set field
c_ = lconf_.overprovision_factor; //! buffer factor
m_ = static_cast<int>(n_ * c_); //! buffer multiplier
b_ = static_cast<int>(m_ * (1 << (o_ + s_))); //! buffer size
logger_->info(
"[generator->generator_cache_maurice_mt] using n: {}, o: {}, s: {}, "
"c: {:.2f}, m: {}, b: {:#x}",
n_, o_, s_, c_, m_, b_);
}
void generator_cache_maurice_mt::generate_load(
const generator_cache_maurice_mt::decomposed_type& decomposed_subtoken,
const generator_cache_maurice_mt::enable_flag_type& flag,
generator_cache_maurice_mt::core_type core,
generator_cache_maurice_mt::index_type index) {
volatile constexpr static thread_local std::uint8_t constant = 0xAA;
/* If tracing is enabled, we also track how many buffer traversals were
* completed. */
#ifdef SPDLOG_TRACE_ON
auto count = int{0};
#endif
/* Since all buffers have thread-local storage, we cannot resize/allocate them
* in the constructor, it's only possible once the worker threads are created.
*
* The thread-local "once flags" are used to perform the resizing the first
* time `generate_load` is called. The resizing is performed in this function
* because, given the duration of the buffer traversal, the overhead is less
* impactful then in the `decompose_subtoken` function. Moreover, the latter
* is performed while holding a lock, therefore has to be kept lightweight.
*/
std::call_once(this->once_flag_, [this, core] {
this->buffer_.resize(b_);
SPDLOG_LOGGER_TRACE(logger_,
"[generator->generate_load] resizing buffer for "
"core {}: buffer @{} -> {:#x}",
core, fmt::ptr(std::addressof(this->buffer_)),
this->buffer_.size());
});
if (decomposed_subtoken) {
SPDLOG_LOGGER_TRACE(
logger_, "[generator->generate_load] worker on core {} enabled", core);
while (flag) {
/* Access elements in the buffer. */
for (auto i = 0; i < (1 << s_); ++i) {
for (auto j = 0; j < m_; ++j) {
auto idx = (1 << o_) * i + (1 << (o_ + s_)) * j;
this->buffer_.at(idx) = constant;
}
}
#ifdef SPDLOG_TRACE_ON
++count;
#endif
}
SPDLOG_LOGGER_TRACE(logger_,
"[generator->generate_load] worker on core {} "
"completed {} loops through buffer",
core, count);
}
}
<file_sep>/cmake/modules/clone_target.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file clone_target.cmake
# @author <NAME>
# @brief Function to clone a target 'as completely as possible'.
#
# list of possible target properties, filtered for read-only and
# incompatible ones.
set(POSSIBLE_TARGET_PROPERTIES
"ALIASED_TARGET"
"ANDROID_ANT_ADDITIONAL_OPTIONS"
"ANDROID_API"
"ANDROID_API_MIN"
"ANDROID_ARCH"
"ANDROID_ASSETS_DIRECTORIES"
"ANDROID_GUI"
"ANDROID_JAR_DEPENDENCIES"
"ANDROID_JAR_DIRECTORIES"
"ANDROID_JAVA_SOURCE_DIR"
"ANDROID_NATIVE_LIB_DEPENDENCIES"
"ANDROID_NATIVE_LIB_DIRECTORIES"
"ANDROID_PROCESS_MAX"
"ANDROID_PROGUARD"
"ANDROID_PROGUARD_CONFIG_PATH"
"ANDROID_SECURE_PROPS_PATH"
"ANDROID_SKIP_ANT_STEP"
"ANDROID_STL_TYPE"
"ARCHIVE_OUTPUT_DIRECTORY_DEBUG"
"ARCHIVE_OUTPUT_DIRECTORY_RELEASE"
"ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO"
"ARCHIVE_OUTPUT_DIRECTORY"
"ARCHIVE_OUTPUT_NAME_DEBUG"
"ARCHIVE_OUTPUT_NAME_RELEASE"
"ARCHIVE_OUTPUT_NAME_RELWITHDEBINFO"
"ARCHIVE_OUTPUT_NAME"
"AUTOGEN_BUILD_DIR"
"AUTOGEN_PARALLEL"
"AUTOGEN_TARGET_DEPENDS"
"AUTOMOC_COMPILER_PREDEFINES"
"AUTOMOC_DEPEND_FILTERS"
"AUTOMOC_MACRO_NAMES"
"AUTOMOC_MOC_OPTIONS"
"AUTOMOC"
"AUTOUIC"
"AUTOUIC_OPTIONS"
"AUTOUIC_SEARCH_PATHS"
"AUTORCC"
"AUTORCC_OPTIONS"
"BINARY_DIR"
"BUILD_RPATH"
"BUILD_WITH_INSTALL_NAME_DIR"
"BUILD_WITH_INSTALL_RPATH"
"BUNDLE_EXTENSION"
"BUNDLE"
"C_EXTENSIONS"
"C_STANDARD"
"C_STANDARD_REQUIRED"
"COMMON_LANGUAGE_RUNTIME"
"COMPATIBLE_INTERFACE_BOOL"
"COMPATIBLE_INTERFACE_NUMBER_MAX"
"COMPATIBLE_INTERFACE_NUMBER_MIN"
"COMPATIBLE_INTERFACE_STRING"
"COMPILE_DEFINITIONS"
"COMPILE_FEATURES"
"COMPILE_FLAGS"
"COMPILE_OPTIONS"
"COMPILE_PDB_NAME"
"COMPILE_PDB_NAME_DEBUG"
"COMPILE_PDB_NAME_RELEASE"
"COMPILE_PDB_NAME_RELWITHDEBINFO"
"COMPILE_PDB_OUTPUT_DIRECTORY"
"COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG"
"COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE"
"COMPILE_PDB_OUTPUT_DIRECTORY_RELWITHDEBINFO"
"CROSSCOMPILING_EMULATOR"
"CUDA_SEPARABLE_COMPILATION"
"CUDA_RESOLVE_DEVICE_SYMBOLS"
"CUDA_EXTENSIONS"
"CUDA_STANDARD"
"CUDA_STANDARD_REQUIRED"
"CXX_EXTENSIONS"
"CXX_STANDARD"
"CXX_STANDARD_REQUIRED"
"DEBUG_POSTFIX"
"DEFINE_SYMBOL"
"DEPLOYMENT_REMOTE_DIRECTORY"
"DOTNET_TARGET_FRAMEWORK_VERSION"
"EchoString"
"ENABLE_EXPORTS"
"ENABLED_SANITIZERS"
"EXCLUDE_FROM_ALL"
"EXCLUDE_FROM_DEFAULT_BUILD_DEBUG"
"EXCLUDE_FROM_DEFAULT_BUILD_RELEASE"
"EXCLUDE_FROM_DEFAULT_BUILD_RELWITHDEBINFO"
"EXCLUDE_FROM_DEFAULT_BUILD"
"EXPORT_NAME"
"EXPORT_PROPERTIES"
"FOLDER"
"Fortran_FORMAT"
"Fortran_MODULE_DIRECTORY"
"FRAMEWORK"
"FRAMEWORK_VERSION"
"GENERATOR_FILE_NAME"
"GNUtoMS"
"HAS_CXX"
"IMPLICIT_DEPENDS_INCLUDE_TRANSFORM"
"IMPORT_PREFIX"
"IMPORT_SUFFIX"
"INCLUDE_DIRECTORIES"
"INSTALL_NAME_DIR"
"INSTALL_RPATH"
"INSTALL_RPATH_USE_LINK_PATH"
"INTERPROCEDURAL_OPTIMIZATION_DEBUG"
"INTERPROCEDURAL_OPTIMIZATION_RELEASE"
"INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO"
"INTERPROCEDURAL_OPTIMIZATION"
"IOS_INSTALL_COMBINED"
"JOB_POOL_COMPILE"
"JOB_POOL_LINK"
"LABELS"
"C_CLANG_TIDY"
"CXX_CLANG_TIDY"
"C_COMPILER_LAUNCHER"
"CXX_COMPILER_LAUNCHER"
"C_CPPCHECK"
"CXX_CPPCHECK"
"C_CPPLINT"
"CXX_CPPLINT"
"C_INCLUDE_WHAT_YOU_USE"
"CXX_INCLUDE_WHAT_YOU_USE"
"C_VISIBILITY_PRESET"
"CXX_VISIBILITY_PRESET"
"LIBRARY_OUTPUT_DIRECTORY_DEBUG"
"LIBRARY_OUTPUT_DIRECTORY_RELEASE"
"LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO"
"LIBRARY_OUTPUT_DIRECTORY"
"LIBRARY_OUTPUT_NAME_DEBUG"
"LIBRARY_OUTPUT_NAME_RELEASE"
"LIBRARY_OUTPUT_NAME_RELWITHDEBINFO"
"LIBRARY_OUTPUT_NAME"
"LINK_DEPENDS_NO_SHARED"
"LINK_DEPENDS"
"LINKER_LANGUAGE"
"LINK_FLAGS_DEBUG"
"LINK_FLAGS_RELEASE"
"LINK_FLAGS_RELWITHDEBINFO"
"LINK_FLAGS"
"LINK_INTERFACE_LIBRARIES_DEBUG"
"LINK_INTERFACE_LIBRARIES_RELEASE"
"LINK_INTERFACE_LIBRARIES_RELWITHDEBINFO"
"LINK_INTERFACE_LIBRARIES"
"LINK_INTERFACE_MULTIPLICITY_DEBUG"
"LINK_INTERFACE_MULTIPLICITY_RELEASE"
"LINK_INTERFACE_MULTIPLICITY_RELWITHDEBINFO"
"LINK_INTERFACE_MULTIPLICITY"
"LINK_LIBRARIES"
"LINK_SEARCH_END_STATIC"
"LINK_SEARCH_START_STATIC"
"LINK_WHAT_YOU_USE"
"MACOSX_BUNDLE_INFO_PLIST"
"MACOSX_BUNDLE"
"MACOSX_FRAMEWORK_INFO_PLIST"
"MACOSX_RPATH"
"MAP_IMPORTED_CONFIG_DEBUG"
"MAP_IMPORTED_CONFIG_RELEASE"
"MAP_IMPORTED_CONFIG_RELWITHDEBINFO"
"NO_SONAME"
"NO_SYSTEM_FROM_IMPORTED"
"OSX_ARCHITECTURES_DEBUG"
"OSX_ARCHITECTURES_RELEASE"
"OSX_ARCHITECTURES_RELWITHDEBINFO"
"OSX_ARCHITECTURES"
"OUTPUT_NAME_DEBUG"
"OUTPUT_NAME_RELEASE"
"OUTPUT_NAME_RELWITHDEBINFO"
"OUTPUT_NAME"
"PDB_NAME_DEBUG"
"PDB_NAME_RELEASE"
"PDB_NAME_RELWITHDEBINFO"
"PDB_NAME"
"PDB_OUTPUT_DIRECTORY_DEBUG"
"PDB_OUTPUT_DIRECTORY_RELEASE"
"PDB_OUTPUT_DIRECTORY_RELWITHDEBINFO"
"PDB_OUTPUT_DIRECTORY"
"POSITION_INDEPENDENT_CODE"
"PREFIX"
"PRIVATE_HEADER"
"PROJECT_LABEL"
"PUBLIC_HEADER"
"RESOURCE"
"RULE_LAUNCH_COMPILE"
"RULE_LAUNCH_CUSTOM"
"RULE_LAUNCH_LINK"
"RUNTIME_OUTPUT_DIRECTORY_DEBUG"
"RUNTIME_OUTPUT_DIRECTORY_RELEASE"
"RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO"
"RUNTIME_OUTPUT_DIRECTORY"
"RUNTIME_OUTPUT_NAME_DEBUG"
"RUNTIME_OUTPUT_NAME_RELEASE"
"RUNTIME_OUTPUT_NAME_RELWITHDEBINFO"
"RUNTIME_OUTPUT_NAME"
"SKIP_BUILD_RPATH"
"SOURCE_DIR"
"SOURCES"
"SOVERSION"
"STATIC_LIBRARY_FLAGS_DEBUG"
"STATIC_LIBRARY_FLAGS_RELEASE"
"STATIC_LIBRARY_FLAGS_RELWITHDEBINFO"
"STATIC_LIBRARY_FLAGS"
"SUFFIX"
"VERSION")
# Creates a new target of same type and copies all possible properties
function (clone_target target new-target)
get_target_property(__type ${target} "TYPE")
if (__type STREQUAL "EXECUTABLE")
add_executable(${new-target} "")
elseif (__type STREQUAL "STATIC_LIBRARY")
add_library(${new-target} STATIC "")
elseif (__type STREQUAL "SHARED_LIBRARY")
add_library(${new-target} SHARED "")
else()
# TODO: Unsure how to dermine whether a property is only meant
# for, e.g., iterface libraries.
message(WARNING "target type ${__type} is not supported!")
return()
endif()
message(STATUS "Created a new target of type ${__type}")
message(STATUS "Copying target properties from ${target} to ${new-target}")
# Copy target properties to the newly created target
foreach(property ${POSSIBLE_TARGET_PROPERTIES})
get_target_property(__property ${target} ${property})
if(__property)
set_target_properties(${new-target} PROPERTIES "${property}" "${__property}")
message(STATUS "Set property ${property} to ${__property}")
endif()
endforeach(property)
endfunction()
<file_sep>/include/exot/primitives/tsc_clock.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/tsc_clock.h
* @author <NAME>
* @brief A clock with std::chrono-like interface that explicitly uses the
* time stamp counter.
*/
#pragma once
#ifdef __x86_64__
#include <chrono> // for time_point and duration
#include <cstdint> // for uint*
#include <thread> // for this_thread
#include <exot/primitives/tsc.h> // for tsc::start, tsc::stop
#include <exot/utilities/timing.h> // for nanosleep
namespace exot::primitives {
inline namespace x86_64 {
// class platform_specific_tsc {
// public:
// typedef std::chrono::duration<std::chrono::nanoseconds::rep,
// std::ratio<1, 1'600'000'000>>
// internal_duration;
// };
/**
* @brief Clock that uses the time stamp counter explicitly
* @details The clock uses the same interface as other clock from the C++
* STL. It can be used as a drop-in replacement whenever a standard
* clock interface is required.
*
* However, due to the need to compute the TSC frequency at runtime,
* there is a small caveat. To maintain the same static interface as
* other clock types, calibration has to be performed during the
* first call to the `now()` function. Since the values for `init`
* and `frequency` are declared static, they will be executed
* exactly once. As soon as their values are set, the calls to
* `tsc_get_frequency()` will not be repeated. In some cases this
* one-off overhead might be acceptable, since all chrono functions,
* duration computations and casts work with the time stamp counter.
*/
template <typename T = SimpleTSC,
typename = std::enable_if_t<is_time_stamp_counter_v<T>>>
class tsc_clock {
public:
typedef std::chrono::nanoseconds duration;
typedef duration::rep rep;
typedef duration::period period;
typedef std::chrono::time_point<tsc_clock> time_point;
static constexpr bool is_steady = true;
static constexpr auto overhead_sleep = std::chrono::milliseconds{100};
static constexpr unsigned overhead_rep = 10;
using tsc = T;
/**
* @brief Gets the current time point
* @details This is the only static function that an STL-like clock has to
* provide.
*
* @return The current time point
*/
static time_point now() noexcept {
/* Initialise the time stamp counter, called only once for all uses of the
* `tsc_clock`. Static local variables have static storage duration and are
* initialised the first time the control flow passes their declarations.
*
* Thanks to that the functions tsc_* do not have to be static. */
static auto init = tsc::start();
/* Get the time stamp counter frequency, called only once for all uses of
* the `tsc_clock`. */
static auto frequency = get_tsc_frequency();
/* The multiplication factor used to convert cycles to the base period type,
* also a static local object. */
static long double multiplier =
static_cast<long double>(period::den) / frequency;
/* The static local variables above constitute the initialisation of the
* tsc_clock.
*
* As a matter of fact, the implementation of the <chrono> header of the
* standard library often relies on such a pattern, e.g. in the
* implementation of the steady_clock::now(): code{static FP fp =
* init_steady_clock();}. */
/* If tsc_clock inherits from `platform_specific_tsc`, the internal duration
* with a custom ratio can be used, and the time point can be obtained by
* casting the internal duration to the public duration (nanoseconds). */
// auto internal = tsc_clock::internal_duration{cycles};
// auto duration =
// std::chrono::duration_cast<tsc_clock::duration>(internal);
/*! Access to the current time stamp counter value. */
auto cycles = tsc::stop();
/* Convert and cast the cycle count to base duration type. */
auto _ = static_cast<decltype(cycles)>(multiplier * cycles);
/* Form the time point. */
return time_point{duration{_}};
}
/**
* @brief Get the sleep duration/overhead in cycles
*
* @param[in] duration_ The sleep duration
*
* @return Number of cycles taken by the sleep call
*/
static std::uint64_t get_sleep_cycle_count(duration duration_) {
auto start = tsc::start();
exot::utilities::nanosleep(duration_);
return (tsc::stop() - start);
}
/**
* @brief Get the average sleep overhead in cycles
*
* @param[in] duration The sleep duration
* @param[in] rep The number of test repetitions
*
* @return The average number of cycles for the sleep call
*/
static std::uint64_t get_sleep_overhead(duration duration_,
unsigned int rep) {
std::uint64_t accum{0};
unsigned int count{rep};
while (count--) accum += get_sleep_cycle_count(duration_);
return accum / rep;
}
/**
* @brief Calculate the time stamp counter frequency
*
* @return The time stamp counter frequency in Hz
*/
static rep get_tsc_frequency() {
/* The average overhead of just the call to `sleep_for` with zero sleep
* duration. */
auto sleep_ovh = get_sleep_overhead(duration{0}, 100);
/* The average cycle count of a call to sleep for `sleep_time`. */
auto sleep_cycles = get_sleep_overhead(overhead_sleep, overhead_rep);
/* The sleep time casted to clock's base duration. */
static auto sleep_ns = std::chrono::duration_cast<duration>(overhead_sleep);
/* `tsc_clock::duration::period::den` is used just in case the clock period
* is not in nanoseconds. */
return period::den * (sleep_cycles - sleep_ovh) / sleep_ns.count();
}
};
} // namespace x86_64
} // namespace exot::primitives
#endif
<file_sep>/examples/configurable.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file examples/configurable.cpp
* @author <NAME>
* @brief An example configurable type.
*/
#include <map>
#include <string>
#include <type_traits>
#include <vector>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <nlohmann/json.hpp>
#include <exot/utilities/configuration.h>
/* Example 1: How to make a custom type work with JSON? */
/* A simple non-template type. */
struct MySimpleT {
int value_;
};
/* A custom class template that wraps an arithmentic type or nullptr.
* In JSON, it will be represented as: {"value": ..., "description": ...}. */
template <typename WrappedType,
typename = std::enable_if_t<(!std::is_null_pointer_v<WrappedType> &&
std::is_arithmetic_v<WrappedType>)>>
struct MyTemplateT {
WrappedType value_; //! A value of type WrappedType
std::string description_; //! A description of type std::string
};
/* To create a custom JSON serialiser, it's easiest to provide a template
* specialisation for the adl_serialiser. The specialisation has to be created
* in the nlohmann namespace. */
/* To allow a type T to be serialised to JSON, create a to_json function, with
* signature to_json(json&, const T&). */
/* To allow a type T to be created from JSON, create a from_json function, with
* signature from_json(const json&, T&). */
namespace nlohmann {
/* Simple types: specialise adl_serializer with your type, here: MySimpleT. */
template <>
struct adl_serializer<MySimpleT> {
static void to_json(json& j, const MySimpleT& o) { j = o.value_; }
static void from_json(const json& j, MySimpleT& o) { j.get_to(o.value_); }
};
/* Template types: provide a partial specialisation with your type. */
template <typename T>
struct adl_serializer<MyTemplateT<T>> {
static void to_json(json& j, const MyTemplateT<T>& o) {
j = json({"value", o.value_}, {"description", o.description_});
}
static void from_json(const json& j, MyTemplateT<T>& o) {
j.at("value").get_to(o.value_);
j.at("description").get_to(o.description_);
}
};
} // namespace nlohmann
using namespace exot::utilities;
using nlohmann::json;
/* Example 2: How to create a configurable class? */
/* First, to make a class 'configurable', you need to inherit from it in a
* CRTP fashion, i.e. inherit from a class which has the derived class as a
* template parameter. Thanks to this pattern, the class MyConfigurableClass
* is accessible inside configurable<...>.
*
* Extra care might be needed when your class is itself a class template. See
* the declaration of settings inside meter_host and meter_host_logger. */
struct MyConfigurableClass : configurable<MyConfigurableClass> {
/* Declare member variables that you wish to configure. These can be quite
* complex types (arrays, maps, etc.), or custom types, as long as a
* serialiser is provided.
*
* Below we have the following types of variables: */
std::vector<std::string> MyStrings; //! A vector of strings
std::map<std::string, double> MyMap; //! A map of pairs string->double
MySimpleT MySimple; //! A simple wrapping type
MyTemplateT<int> MyCustom; //! A complex type from a class template
/* IMPORTANT: The configurable<> needs a name() function to be available.
* A static assertion is present, and will complain if unavailable. */
const char* name() const { return "MyConfigurableClass"; }
/* The function where JSON values are written to member variables. */
void configure() {
/* To instruct which key from JSON is supposed to be written to which
* variable, use the bind_and_describe_data function. It takes the key, and
* an lvalue reference to the variable. */
bind_and_describe_data("MyStrings", MyStrings);
bind_and_describe_data("MyMap", MyMap);
bind_and_describe_data("MySimple", MySimple);
bind_and_describe_data("MyCustom", MyCustom);
}
/* Custom function for demonstration purposes. */
void print() {
fmt::print("\nMyConfigurableClass:\n");
fmt::print("├ MyStrings: {}\n", MyStrings);
fmt::print("├ MyMap: {}\n", MyMap);
fmt::print("├ MySimple: {}\n", MySimple.value_);
fmt::print("└ MyCustom:\n");
fmt::print(" ├ value: {}\n", MyCustom.value_);
fmt::print(" └ description: {}\n", MyCustom.description_);
}
};
static const bool USE_TEMPLATE_HELPER{false};
void section(const std::string& text) {
fmt::print("\n{} {}\n", std::string('-', 78 - text.size()), text);
}
int main() {
/* Create a JSON object using the '_json' literal. */
auto j = R"(
{ "MyConfigurableClass": {
"MyStrings": ["String1", "String2"],
"MyMap": { "Key1": 1, "Key2": 2},
"MySimple": 1,
"MyCustom": { "value": 10.1e-2, "description": "My custom type"}
}})"_json;
section("Provided JSON object");
fmt::print("{}\n", R"(
{ "MyConfigurableClass": {
"MyStrings": ["String1", "String2"],
"MyMap": { "Key1": 1, "Key2": 2},
"MySimple": 1,
"MyCustom": { "value": 10.1e-2, "description": "My custom type"}
}})");
/* Create an instance of the custom class. */
MyConfigurableClass instance;
section("Before configuring");
/* Before configuring, the instance's internal JSON should be a nullptr. */
fmt::print("\nInstance's internal JSON reference is null: {}\n",
instance.get_json_const_ref().is_null());
/* The printed values will be uninitialised. */
instance.print();
/* To configure the instance, use the function template helper, or the
* set_json() and configure() member functions. */
if constexpr (USE_TEMPLATE_HELPER) {
configure(j, instance);
} else {
instance.set_json(j);
instance.configure();
}
section("After configuring");
fmt::print("\nInstance's internal JSON reference is null: {}\n",
instance.get_json_const_ref().is_null());
instance.print();
return 0;
}
<file_sep>/src/primitives/x86_64.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/x86_64.cpp
* @author <NAME>
* @brief Implementation of the IA-64 specific low level utilities.
*/
#if defined(__x86_64__)
#include <exot/primitives/x86_64.h>
#include <fmt/format.h>
namespace exot::primitives {
inline namespace x86_64 {
std::array<std::uint32_t, 4> cpuid(std::uint32_t eax, std::uint32_t ecx) {
std::uint32_t ebx, edx;
/* Check used for position-independent code compilation in a 2013 document from
* Intel Corporation "How to detect New Instruction support in the 4th
* generation Intel® CoreTM processor family" by <NAME>.
*
* For example, PIC has to be used when compiling with Android NDK. */
#if defined(__PIC__)
asm volatile(
"movl %%ebx, %%edi \n"
"cpuid \n"
"xchgl %%ebx, %%edi"
: "=D"(ebx),
#else
asm volatile("cpuid"
: "+b"(ebx),
#endif
"+a"(eax), "+c"(ecx), "=d"(edx));
#ifndef DEBUG
/* @todo This statement is used temporarily to solve an unexpected segfault
* "Access not within mapped region" in modules/thermal_msr.cpp, when compiled
* with GCC 7.3.0 with optimisation levels 2 and 3 in build configurations
* Release or RelWithDebInfo */
static_cast<void>(fmt::format("{},{},{},{}", eax, ebx, ecx, edx));
#endif
return {eax, ebx, ecx, edx};
}
unsigned int logical_id() {
/* If the variable had only the `static` storage specifier, the value would be
* 'cached' over all invocations of the function, regardless of which thread
* on which logical processor executed the function. However, if the variable
* is marked further with the `thread_local` specifier, the variable is
* allocated when a thread begins and deallocated when it ends, therefore each
* thread has its own 'cached' instance of the cpuid information.
*
* It is better to cache the results of the CPUID instruction, because it can
* take multiple clock cycles and incurs a large latency in the dependency
* chain.
*
* For example, a quick informal benchmark for 100'000 `logical_id()`
* invocations results in execution times of 850µs for the code below, and
* 11500µs for a non-caching version, three orders of magnitude more. */
static thread_local auto cpuid_0x0B{cpuid(0x0B, 0)};
return static_cast<unsigned int>(cpuid_0x0B[3] & 0xFFFFUL);
}
unsigned int cluster_id() {
static thread_local auto cpuid_0x0B{cpuid(0x0B, 0)};
return static_cast<unsigned int>((cpuid_0x0B[3] >> 16) & 0xFFFFUL);
}
unsigned int logical_processors_per_core() {
static thread_local auto cpuid_0x0B{cpuid(0x0B, 0)};
return static_cast<unsigned int>(cpuid_0x0B[1]);
}
} // namespace x86_64
} // namespace exot::primitives
#endif
<file_sep>/CMakeLists.txt
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
#------------------------------------------------------------------------------
# The build specification for the library
cmake_minimum_required(VERSION 3.6)
project(exot-library VERSION 3.0.0 LANGUAGES CXX)
# Use the following external cmake functions/modules
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake/modules)
include(add_fiber_dependency)
include(colour_message)
include(print_target_properties)
include(print_directory_properties)
include(print_build_info)
include(configure_clang_format)
include(configure_clang_tidy)
# Force CMake to provide compile commands, which are useful for IDEs and static
# analysers.
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
get_directory_property(__has_parent PARENT_DIRECTORY)
if(__has_parent)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON PARENT_SCOPE)
endif()
colour_message(STATUS BLUE BOLD
"Configuring the exot library ⤵")
# Set of options available for the library
option(exot_use_fibers "Use Boost::fiber" OFF)
option(enable_clang_format "Use code autoformatting" ON)
option(enable_clang_tidy "Use the static analyser" OFF)
if(CMAKE_BUILD_TYPE)
if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
set(enable_clang_tidy ON)
# "-Og should be the optimization level of choice for the standard
# edit-compile-debug cycle, offering a reasonable level of optimization
# while maintaining fast compilation and a good debugging experience. It
# is a better choice than -O0 for producing debuggable code because some
# compiler passes that collect debug information are disabled at -O0."
# See: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
string(APPEND CMAKE_CXX_FLAGS_DEBUG " -Og")
endif()
endif()
configure_clang_tidy(${enable_clang_tidy})
print_build_info()
#------------------------------------------------------------------------------
# Library
# Add a static library target
add_library(exot STATIC "")
add_library(exot-modules STATIC "")
# CMake versions lower than 3.8 will complain that a 'unknown feature' was
# specified with target_compile_features, and will complain that CXX_STANDARD
# 'contained an invalid value: 17'.
if (${CMAKE_MINOR_VERSION} GREATER 7)
# A list of used compile features, useful in the case when special arguments
# are required for the compiler to enable them.
target_compile_features(exot PUBLIC
cxx_std_17
cxx_auto_type
cxx_constexpr
cxx_decltype
cxx_delegating_constructors
cxx_inline_namespaces
cxx_lambdas
cxx_nullptr
cxx_override
cxx_range_for
cxx_rvalue_references
cxx_static_assert
cxx_strong_enums
cxx_template_template_parameters
cxx_thread_local
cxx_uniform_initialization
cxx_variable_templates
cxx_variadic_templates)
set_target_properties(exot PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED YES)
else ()
set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=c++17")
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-std=c++17" __has_stdcxx_17)
if (__has_stdcxx_17)
get_target_property(__exot_compile_options exot COMPILE_OPTIONS)
if(__exot_compile_options)
string(REPLACE "-std=c++11" "" __exot_compile_options
"${__exot_compile_options}")
string(REPLACE "-std=c++14" "" __exot_compile_options
"${__exot_compile_options}")
string(REPLACE "-std=gnu++11" "" __exot_compile_options
"${__exot_compile_options}")
string(REPLACE "-std=gnu++14" "" __exot_compile_options
"${__exot_compile_options}")
set_target_properties(exot PROPERTIES
COMPILE_OPTIONS ${__exot_compile_options})
endif()
target_compile_options(exot PUBLIC "-std=c++17")
else()
message(FATAL_ERROR "The compiler does not support the C++17 standard.")
endif()
endif ()
# Source and include files
set(include_dir ${CMAKE_CURRENT_LIST_DIR}/include)
set(include_subdir ${include_dir}/exot)
# Core exot library headers & sources
set(framework_headers
${include_subdir}/framework/all.h
${include_subdir}/framework/connect.h
${include_subdir}/framework/executor.h
${include_subdir}/framework/interface.h
${include_subdir}/framework/node.h
${include_subdir}/framework/queue.h
${include_subdir}/framework/state.h)
set(utilities_headers
${include_subdir}/utilities/alignment.h
${include_subdir}/utilities/allocator.h
${include_subdir}/utilities/barrier.h
${include_subdir}/utilities/bits.h
${include_subdir}/utilities/cache.h
${include_subdir}/utilities/cli.h
${include_subdir}/utilities/configuration.h
${include_subdir}/utilities/enum.h
${include_subdir}/utilities/eviction.h
${include_subdir}/utilities/filesystem.h
${include_subdir}/utilities/fmt.h
${include_subdir}/utilities/formatting.h
${include_subdir}/utilities/helpers.h
${include_subdir}/utilities/istream.h
${include_subdir}/utilities/literals.h
${include_subdir}/utilities/main.h
${include_subdir}/utilities/mmap.h
${include_subdir}/utilities/logging.h
${include_subdir}/utilities/ostream.h
${include_subdir}/utilities/pagemap.h
${include_subdir}/utilities/platform_id.h
${include_subdir}/utilities/synchronised.h
${include_subdir}/utilities/thread.h
${include_subdir}/utilities/timing.h
${include_subdir}/utilities/timing_source.h
${include_subdir}/utilities/types.h
${include_subdir}/utilities/workers.h)
set(primitives_headers
${include_subdir}/primitives/cache.h
${include_subdir}/primitives/fenced_clock.h
${include_subdir}/primitives/monotonic_clock.h
${include_subdir}/primitives/msr.h
${include_subdir}/primitives/ordering.h
${include_subdir}/primitives/perf_clock.h
${include_subdir}/primitives/rng.h
${include_subdir}/primitives/tsc.h
${include_subdir}/primitives/tsc_clock.h
${include_subdir}/primitives/x86_64.h)
set(components_headers
${include_subdir}/components/domain_adapter.h
${include_subdir}/components/function_nodes.h
${include_subdir}/components/generator_host.h
${include_subdir}/components/generator_ffb.h
${include_subdir}/components/logger.h
${include_subdir}/components/meter_host.h
${include_subdir}/components/meter_host_logger.h
${include_subdir}/components/schedule_reader.h)
set(headers "")
list(APPEND headers
${framework_headers}
${utilities_headers}
${primitives_headers}
${components_headers})
# Modules headers & sources
set(meters_headers
${include_subdir}/meters/base.h
${include_subdir}/meters/cache_er.h
${include_subdir}/meters/cache_ff.h
${include_subdir}/meters/cache_fp.h
${include_subdir}/meters/cache_fr.h
${include_subdir}/meters/cache_l1.h
${include_subdir}/meters/fan_sysfs.h
${include_subdir}/meters/fan_procfs.h
${include_subdir}/meters/frequency.h
${include_subdir}/meters/frequency_rel.h
${include_subdir}/meters/frequency_sysfs.h
${include_subdir}/meters/power.h
${include_subdir}/meters/power_msr.h
${include_subdir}/meters/rdseed_status.h
${include_subdir}/meters/rdseed_timing.h
${include_subdir}/meters/thermal.h
${include_subdir}/meters/thermal_msr.h
${include_subdir}/meters/thermal_sysfs.h
${include_subdir}/meters/utilisation.h
${include_subdir}/meters/utilisation_procfs.h
${include_subdir}/meters/process.h
${include_subdir}/meters/process_android.h
)
set(generators_headers
${include_subdir}/generators/base.h
${include_subdir}/generators/base_bitset.h
${include_subdir}/generators/base_ffb.h
${include_subdir}/generators/base_shared_memory.h
${include_subdir}/generators/cache_maurice_mt.h
${include_subdir}/generators/cache_st.h
${include_subdir}/generators/inactive_mt.h
${include_subdir}/generators/rdseed_mt.h
${include_subdir}/generators/utilisation_mt.h
${include_subdir}/generators/utilisation_ut.h
${include_subdir}/generators/utilisation_ffb_conservative.h)
set(modules_headers "")
list (APPEND modules_headers
${meters_headers}
${generators_headers})
set(source_dir ${CMAKE_CURRENT_LIST_DIR}/src)
set(sources
${source_dir}/primitives/msr.cpp
${source_dir}/primitives/x86_64.cpp
${source_dir}/utilities/barrier.cpp
${source_dir}/utilities/cli.cpp
${source_dir}/utilities/configuration.cpp
${source_dir}/utilities/filesystem.cpp
${source_dir}/utilities/logging.cpp
${source_dir}/utilities/platform_id.cpp
${source_dir}/utilities/thread.cpp
)
set(modules_sources
${source_dir}/generators/cache_maurice_mt.cpp
${source_dir}/generators/rdseed_mt.cpp
${source_dir}/generators/utilisation_mt.cpp
${source_dir}/generators/utilisation_ffb_conservative.cpp
${source_dir}/generators/utilisation_ut.cpp
${source_dir}/meters/cache_l1.cpp
${source_dir}/meters/frequency_rel.cpp
${source_dir}/meters/frequency_sysfs.cpp
${source_dir}/meters/power_msr.cpp
${source_dir}/meters/thermal_msr.cpp
${source_dir}/meters/thermal_sysfs.cpp
${source_dir}/meters/utilisation_procfs.cpp
${source_dir}/meters/process_android.cpp
)
set(headers_and_sources ${headers} ${sources})
set(modules_headers_and_sources ${modules_headers} ${modules_sources})
#------------------------------------------------------------------------------
# Third-party dependencies
colour_message(STATUS YELLOW BOLD
"Configuring third-party libraries and dependencies ⤵")
find_package(Threads REQUIRED)
# Import external CMake projects
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/vendor/fmt)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/vendor/spdlog)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/vendor/doctest)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/vendor/json)
# `clipp` is not a CMake project, the include directory is set manually
set(clipp_include_dir ${CMAKE_CURRENT_LIST_DIR}/vendor/clipp/include)
# `doctest` target does not export INCLUDE_DIRECTORIES
set(doctest_include_dir ${CMAKE_CURRENT_LIST_DIR}/vendor/doctest/doctest)
if (${exot_use_fibers})
find_package(Boost 1.67 COMPONENTS fiber REQUIRED)
endif ()
colour_message(STATUS YELLOW BOLD
"Finished configuring third-party libraries ⤴")
#------------------------------------------------------------------------------
# Add dependencies and configure the library
target_sources(exot PRIVATE ${headers_and_sources})
target_sources(exot-modules PRIVATE ${modules_headers_and_sources})
target_link_libraries(exot-modules PUBLIC exot)
target_include_directories(exot PUBLIC
${include_dir}
${clipp_include_dir})
target_link_libraries(exot PUBLIC
fmt::fmt
spdlog
nlohmann_json::nlohmann_json)
if (${CMAKE_CXX_FLAGS} MATCHES "-static.*")
message(STATUS "MATCHED: " Threads::Threads)
target_link_libraries(exot PUBLIC
"-Wl,--whole-archive" Threads::Threads "-Wl,--no-whole-archive")
else()
target_link_libraries(exot PUBLIC Threads::Threads)
endif()
if (${ANDROID})
find_library(android-logging log)
target_link_libraries(exot PUBLIC ${android-logging})
endif()
add_fiber_dependency(exot)
set_target_properties(exot PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(CMAKE_BUILD_TYPE)
if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
target_compile_definitions(exot PUBLIC
-DSPDLOG_DEBUG_ON=1 -DSPDLOG_TRACE_ON=1
-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE)
else()
target_compile_definitions(exot PUBLIC
-DSPDLOG_NO_THREAD_ID)
endif()
endif()
target_compile_options(exot PUBLIC -DSPDLOG_FMT_EXTERNAL)
set(EXOT_TIME_FENCE 0 CACHE STRING "The default timing fence")
set(EXOT_TIME_SOURCE 4 CACHE STRING "The default timing source")
set_property(CACHE EXOT_TIME_FENCE PROPERTY STRINGS 0 1 2 3)
set_property(CACHE EXOT_TIME_SOURCE PROPERTY STRINGS 0 1 2 3 4 5)
if(EXOT_TIME_FENCE STREQUAL 0)
colour_message(STATUS YELLOW "The default timing serialisation for <exot> is: TimingFenceType::Atomic")
elseif(EXOT_TIME_FENCE STREQUAL 1)
colour_message(STATUS YELLOW "The default timing serialisation for <exot> is: TimingFenceType::Weak")
elseif(EXOT_TIME_FENCE STREQUAL 2)
colour_message(STATUS YELLOW "The default timing serialisation for <exot> is: TimingFenceType::Strong")
elseif(EXOT_TIME_FENCE STREQUAL 3)
colour_message(STATUS YELLOW "The default timing serialisation for <exot> is: TimingFenceType::None")
else()
colour_message(FATAL_ERROR RED "Invalid default timing serialisation for <exot> chosen: " ${EXOT_TIME_FENCE})
endif()
if(EXOT_TIME_SOURCE STREQUAL 0)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::SteadyClock")
elseif(EXOT_TIME_SOURCE STREQUAL 1)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::MonotonicCounter")
elseif(EXOT_TIME_SOURCE STREQUAL 2)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::MonotonicClock")
elseif(EXOT_TIME_SOURCE STREQUAL 3)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::TimeStampCounter")
elseif(EXOT_TIME_SOURCE STREQUAL 4)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::HardwarePerformanceCounter")
elseif(EXOT_TIME_SOURCE STREQUAL 5)
colour_message(STATUS YELLOW "The default timing source for <exot> is: TimingSourceType::SoftwarePerformanceCounter")
else()
colour_message(FATAL_ERROR RED "Invalid default timing source for <exot> chosen: " ${EXOT_TIME_SOURCE})
endif()
target_compile_definitions(exot PUBLIC
EXOT_TIME_FENCE=${EXOT_TIME_FENCE}
EXOT_TIME_SOURCE=${EXOT_TIME_SOURCE})
set(GENERATOR_HOST_PERFORM_VALIDATION 0 CACHE STRING "Perform token validation?")
set(GENERATOR_HOST_PROVIDE_TIMING_STATISTICS 1 CACHE STRING "Provide time keeper statistics?")
set(METER_SET_AFFINITY 1 CACHE STRING "Set meter host affinity?")
set(METER_USE_STATISTICS 0 CACHE STRING "Provide time keeper statistics?")
set(METER_LOG_SYSTEM_TIME 0 CACHE STRING "Log system time?")
set(METER_NOW_FROM_TIMER 1 CACHE STRING "Take timestamp from time keeper?")
set_property(CACHE GENERATOR_HOST_PERFORM_VALIDATION PROPERTY STRINGS 0 1)
set_property(CACHE GENERATOR_HOST_PROVIDE_TIMING_STATISTICS PROPERTY STRINGS 0 1)
set_property(CACHE METER_SET_AFFINITY PROPERTY STRINGS 0 1)
set_property(CACHE METER_USE_STATISTICS PROPERTY STRINGS 0 1)
set_property(CACHE METER_LOG_SYSTEM_TIME PROPERTY STRINGS 0 1)
set_property(CACHE METER_NOW_FROM_TIMER PROPERTY STRINGS 0 1)
target_compile_definitions(exot PUBLIC
GENERATOR_HOST_PERFORM_VALIDATION=${GENERATOR_HOST_PERFORM_VALIDATION}
GENERATOR_HOST_PROVIDE_TIMING_STATISTICS=${GENERATOR_HOST_PROVIDE_TIMING_STATISTICS}
METER_SET_AFFINITY=${METER_SET_AFFINITY}
METER_USE_STATISTICS=${METER_USE_STATISTICS}
METER_LOG_SYSTEM_TIME=${METER_LOG_SYSTEM_TIME}
METER_NOW_FROM_TIMER=${METER_NOW_FROM_TIMER})
print_target_properties(exot LINK_LIBRARIES)
print_target_properties(exot COMPILE_DEFINITIONS)
print_target_properties(exot COMPILE_OPTIONS)
print_target_properties(exot LINK_FLAGS)
print_target_properties(exot LINK_FLAGS_DEBUG)
print_target_properties(exot LINK_FLAGS_RELEASE)
print_target_properties(exot CXX_STANDARD)
print_target_properties(exot CXX_STANDARD_REQUIRED)
configure_clang_format(${enable_clang_format} exot)
#------------------------------------------------------------------------------
# Testing target
file(GLOB test_sources "${CMAKE_CURRENT_LIST_DIR}/test/test_*.cpp")
add_executable(exot-test ${test_sources})
target_link_libraries(exot-test Threads::Threads exot)
target_include_directories(exot-test PUBLIC ${doctest_include_dir})
colour_message(STATUS BLUE BOLD
"Finished configuring the exot library ⤴")
#------------------------------------------------------------------------------
# Example code targets
# Joint target for all example apps
add_custom_target(exot-examples)
file(GLOB examples "${CMAKE_CURRENT_LIST_DIR}/examples/*.cpp")
foreach(example ${examples})
get_filename_component(_name ${example} NAME_WE)
add_executable(exot-example-${_name} ${example})
target_link_libraries(exot-example-${_name} exot-modules)
add_dependencies(exot-examples exot-example-${_name})
endforeach(example)
#------------------------------------------------------------------------------
# Miscellaneous targets from /scratch/misc
add_custom_target(exot-misc)
file(GLOB misc "${CMAKE_CURRENT_LIST_DIR}/scratch/misc/*.cpp")
foreach(example ${misc})
get_filename_component(_name ${example} NAME_WE)
add_executable(exot-misc-${_name} ${example})
if (${_name} MATCHES ".*_no_modules.*")
target_link_libraries(exot-misc-${_name} exot)
else ()
target_link_libraries(exot-misc-${_name} exot-modules)
endif ()
add_dependencies(exot-misc exot-misc-${_name})
endforeach(example)
#------------------------------------------------------------------------------
# Temporary app targets from /scratch/apps
add_custom_target(exot-apps)
file(GLOB apps "${CMAKE_CURRENT_LIST_DIR}/scratch/apps/*.cpp")
foreach(example ${apps})
get_filename_component(_name ${example} NAME_WE)
add_executable(${_name} ${example})
if (${_name} MATCHES ".*_no_modules.*")
target_link_libraries(${_name} exot)
else ()
target_link_libraries(${_name} exot-modules)
endif ()
add_dependencies(exot-apps ${_name})
endforeach(example)
<file_sep>/test/test_istream.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
#include <array>
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
template <typename CharT, typename CharTraitsT, class Current, class... Rest>
std::tuple<Current, Rest...> read_tuple(
std::basic_istream<CharT, CharTraitsT>& stream) {
Current current;
stream >> current;
if constexpr (sizeof...(Rest) == 0) {
return std::tuple{current};
} else {
return std::tuple_cat(std::tuple{current},
read_tuple<CharT, CharTraitsT, Rest...>(stream));
}
}
namespace details {
template <typename CharT, typename CharTraitsT>
inline auto read_into_stringstream(
std::basic_istream<CharT, CharTraitsT>& istream)
-> std::basic_istringstream<CharT> {
std::basic_string<CharT> token;
istream >> token;
return std::move(std::basic_istringstream<CharT>{token});
}
} // namespace details
namespace std {
template <typename T, typename CharT, typename CharTraitsT>
std::basic_istream<CharT, CharTraitsT>& operator>>(
std::basic_istream<CharT, CharTraitsT>& istream,
std::vector<T>& container) {
using value_type = typename std::vector<T>::value_type;
using string_type = std::basic_string<CharT>;
using stream_type = std::basic_istringstream<CharT>;
static constexpr auto delimiter = CharT{','};
auto stream = details::read_into_stringstream(istream);
for (auto [token, input] = std::make_tuple(value_type{}, string_type{}); //
std::getline(stream, input, delimiter);) {
stream_type{input} >> token;
container.push_back(token);
}
return istream;
}
template <typename T, size_t N, typename CharT, typename CharTraitsT>
std::basic_istream<CharT, CharTraitsT>& operator>>(
std::basic_istream<CharT, CharTraitsT>& istream,
std::array<T, N>& container) {
using string_type = std::basic_string<CharT>;
using stream_type = std::basic_istringstream<CharT>;
static constexpr auto delimiter = CharT{','};
auto stream = details::read_into_stringstream(istream);
for (auto [i, input] = std::make_tuple(size_t{0}, string_type{});
std::getline(stream, input, delimiter) && i < N; ++i) {
stream_type{input} >> container.at(i);
}
return istream;
};
template <typename CharT, typename CharTraitsT, class... Ts>
std::basic_istream<CharT, CharTraitsT>& operator>>(
std::basic_istream<CharT, CharTraitsT>& stream, std::tuple<Ts...>& tuple) {
tuple = read_tuple<CharT, CharTraitsT, Ts...>(stream);
return stream;
}
} // namespace std
namespace std {
template <typename T, typename CharT, typename CharTraitsT>
std::basic_ostream<CharT, CharTraitsT>& operator<<(
std::basic_ostream<CharT, CharTraitsT>& ostream,
const std::vector<T>& range) {
ostream << CharT{'['};
for (typename std::vector<T>::const_iterator it = range.begin();
it != range.end(); ++it) {
if (it == range.begin()) {
ostream << *it;
} else {
ostream << CharT{','} << *it;
}
}
ostream << CharT{']'};
return ostream;
}
template <typename T, size_t N, typename CharT, typename CharTraitsT>
std::basic_ostream<CharT, CharTraitsT>& operator<<(
std::basic_ostream<CharT, CharTraitsT>& ostream,
const std::array<T, N>& range) {
ostream << CharT{'['};
for (size_t i = 0ull; i < N; ++i) {
if (i > 0ull) {
ostream << CharT{','} << range.at(i);
} else {
ostream << range.at(i);
}
}
ostream << CharT{']'};
return ostream;
}
} // namespace std
// using token_type = std::tuple<int, std::vector<int>, std::array<double, 3>>;
using token_type =
std::tuple<int, std::vector<int>, std::array<double, 3>, int>;
int main(int argc, char* argv[]) {
token_type v;
std::cin >> v;
std::cout << "0: " << std::get<0>(v) << "\n";
std::cout << "1: " << std::get<1>(v) << "\n";
std::cout << "2: " << std::get<2>(v) << "\n";
std::cout << "3: " << std::get<3>(v) << "\n";
return 0;
}
<file_sep>/include/exot/utilities/configuration.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/configuration.h
* @author <NAME>
* @brief General purpose utilities for configuration/bootstrapping.
*/
#pragma once
#include <algorithm>
#include <chrono>
#include <map>
#include <numeric>
#include <optional>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <nlohmann/json.hpp>
#include <exot/utilities/helpers.h>
#include <exot/utilities/thread.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* The pointer to the root config, has to form a valid JSON pointer or be empty.
*/
#ifndef POINTER_TO_ROOT_CONFIG
#define POINTER_TO_ROOT_CONFIG ""
#endif
static const char* CONFIG_ROOT = POINTER_TO_ROOT_CONFIG;
/**
* @brief Base class for configurable types
* @note Empty base class does not increase the object size. The structure
* is used mostly for type checks.
*/
struct configurable_base {};
/**
* @brief Type trait which determines whether a type has a settings member
* type, and component and type member functions.
* @todo This type trait is incomplete (does not detect all required
* members).
*
* @tparam T The type
* @tparam _ Template helper
*/
template <typename T, typename = void, typename = void>
struct is_configurable : std::false_type {};
template <typename T>
struct is_configurable<
T, std::enable_if_t<std::is_base_of_v<configurable_base, T>>,
std::void_t<decltype(std::declval<std::decay_t<T>>().name()),
decltype(std::declval<std::decay_t<T>>().configure())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_configurable_v = is_configurable<T>::value;
/**
* @brief Attempts to assign a value from a json object to a referenced
* variable, using the provided key.
*
* @param[in] json The json object
* @param[in] key The key
* @param ref The reference to data
*
* @tparam T The type of data
* @tparam <unnamed> Template helper
*/
/* @todo Temporarily provide manual partial template specialisations until the
* issue with the following declaration is resolved. It does not cause issues
* when provided in isolation from the library.
template <typename T, typename K,
typename = std::enable_if_t<(
exot::utilities::is_same_d<std::decay_t<K>, std::string>::value ||
exot::utilities::is_same_d<K,
nlohmann::json::json_pointer>::value)>>
*/
template <typename T, typename K>
inline void get_from_json_to(const nlohmann::json& json, K key, T& ref);
/**
* @brief Temporary partial specialisation for get_from_json_to and const
* char* key.
*/
template <typename T>
inline void get_from_json_to(const nlohmann::json& json, const char* key,
T& ref) {
if constexpr (is_iterable_and_clearable<decltype(ref)>::value) {
/* ---------------------------------------------------------------------- */
/* If T is a type that can be iterated and cleared, likely a container. */
/* Create an optional storage for the old value of ref. If ref was not
* empty, store its old value. */
std::optional<T> old_value;
if (!ref.empty()) old_value = ref;
try {
/* Clear the container to prevent appending if a default value was set. If
* this operation proves unsuccessful, the value will be restored. */
if (!ref.empty()) ref.clear();
json.at(key).get_to(ref);
} catch (const nlohmann::json::out_of_range& e) {
/* Ignore key-not-found and unresolved reference token errors and restore
* the erased value if possible. */
if (is_one_of(e.id, 403, 404)) {
if (old_value.has_value()) ref = old_value.value();
} else {
throw nlohmann::json::out_of_range::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} catch (const nlohmann::json::type_error& e) {
if (e.id == 302) {
/* Only allow a type mismatch error when a value has been set to null.
* Otherwise, rethrow with info about the accessed key. */
if (json.at(key).type() != nlohmann::json::value_t::null) {
/* json::json_pointer defines a std::string() operator, hence it's not
* necessary to explicitly convert it below. */
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
} else {
if (old_value.has_value()) { ref = old_value.value(); }
}
} else {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
}
} else {
/* ---------------------------------------------------------------------- */
/* If T is a simpler type. */
try {
json.at(key).get_to(ref);
} catch (const nlohmann::json::out_of_range& e) {
/* Only ignore key-not-found and unresolved reference errors. */
if (is_none_of(e.id, 403, 404)) {
throw nlohmann::json::out_of_range::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} catch (const nlohmann::json::type_error& e) {
/* Only allow a type mismatch error when a value has been set to null.
* Otherwise, rethrow with info about the accessed key. */
if (e.id == 302) {
if (json.at(key).type() != nlohmann::json::value_t::null) {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} else {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
}
}
}
/**
* @brief Temporary partial specialisation for get_from_json_to and a JSON
* pointer.
*/
template <typename T>
inline void get_from_json_to(const nlohmann::json& json,
const nlohmann::json::json_pointer& key, T& ref) {
if constexpr (is_iterable_and_clearable<decltype(ref)>::value) {
/* ---------------------------------------------------------------------- */
/* If T is a type that can be iterated and cleared, likely a container. */
/* Create an optional storage for the old value of ref. If ref was not
* empty, store its old value. */
std::optional<T> old_value;
if (!ref.empty()) old_value = ref;
try {
/* Clear the container to prevent appending if a default value was set. If
* this operation proves unsuccessful, the value will be restored. */
if (!ref.empty()) ref.clear();
json.at(key).get_to(ref);
} catch (const nlohmann::json::out_of_range& e) {
/* Ignore key-not-found and unresolved reference token errors and restore
* the erased value if possible. */
if (is_one_of(e.id, 403, 404)) {
if (old_value.has_value()) ref = old_value.value();
} else {
throw nlohmann::json::out_of_range::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} catch (const nlohmann::json::type_error& e) {
if (e.id == 302) {
/* Only allow a type mismatch error when a value has been set to null.
* Otherwise, rethrow with info about the accessed key. */
if (json.at(key).type() != nlohmann::json::value_t::null) {
/* json::json_pointer defines a std::string() operator, hence it's not
* necessary to explicitly convert it below. */
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
} else {
if (old_value.has_value()) { ref = old_value.value(); }
}
} else {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
}
} else {
/* ---------------------------------------------------------------------- */
/* If T is a simpler type. */
try {
json.at(key).get_to(ref);
} catch (const nlohmann::json::out_of_range& e) {
/* Only ignore key-not-found and unresolved reference errors. */
if (is_none_of(e.id, 403, 404)) {
throw nlohmann::json::out_of_range::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} catch (const nlohmann::json::type_error& e) {
/* Only allow a type mismatch error when a value has been set to null.
* Otherwise, rethrow with info about the accessed key. */
if (e.id == 302) {
if (json.at(key).type() != nlohmann::json::value_t::null) {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
} else {
throw nlohmann::json::type_error::create(
e.id,
e.what() + fmt::format(", the accessed key was: \"{}\"", key));
}
}
}
}
/**
* @brief Mixin for use in CRTP patterns to introduce configurability to
* compatible classes.
* @details To take advantage of the configurable mixin the class of type D
* should have a function returning a string: name().
* These are used to subset configuration structures using JSON
* pointers.
* @todo Provide a way for this to return a clipp::group for CLI config
*
* @tparam D The type to be mixed-in.
*/
template <typename D>
struct configurable : configurable_base {
const char* name() const {
static_assert(is_configurable<D>::value,
"The class should have a name() member function.");
return derived().name();
}
/**
* @brief Sets the internal JSON config
*
* @param[in] root The root JSON file/config
*/
void set_json(const nlohmann::json& root) {
try {
json_config_ = root.at(get_json_pointer());
} catch (const nlohmann::json::out_of_range& e) { json_config_ = nullptr; }
}
/**
* @brief Gets the internal JSON config's value
*
* @return The value of the JSON
*/
nlohmann::json get_json() const { return json_config_; }
/**
* @brief Gets the internal JSON config as a constant reference.
*
* @return The constant reference to the JSON.
*/
const nlohmann::json& get_json_const_ref() const { return json_config_; }
/**
* @brief Configure, to be implemented in the derived class
*/
void configure();
std::string describe() {
auto holder = fmt::format("[{}]\n", name());
derived().configure();
for (auto const& [k, v] : descriptions_) {
holder.append(fmt::format("| {:<40s} {}\n", k, v));
}
return holder;
}
protected:
/**
* @brief CRTP helper for casting this class to the CRTP-derived class
*
* @return The reference to this using the pointer to the base class
*/
constexpr D& derived() { return *static_cast<D*>(this); }
/**
* @brief CRTP helper for casting this class to the CRTP-derived class
*
* @return The const reference to this casted to the base class
*/
constexpr const D& derived() const { return *static_cast<const D*>(this); }
/**
* @brief Gets a JSON pointer to the class-specific configuration.
*
* @return The JSON pointer to configuration.
*/
nlohmann::json::json_pointer get_json_pointer() const {
return nlohmann::json::json_pointer(
fmt::format("{}/{}", CONFIG_ROOT, name()));
}
/**
* @brief Gets a reference to the contained JSON config
*
* @return The reference to the JSON config.
*/
nlohmann::json& get_json_ref() { return json_config_; }
/**
* @brief Bind a JSON value at a key to a local variable
* @details The function was refactored to allow incomplete configs to be
* used, in which case the JSON config was not assigned and the
* reference is a nullptr.
*
* @param[in] key The JSON key
* @param to The reference to the local variable
*
* @tparam T The type of the local variable
*
* @return True if able to bind, false otherwise.
*/
template <typename T>
bool bind_and_describe_data(const char* key, T& to,
std::string&& description = std::string{}) {
descriptions_.insert_or_assign(key, description);
if (get_json_const_ref() == nullptr) return false;
static_assert(
std::is_lvalue_reference<decltype(to)>::value,
"bind_and_describe_data: 'to' must be an lvalue reference (T&).");
get_from_json_to(get_json_const_ref(), key, std::forward<T&>(to));
return true;
}
private:
/**
* The JSON config
*/
nlohmann::json json_config_;
std::map<const char*, std::string> descriptions_;
};
/* Base templates that need to be specialised. */
/**
* @brief Sets the JSON object in configurables
*
* @param[in] json The json
* @param ts The configurables
*
* @tparam U The type in which the json object is provided
* @tparam Ts The types of the configurables
*/
template <typename U, typename... Ts>
inline void set_json(U json, Ts&&... ts);
/**
* @brief Sets the JSON object in configurables and configures them
*
* @param[in] json The json
* @param ts The configurables
*
* @tparam U The type in which the json object is provided
* @tparam Ts The types of the configurables
*/
template <typename U, typename... Ts>
inline void configure(U json, Ts&&... ts);
/* Template specialisations with const reference to a JSON object. */
/**
* @brief Sets the JSON file in multiple configurables
*
* @param[in] root The root JSON
* @param[in] ts The configurables
*
* @tparam Ts The types of the configurables
*/
template <typename... Ts>
inline void set_json(nlohmann::json::const_reference root, Ts&&... ts) {
(..., ts.set_json(root));
}
/**
* @brief Configures multiple configurables
*
* @param[in] ts The configurables
*
* @tparam Ts The types of the configurables
*/
template <typename... Ts>
inline void only_configure(Ts&&... ts) {
(..., ts.configure());
}
/**
* @brief Sets the JSON file in multiple configurables and configures them
*
* @param[in] root The root JSON
* @param[in] ts The configurables
*
* @tparam Ts The types of the configurables
*/
template <typename... Ts>
inline void configure(nlohmann::json::const_reference root, Ts&&... ts) {
set_json(root, ts...);
only_configure(ts...);
}
/**
* @brief Sort and deduplicate a vector of comparable elements
* @todo Move to a more general header file
*
* @param vector The vector
*
* @tparam T The sorted and deduplicated vector
*/
template <typename T>
void sort_and_deduplicate(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
/**
* @brief Bootstrap a vector of cores
* @details Checks hardware concurrency, initialises the vector if empty, and
* checks if any of the specified cores are out of range.
*
* @param cores The vector with core numbers
*/
void bootstrap_cores(std::vector<unsigned>& cores);
template <typename T>
inline constexpr bool is_string_or_arithmetic = (is_string_d<T> ||
is_arithmetic_d<T>);
template <typename T>
inline constexpr bool is_string_or_arithmetic_or_pointer =
(is_string_d<T> || is_arithmetic_d<T> || is_pointer_d<T>);
/**
* @brief Generate a header for application logging purposes
*
* @param ts Values to supply to the header, exactly 4 have to be
* provided. 1: module, 2: variable, 3: dimension, 4: unit.
*
* @tparam Ts Types of values, see static_assert's for compatibility
*
* @return A string with a formatted header
*/
template <typename... Ts>
std::string generate_header(Ts&&... ts) {
/* Make sure that the right number of arguments were provided. */
static_assert(sizeof...(ts) == 4, "Only meaningful with 4 arguments");
/* Forward as tuple to allow indexing. */
auto t = std::forward_as_tuple(std::forward<Ts>(ts)...);
/* Verify that types conform to design. */
/* 1. The first argument should be the output of settings::name(), or the
* module name. */
static_assert(is_string_d<decltype(std::get<0>(t))>,
"First argument must be convertible to a string");
/* 2. The second argument is the variable being produced, can be a name or
* a number. */
static_assert(
is_string_or_arithmetic<decltype(std::get<1>(t))>,
"Second argument must be convertible to a string or an arithmetic type");
/* 3. The third argument is the dimension of the variable, e.g. which core
* is being represented. It can also be a pointer, to account for
* addresses, which will be casted to (void*). */
static_assert(is_string_or_arithmetic_or_pointer<decltype(std::get<2>(t))>,
"Third argument must be convertible to a string or an "
"arithmetic type or a pointer type");
/* 4. The fourth argument is the unit of the variable, e.g. Hz, Watts. */
static_assert(is_string_d<decltype(std::get<3>(t))>,
"Fourth argument must be convertible to a string");
/* Caveat: A (char*) type, although satisfying the is_pointer_d trait, is also
* convertible to string, therefore will be interpreted as a string.
* To get an address of a char type pass your argument at the calling site
* to fmt::ptr(), casting it to (void*), or perform the casting yourself. */
const auto _3rd = [&](auto&& x) {
if constexpr (is_pointer_d<decltype(x)> && !is_string_d<decltype(x)>) {
return fmt::ptr(x);
} else {
return x;
}
};
return fmt::format(FMT_STRING("{}:{}:{}:{}"), std::get<0>(t), std::get<1>(t),
_3rd(std::get<2>(t)), std::get<3>(t));
}
} // namespace exot::utilities
namespace nlohmann {
/**
* @brief Overload of the json serialiser for std::optional wrapped types
*
* @tparam T The type "carried" by std::optional
*/
template <typename T>
struct adl_serializer<std::optional<T>> {
static void to_json(json& j, const std::optional<T>& o) {
if (o.has_value()) {
j = o.value();
} else {
j = nullptr;
}
}
static void from_json(const json& j, std::optional<T>& o) {
if (j.is_null()) {
o = std::nullopt;
} else {
o = j.get<T>();
}
}
};
/**
* @brief Overload of the json serialiser for std::chrono::duration.
* @details Values are written to and from numeric values in seconds. For
* example, to write a nanosecond to a duration object, write 1e-9
* in the JSON file. The target type might not be able to hold the
* specified duration!
*
* @tparam Rep Underlying type representing the duration object.
* @tparam Period A std::ratio representing the tick period.
*/
template <typename Rep, typename Period>
struct adl_serializer<std::chrono::duration<Rep, Period>> {
static void to_json(json& j, const std::chrono::duration<Rep, Period>& o) {
auto d = std::chrono::duration_cast<
std::chrono::duration<double, std::ratio<1>>>(o);
j = d.count();
}
static void from_json(const json& j, std::chrono::duration<Rep, Period>& o) {
if (!j.is_number()) {
throw json::type_error::create(
302,
fmt::format("type must be a number, but was a {}", j.type_name()));
} else {
auto d = std::chrono::duration<double, std::ratio<1>>(
j.get<json::number_float_t>());
o = std::chrono::duration_cast<std::chrono::duration<Rep, Period>>(d);
}
}
};
/**
* @brief Overload of the json serialiser for SchedulingPolicy
*/
template <>
struct adl_serializer<exot::utilities::SchedulingPolicy> {
static void to_json(json& j, const exot::utilities::SchedulingPolicy& o) {
switch (o) {
case exot::utilities::SchedulingPolicy::Other:
j = "other";
break;
case exot::utilities::SchedulingPolicy::Fifo:
j = "fifo";
break;
case exot::utilities::SchedulingPolicy::RoundRobin:
j = "round_robin";
break;
case exot::utilities::SchedulingPolicy::Deadline:
j = "deadline";
break;
case exot::utilities::SchedulingPolicy::Batch:
j = "batch";
break;
case exot::utilities::SchedulingPolicy::Idle:
j = "idle";
break;
default:
break;
}
}
static void from_json(const json& j, exot::utilities::SchedulingPolicy& o) {
if (!j.is_string()) {
throw json::type_error::create(
302,
fmt::format("type must be a string, but was a {}", j.type_name()));
} else {
auto value = j.get<json::string_t>();
if (value == "other") {
o = exot::utilities::SchedulingPolicy::Other;
} else if (value == "fifo") {
o = exot::utilities::SchedulingPolicy::Fifo;
} else if (value == "round_robin") {
o = exot::utilities::SchedulingPolicy::RoundRobin;
} else if (value == "deadline") {
o = exot::utilities::SchedulingPolicy::Deadline;
} else if (value == "batch") {
o = exot::utilities::SchedulingPolicy::Batch;
} else if (value == "idle") {
o = exot::utilities::SchedulingPolicy::Idle;
} else {
throw json::other_error::create(
501, fmt::format("provided scheduling policy value \"{}\" is not "
"featured in the enum class",
value));
}
}
}
};
/**
* @brief Overload of the json serialiser for SPDLOG's log level
*/
template <>
struct adl_serializer<spdlog::level::level_enum> {
static void to_json(json& j, const spdlog::level::level_enum& o) {
switch (o) {
case spdlog::level::level_enum::trace:
j = "trace";
break;
case spdlog::level::level_enum::debug:
j = "debug";
break;
case spdlog::level::level_enum::info:
j = "info";
break;
case spdlog::level::level_enum::warn:
j = "warn";
break;
case spdlog::level::level_enum::err:
j = "err";
break;
case spdlog::level::level_enum::critical:
j = "critical";
break;
case spdlog::level::level_enum::off:
j = "off";
break;
default:
break;
}
}
static void from_json(const json& j, spdlog::level::level_enum& o) {
if (!j.is_string()) {
throw json::type_error::create(
302,
fmt::format("type must be a string, but was a {}", j.type_name()));
} else {
auto value = j.get<json::string_t>();
if (value == "trace") {
o = spdlog::level::level_enum::trace;
} else if (value == "debug") {
o = spdlog::level::level_enum::debug;
} else if (value == "info") {
o = spdlog::level::level_enum::info;
} else if (value == "warn") {
o = spdlog::level::level_enum::warn;
} else if (value == "err") {
o = spdlog::level::level_enum::err;
} else if (value == "critical") {
o = spdlog::level::level_enum::critical;
} else if (value == "off") {
o = spdlog::level::level_enum::off;
} else {
throw json::other_error::create(
501, fmt::format("provided scheduling policy value \"{}\" is not "
"featured in the enum class",
value));
}
}
}
};
} // namespace nlohmann
<file_sep>/src/primitives/msr.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/msr.cpp
* @author <NAME>
* @brief Implementation of the MSR accessor class.
*/
#if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
#include <cerrno>
#include <cstring>
#include <exot/primitives/msr.h>
using namespace exot::primitives;
MSR::MSR(std::initializer_list<unsigned> cpus) : cpus_{cpus} {
check();
conform();
init();
}
MSR::MSR(const std::vector<unsigned>& cpus) : cpus_{cpus} {
check();
conform();
init();
}
MSR::MSR(std::vector<unsigned>&& cpus) : cpus_{std::move(cpus)} {
check();
conform();
init();
}
MSR::MSR() {
auto thread_count = std::thread::hardware_concurrency();
cpus_.resize(thread_count);
std::iota(cpus_.begin(), cpus_.end(), 0);
check();
conform();
init();
}
MSR& MSR::operator=(const MSR& other) {
cpus_ = other.cpus_;
filenames_.erase(filenames_.cbegin(), filenames_.cend());
file_descriptors_.erase(file_descriptors_.cbegin(), file_descriptors_.cend());
cpu_to_index_.erase(cpu_to_index_.cbegin(), cpu_to_index_.cend());
/**
* Need to reopen the pseudo-devices and update mapping.
*/
init();
return *this;
}
MSR::~MSR() {
for (auto& fd : file_descriptors_) { ::close(fd); }
}
std::uint64_t MSR::read(unsigned int cpu, std::uint64_t msr) {
/* Although it should be possible to replicate the functionality of `pread`
* with more idiomatic code (via an fstream opened in binary mode, and
* fstream::{seekg, peekg, read}), an initial attempt did not achieve the
* same functionality. Nevertheless, `pread` is said to be thread-safe and
* should allow concurrent access to a single file descriptor. */
assert(((1 << cpu) & used_cpu_mask_) != 0);
std::uint64_t value;
auto ret = pread(file_descriptors_.at(cpu_to_index_[cpu]),
reinterpret_cast<void*>(&value), sizeof(value), msr);
if (ret == -1) {
throw std::runtime_error(fmt::format("[MSR] error ({}) in pread: {}", errno,
std::strerror(errno)));
}
return value;
}
std::uint64_t MSR::read_any(std::uint64_t msr) {
static short i{0};
static short n{static_cast<short>(cpus_.size())};
i = i == n ? 0 : i; //! require to prevent overflows
return read(cpus_.at(i++ % n), msr);
}
std::uint64_t MSR::read_first(std::uint64_t msr) {
return read(cpus_.at(0), msr);
}
void MSR::write(unsigned int cpu, std::uint64_t msr, uint64_t value) {
auto ret = pwrite(file_descriptors_.at(cpu_to_index_[cpu]),
reinterpret_cast<void*>(&value), sizeof(value), msr);
if (ret == -1) {
throw std::runtime_error(fmt::format("[MSR] error ({}) in pwrite: {}",
errno, std::strerror(errno)));
}
}
void MSR::write_any(std::uint64_t msr, std::uint64_t value) {
static short i{0};
static short n{static_cast<short>(cpus_.size())};
i = i == n ? 0 : i; //! required to prevent overflows
write(cpus_.at(i++ % n), msr, value);
}
void MSR::write_first(std::uint64_t msr, std::uint64_t value) {
write(cpus_.at(0), msr, value);
}
std::vector<std::uint64_t> MSR::read_all(std::uint64_t msr) {
for (auto cpu : cpus_) { values.at(cpu_to_index_[cpu]) = (read(cpu, msr)); }
return values;
}
void MSR::write_all(std::uint64_t msr, uint64_t value) {
for (auto cpu : cpus_) { write(cpu, msr, value); }
}
std::vector<std::string> MSR::get_filenames() const {
return filenames_;
}
std::vector<int> MSR::get_file_descriptors() const {
return file_descriptors_;
}
std::vector<unsigned int> MSR::get_cpus() const {
return cpus_;
}
int MSR::get_cpu_count() const {
return cpus_.size();
}
auto MSR::get_index_to_cpu_mapping() const {
return cpu_to_index_;
}
void MSR::init() {
std::vector<std::fstream> descriptors; //! local vector of stream objects
//! used for checking access
unsigned int index{0};
/* Create filenames and check if descriptors are readable. */
for (auto cpu : cpus_) {
auto filename = fmt::format("/dev/cpu/{}/msr", cpu);
filenames_.push_back(filename);
descriptors.emplace_back(filename,
std::ios::in | std::ios::out | std::ios::binary);
/* Mapping between cpu and array index. */
cpu_to_index_[cpu] = index;
++index;
exot::utilities::set_bit(used_cpu_mask_, cpu);
}
/* Check if all file descriptors are readable, if not, throw. */
bool all_readable =
std::all_of(descriptors.begin(), descriptors.end(),
[](const auto& descriptor) { return descriptor.is_open(); });
if (!all_readable) {
throw std::logic_error("At least one MSR pseudo-device is not readable.");
}
for (auto&& descriptor : descriptors) { descriptor.close(); }
for (const auto& filename : filenames_) {
int fd = ::open(filename.c_str(), O_RDWR);
if (fd < 0)
throw std::logic_error(
fmt::format("Opening MSR pseudo-device {} failed.", filename));
file_descriptors_.push_back(fd);
}
values.resize(cpus_.size());
}
void MSR::conform() {
std::sort(cpus_.begin(), cpus_.end());
auto last_unique = std::unique(cpus_.begin(), cpus_.end());
cpus_.erase(last_unique, cpus_.end());
}
void MSR::check() const {
if (!std::all_of(cpus_.begin(), cpus_.end(), [](auto el) {
return el < std::thread::hardware_concurrency();
})) {
throw std::out_of_range(
"At least one element in the CPU vector exceeds hardware "
"concurrency.");
}
}
#endif
<file_sep>/src/meters/thermal_msr.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/thermal_msr.cpp
* @author <NAME>
* @brief Implementation of the MSR thermal metering module.
*/
#if defined(__linux__) && !defined(__ANDROID__) && defined(__x86_64__)
#include <exot/meters/thermal_msr.h>
#include <algorithm> // for std::transform
#include <fstream> // for ifstream
#include <thread> // for hardware_concurrency
#include <fmt/format.h> // for formatting strings
#include <fmt/ostream.h> // for ostream support
#include <exot/primitives/x86_64.h> // for logical_processors_per_core
#include <exot/utilities/bits.h> // for bit manipulation functions
#include <exot/utilities/ostream.h> // for ostream operator overloads
namespace exot::modules {
thermal_msr::thermal_msr(settings& conf)
: msr_{conf_.cores}, conf_{validate_settings(conf)} {
/* Acquire the reference temperature target.
*
* Bits 23:16 hold the temperature target of the particular processor
* (TJunction). */
temperature_target_ = exot::utilities::extract_bit_range(
msr_.read(conf_.cores[0], IA32_TEMPERATURE_TARGET), 16u, 23u);
/* Check if the processor supports package-level thermal management. */
if (conf_.use_package) {
auto cpuid_06h_eax = exot::primitives::cpuid(0x06)[0];
if (!exot::utilities::test_bit(cpuid_06h_eax, 6u)) {
debug_log_->warn(
"Package temperature was requested but the processor does not "
"support package level thermal management. Falling back to "
"cores-only.");
conf_.use_package = false;
}
}
readings_.resize(conf_.cores.size() + (conf_.use_package ? 1 : 0));
debug_log_->info("[thermal_msr] using cores: {}, package? {}", conf_.cores,
conf_.use_package);
}
typename thermal_msr::return_type thermal_msr::measure() {
static size_t count = conf_.cores.size();
for (unsigned i{0}; i < count; ++i) {
readings_.at(i) = msr_.read(conf_.cores.at(i), IA32_THERM_STATUS);
}
if (conf_.use_package)
readings_.at(count) = msr_.read_any(IA32_PACKAGE_THERM_STATUS);
return get_temperatures(std::move(readings_));
}
std::vector<std::string> thermal_msr::header() {
std::vector<std::string> description;
for (auto core : conf_.cores) {
description.push_back(exot::utilities::generate_header(
conf_.name(), "core", core, DefaultUnits::temperature));
}
if (conf_.use_package) {
description.push_back(exot::utilities::generate_header(
conf_.name(), "package", "", DefaultUnits::temperature));
}
return description;
}
thermal_msr::settings thermal_msr::validate_settings(settings& conf) {
/* If no cores were provided... */
if (conf.cores.empty()) {
for (unsigned i = 0; i < std::thread::hardware_concurrency();
i += exot::primitives::logical_processors_per_core()) {
conf.cores.push_back(i);
}
}
return conf;
}
unsigned short thermal_msr::get_temperature(std::uint64_t raw) {
return static_cast<unsigned short>(
temperature_target_ - exot::utilities::extract_bit_range(raw, 16u, 22u));
}
typename thermal_msr::return_type thermal_msr::get_temperatures(
std::vector<std::uint64_t>&& raw) {
return_type out(raw.size());
for (decltype(raw.size()) i = 0; i < raw.size(); ++i) {
out.at(i) = get_temperature(raw.at(i));
}
return out;
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/meters/process_android.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/process_android.h
* @author <NAME>
* @brief Current Process meter module for Android.
*/
#pragma once
#if defined(__linux__) && defined(__ANDROID__)
#include <jni.h> // for Java Native Interface access
#include <algorithm> // for std::transform
#include <cstdint> // for std::uint*
#include <fstream> // for ifstream
#include <string> // for std::string
#include <thread> // for hardware_concurrency
#include <vector> // for variable-size arrays
#include <fmt/format.h> // for formatting strings
#include <fmt/ostream.h> // for ostream support
#include <spdlog/spdlog.h> // for logging
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/bits.h> // for bit manipulation functions
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/ostream.h> // for ostream operator overloads
namespace exot::modules {
struct process_android : module {
using return_type = std::string;
struct settings : public exot::utilities::configurable<settings> {
// jclass* jclazz;
// jobject* jinstance;
// jmethodID* jmid;
// JavaVM* jvm;
// jint jniversion;
// bool dummy{false};
std::uintptr_t jclazz;
std::uintptr_t jinstance;
std::uintptr_t jmid;
std::uintptr_t jvm;
int jniversion;
bool dummy{false};
const char* name() const { return "process_android"; }
void configure() {
bind_and_describe_data("jclazz", jclazz);
bind_and_describe_data("jinstance", jinstance);
bind_and_describe_data("jmid", jmid);
bind_and_describe_data("jvm", jvm);
bind_and_describe_data("jniversion", jniversion);
bind_and_describe_data("dummy", dummy);
}
};
explicit process_android(settings& conf);
~process_android();
return_type measure();
std::vector<std::string> header();
private:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_;
return_type readings;
JNIEnv* jenv_;
/**
* @brief Provide sensible settings
* @details The used Java Native Environment pointer is checked here.
* If its not valid, the service should die gracefully.
*
* @param conf Module settings
*
* @return Module settings
*/
settings validate_settings(settings&);
};
} // namespace exot::modules
#endif
<file_sep>/include/exot/utilities/istream.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/istream.h
* @author <NAME>
* @brief Input stream overloads for reading tuples and other data types.
*/
#pragma once
#include <array> // for std::array
#include <chrono> // for duration
#include <istream> // for istream
#include <iterator> // for istream_iterator, back_inserter
#include <sstream> // for istringstream
#include <tuple> // for tuple, tuple_cat
#include <exot/utilities/helpers.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* @brief Input stream operator overload for reading durations
*
* @param stream The input stream
* @param duration The duration object
*
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
* @tparam Rep The underlying type used by the duration
* @tparam Period The underlying period type used by the duration
*
* @return The duration with assigned value
*/
template <typename CharT, typename CharTraitsT, class Rep, class Period>
std::istream& operator>>(std::basic_istream<CharT, CharTraitsT>& stream,
std::chrono::duration<Rep, Period>& duration) {
Rep tmp;
stream >> tmp;
duration = std::chrono::duration<Rep, Period>(tmp);
return stream;
}
/**
* @brief Reads a tuple from an istream
*
* @param stream The input stream
*
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
* @tparam Current The current tuple element type
* @tparam Rest The types of the other tuple elements
*
* @return A tuple with read values
*/
template <typename CharT, typename CharTraitsT, class Current, class... Rest>
std::tuple<Current, Rest...> read_tuple(
std::basic_istream<CharT, CharTraitsT>& stream) {
Current current;
stream >> current;
/* Check if there are no more objects to be read, the current being the last.
* Such solution saves us the trouble creating two template functions for base
* and recursive case. */
if constexpr (sizeof...(Rest) == 0) {
/* The bracket notation is the new uniform initialisation. */
return std::tuple{current};
} else {
/* `tuple_cat` combines tuple elements in a larger tuple, the result is not
* a tuple of tuples, but rather a tuple holding the types of all individual
* tuple arguments.
*
* The next call to `read_tuple` will receive the remaining tuple types, as
* long as there are any remaining. */
return std::tuple_cat(std::tuple{current},
read_tuple<CharT, CharTraitsT, Rest...>(stream));
}
}
namespace details {
/**
* @brief Reads a token from an input stream into a input stringstream
*
* @param stream The input stream
*
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
*
* @return A single token as a stringstream
*/
template <typename CharT, typename CharTraitsT>
inline std::basic_istringstream<CharT> read_into_stringstream(
std::basic_istream<CharT, CharTraitsT>& stream) {
std::basic_string<CharT> token;
stream >> token;
return std::move(std::basic_istringstream<CharT>{token});
}
} // namespace details
} // namespace exot::utilities
/**
* These have to be accessible from the global namespace
*/
namespace std {
/**
* @brief Input stream operator overload for reading tuples
* @todo The function may not work when the tuple holds iterable types
*
* @param stream The stream
* @param tuple The tuple
*
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
* @tparam Ts Types held by the tuple
*
* @return The stream
*/
template <typename CharT, typename CharTraitsT, class... Ts>
std::basic_istream<CharT, CharTraitsT>& operator>>(
std::basic_istream<CharT, CharTraitsT>& stream, std::tuple<Ts...>& tuple) {
tuple = exot::utilities::read_tuple<CharT, CharTraitsT, Ts...>(stream);
return stream;
}
/**
* @brief Input stream operator overload for reading into appendable
* containers. The container has to have a `push_back()` function.
*
* @param istream The input stream
* @param container The container
*
* @tparam T The type of the container
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
*
* @return The stream
*/
template <typename T, typename CharT, typename CharTraitsT>
typename std::enable_if<(exot::utilities::is_iterable<T>::value &&
exot::utilities::has_push_back<T>::value),
std::basic_istream<CharT, CharTraitsT>&>::type&
operator>>(std::basic_istream<CharT, CharTraitsT>& istream, T& container) {
using value_type = typename T::value_type;
using string_type = std::basic_string<CharT>;
using stream_type = std::basic_istringstream<CharT>;
static constexpr auto delimiter = CharT{','};
auto stream = exot::utilities::details::read_into_stringstream(istream);
for (auto [token, input] = std::make_tuple(value_type{}, string_type{}); //
std::getline(stream, input, delimiter);) {
stream_type{input} >> token;
container.push_back(token);
}
return istream;
};
/**
* @brief Input stream operator overload for reading into fixed-size
* arrays.
*
* @param istream The input stream
* @param container The array
*
* @tparam T The value type stored in the array
* @tparam N The size of the array
* @tparam CharT Character type used by the stream
* @tparam CharTraitsT Character traits used by the stream
*
* @return The stream
*/
template <typename T, size_t N, typename CharT, typename CharTraitsT>
std::basic_istream<CharT, CharTraitsT>& operator>>(
std::basic_istream<CharT, CharTraitsT>& istream,
std::array<T, N>& container) {
using string_type = std::basic_string<CharT>;
using stream_type = std::basic_istringstream<CharT>;
static constexpr auto delimiter = CharT{','};
auto stream = exot::utilities::details::read_into_stringstream(istream);
for (auto [i, input] = std::make_tuple(size_t{0}, string_type{});
std::getline(stream, input, delimiter) && i < N; ++i) {
stream_type{input} >> container.at(i);
}
return istream;
};
} // namespace std
<file_sep>/include/exot/primitives/cache.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/cache.h
* @author <NAME>
* @brief Primitives and utilities for cache-based channels.
*/
#pragma once
#ifndef ALWAYS_INLINE
#define ALWAYS_INLINE inline __attribute__((always_inline))
#endif
#include <cstdint>
#include <limits>
#include <type_traits>
#include <exot/utilities/bits.h>
namespace exot::primitives {
/* x86 primitives. */
#if defined(__x86_64__)
inline namespace x86_64 {
/**
* @brief Reads an address into a temporary register
* @note Will use instructions specific to 32-bit and 64-bit integers if
* such are provided. Clobbers the temporary register, "RAX" or
* "EAX".
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_read(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
if constexpr (std::numeric_limits<S>::digits == 64) {
asm volatile( //
"movq (%0), %%rax # EXOT->cache " //
: // output
: "r"(address) // input
: "%rax"); // clobber
} else {
asm volatile( //
"mov (%0), %%eax # EXOT->cache " //
: // output
: "r"(address) // input
: "%eax"); // clobber
}
}
/**
* @brief Writes an immediate value to an address
* @note Will use instructions specific to 32-bit and 64-bit integers if
* such are provided.
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_write(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
if constexpr (std::numeric_limits<S>::digits == 64) {
asm volatile( //
"movq $0, %0 # EXOT->cache " //
: // output
: "r"(address) // input
:); // clobber
} else {
asm volatile( //
"mov $0, %0 # EXOT->cache " //
: // output
: "r"(address) // input
:); // clobber
}
}
/**
* @brief Instructs the processor to prefetch an address
*
* @param address The address
*/
ALWAYS_INLINE void prefetch(void* address) {
asm volatile(
"prefetchnta (%0) # EXOT->cache \n\t" //
"prefetcht2 (%0) # EXOT->cache " //
: // output
: "r"(address)); // input
}
/**
* @brief Instructs the processor to flush an address from all caches
* @details "Executions of the CLFLUSH instruction are ordered with respect
* to each other and with respect to writes, locked
* read-modify-write instructions, fence instructions, and
* executions of CLFLUSHOPT to the same cache line." Also,
* "CLFLUSH instruction may always cause transactional abort with
* Transactional Synchronization Extensions (TSX)."
* See: https://www.felixcloutier.com/x86/clflush.
*
* @param address The address
*/
ALWAYS_INLINE void flush(void* address) {
asm volatile( //
"clflush 0(%0) # EXOT->cache " //
: // output
: "r"(address)); // input
}
ALWAYS_INLINE void flushopt(void* address) {
asm volatile( //
"clflushopt 0(%0) # EXOT->cache " //
: // output
: "r"(address)); // input
}
/**
* @brief Measures access time to an address and flushes it
* @note Function as given in the FLUSH+RELOAD paper [1].
*
* [1] <NAME> and <NAME>, “FLUSH+RELOAD - A High Resolution,
* Low Noise, L3 Cache Side-Channel Attack.,” 23rd USENIX Security
* Symposium, 2014.
*
* @param address The address
*
* @return The time to access the address in cycles
*/
ALWAYS_INLINE auto flush_reload(void* address) {
volatile std::uint32_t value;
asm volatile(
"mfence # EXOT->cache \n\t" //
"lfence # EXOT->cache \n\t" //
"rdtsc # EXOT->cache \n\t" // saves in edx:eax
"lfence # EXOT->cache \n\t" //
"movl %%eax, %%esi # EXOT->cache \n\t" // save eax of 1st rdtsc
"movl (%1), %%eax # EXOT->cache \n\t" // access address (ecx)
"lfence # EXOT->cache \n\t" //
"rdtsc # EXOT->cache \n\t" //
"subl %%esi, %%eax # EXOT->cache \n\t" // 2nd rdtsc - 1st rdtsc
"clflush 0(%1) # EXOT->cache " //
: "=a"(value) // output
: "c"(address) // input
: "%esi", "%edx"); // clobber
return value;
}
/**
* The following values are codify the bit positions that are xor'ed to
* produce a hash bit in the reverse-engineered Intel slice hashing function,
* as given in [1].
*
* [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>,
* “Reverse Engineering Intel Last-Level Cache Complex Addressing Using
* Performance Counters.,” RAID, vol. 9404, no. 3, pp. 48–65, 2015.
*
* tag + index | off
* Bit position: 3333333322222222221111111111
* 76543210987654321098765432109876543210
*/
static constexpr std::uintptr_t O_0 = 0b01101101011111010101110101010001000000;
static constexpr std::uintptr_t O_1 = 0b10111010110101111110101010100010000000;
static constexpr std::uintptr_t O_2 = 0b11110011001100110010010011000100000000;
/**
* @brief Slice selection hash function for Intel Sandy Bridge, Ivy Bridge,
* and Haswell.
* @note Based on the reverse engineering done by Maurice et al. (2015).
*
* @param[in] physical_address The physical address
* @param[in] slice_count The number of slices in the system
*
* @return The LLC slice in which the physical address is located
*/
constexpr inline auto slice_selection_hash(std::uintptr_t physical_address,
unsigned slice_count)
-> unsigned int {
using namespace exot::utilities; // for parity
if (slice_count == 2) { // ------
return (parity(physical_address & O_0)) // bit 0
& 0b1; // mask
} else if (slice_count == 4) { // ------
return ((parity(physical_address & O_0)) | // bit 0
(parity(physical_address & O_1) << 1)) // bit 1
& 0b11; // mask
} else if (slice_count == 8) { // ------
return ((parity(physical_address & O_0)) | // bit 0
(parity(physical_address & O_1) << 1) | // bit 1
(parity(physical_address & O_2) << 2)) // bit 2
& 0b111; // mask
} else {
return -1;
}
}
} // namespace x86_64
#endif
/* ARMv8 primitives. */
#if defined(__aarch64__)
inline namespace aarch64 {
/**
* @brief Reads an address into a temporary register
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_read(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
volatile S value;
if constexpr (std::numeric_limits<S>::digits == 8) {
asm volatile( //
"ldrb %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else if constexpr (std::numeric_limits<S>::digits == 16) {
asm volatile( //
"ldrh %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else {
asm volatile( //
"ldr %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
}
}
/**
* @brief Writes an immediate value to an address
* @note Will use instructions specific to 32-bit and 64-bit integers if
* such are provided.
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_write(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
volatile S value;
if constexpr (std::numeric_limits<S>::digits == 8) {
asm volatile( //
"ldrb %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else if constexpr (std::numeric_limits<S>::digits == 16) {
asm volatile( //
"ldrh %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else {
asm volatile( //
"ldr %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
}
}
/**
* @brief Instructs the processor to prefetch an address
* @note Uses the following operations:
*
* Instruction breakdown [prfm|pld|l1|keep]:
* - [prfm]: Prefetch from memory
* - [pld]: Prefetch for load (as opposed to store with [pst]).
* - [l{1,2,3}]: The cache to target (L1, L2, or L3)
* - [keep]: Policy -> keep in cache.
*
* Enable level 3 by prepending the list with:
* "prfm pldl3keep, [%x0] // EXOT->cache \n\t"
*
* @param address The address
*/
ALWAYS_INLINE void prefetch(void* address) {
asm volatile( //
"prfm pldl2keep, [%x0] // EXOT->cache \n\t" //
"prfm pldl1keep, [%x0] // EXOT->cache " //
: // output
: "r"(address)); // input
}
/**
* @brief Instructs the processor to flush an address from all caches
* @note Uses the following operations:
*
* - [dc civac]: Data cache clean & invalidate.
* - [dc] data cache,
* - [civac] option (clean and invalidate by virtual address to
* point of coherency).
* - [dsb ish]: Ensure completion of invalidations.
* - [dsb] data synchronisation barrier,
* - [ish] option (inner shareable: ordered access before and
* after any load/store combination).
* - [isb]: Synchronise the fetched instruction stream.
* - [isb] instruction synchronization barrier.
*
* @param address The address
*/
ALWAYS_INLINE void flush(void* address) {
asm volatile( //
"dc civac, %0 // EXOT->cache \n\t" // clean & invalidate
"dsb ish // EXOT->cache \n\t" // ensure completion
"isb // EXOT->cache " // synchronise instrs.
: // output
: "r"(address)); // input
}
} // namespace aarch64
#endif
#if defined(__arm__) && !defined(__aarch64__)
inline namespace arm {
/**
* @brief Reads an address into a temporary register
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_read(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
volatile S value;
if constexpr (std::numeric_limits<S>::digits == 8) {
asm volatile( //
"ldrb %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else if constexpr (std::numeric_limits<S>::digits == 16) {
asm volatile( //
"ldrh %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else {
asm volatile( //
"ldr %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
}
}
/**
* @brief Writes an immediate value to an address
* @note Will use instructions specific to 32-bit and 64-bit integers if
* such are provided.
*
* @param address The address
*
* @tparam S An integer for size information
* @tparam <unnamed> Template helper
*/
template <
typename S = std::uint32_t,
typename = std::enable_if_t<exot::utilities::are_unsigned_integral<S>>>
ALWAYS_INLINE void access_write(void* address) {
static_assert(std::numeric_limits<S>::digits <= 64,
"Only fundamental types are allowed.");
volatile S value;
if constexpr (std::numeric_limits<S>::digits == 8) {
asm volatile( //
"ldrb %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else if constexpr (std::numeric_limits<S>::digits == 16) {
asm volatile( //
"ldrh %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
} else {
asm volatile( //
"ldr %0, [%1] // EXOT->cache " //
: "=r"(value) // output
: "r"(address) // input
:); // clobber
}
}
/**
* @brief Instructs the processor to prefetch an address
* @note Uses the following operations:
*
* Instruction breakdown [prfm|pld|l1|keep]:
* - [prfm]: Prefetch from memory
* - [pld]: Prefetch for load (as opposed to store with [pst]).
* - [l{1,2,3}]: The cache to target (L1, L2, or L3)
* - [keep]: Policy -> keep in cache.
*
* @param address The address
*/
ALWAYS_INLINE void prefetch(void* address) {
asm volatile( //
"prfm pldl3keep, [%x0] // EXOT->cache \n\t" //
"prfm pldl2keep, [%x0] // EXOT->cache \n\t" //
"prfm pldl1keep, [%x0] // EXOT->cache " //
: // output
: "r"(address)); // input
}
} // namespace arm
#endif
} // namespace exot::primitives
<file_sep>/cmake/modules/sanitizers.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file sanitizers.cmake
# @author <NAME>
# @brief Functions to enable sanitisers for compilation targets.
#
# Properties:
# - ENABLED_SANITIZERS
# Functions:
# - target_add_sanitizer: adds a sanitizer runtime to a target
# - target_disable_sanitizers: disables all sanitizers of a target
# - add_sanitizer_target: creates a clone of a target with a sanitizer
# - add_sanitizer_targets: creates clones of a target for all sanitizers
# Sanitizer interactions:
# 1. leak + memory: NOT ALLOWED
# 2. leak + thread: NOT ALLOWED
# 3. leak + address: OK
# 4. leak + undefined: OK
# 5. memory + leak: NOT ALLOWED
# 6. memory + thread: NOT ALLOWED
# 7. memory + address: NOT ALLOWED
# 8. memory + undefined: OK
# 9. thread + leak: NOT ALLOWED
# 10. thread + memory: NOT ALLOWED
# 11. thread + address: NOT ALLOWED
# 12. thread + undefined: OK
# 13. address + leak: OK
# 14. address + memory: NOT ALLOWED
# 15. address + thread: NOT ALLOWED
# 16. address + undefined: OK
# 17. undefined + leak: OK
# 18. undefined + memory: OK
# 19. undefined + thread: OK
# 20. undefined + address: OK
define_property(TARGET PROPERTY ENABLED_SANITIZERS
BRIEF_DOCS "List of enabled sanitizers for a target."
FULL_DOCS "List of enabled sanitizers for a target.
Has to contain one of: address, memory, leak, thread, undefined.")
include(clone_target)
include(CheckCXXCompilerFlag)
# Adds a sanitizer runtime to a target
function (target_add_sanitizer target sanitizer)
if (NOT ${sanitizer} MATCHES "(address|memory|leak|thread|undefined)")
return()
endif()
get_target_property(__tmp ${target} ENABLED_SANITIZERS)
if (__tmp)
set(__list_of_enabled_sanitizers ${__tmp})
else()
set(__list_of_enabled_sanitizers "")
endif()
# do not duplicate
if(${sanitizer} IN_LIST $_list_of_enabled_sanitizers)
message(WARNING "sanitizer ${sanitizer} already added for target ${target}")
return()
endif()
# the support flags need to be set only once
if(NOT __list_of_enabled_sanitizers)
set(__support_flags "-g" "-fno-omit-frame-pointer" "-fno-optimize-sibling-calls")
check_cxx_compiler_flag("${__support_flags}" __support_flags_compile)
else()
set(__support_flags)
endif()
#------------------------------------------------------------------ ADDRESS
if(${sanitizer} STREQUAL "address")
if("memory" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Address and memory sanitizers cannot be used together. "
"Address sanitizer will not be added to target '${target}'.")
return()
endif()
if("thread" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Address and thread sanitizers cannot be used together. "
"Address sanitizer will not be added to target '${target}'.")
return()
endif()
list(APPEND __list_of_enabled_sanitizers "address")
set(__flag "-fsanitize=address")
#------------------------------------------------------------------ MEMORY
elseif(${sanitizer} STREQUAL "memory")
if("address" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Memory and address sanitizers cannot be used together. "
"Memory sanitizer will not be added to target '${target}'.")
return()
endif()
if("leak" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Memory and leak sanitizers cannot be used together. "
"Memory sanitizer will not be added to target '${target}'.")
return()
endif()
if("thread" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Memory and thread sanitizers cannot be used together. "
"Memory sanitizer will not be added to target '${target}'.")
return()
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
message(WARNING "Memory sanitizer is not available for the GNU compiler.")
return()
endif()
list(APPEND __list_of_enabled_sanitizers "memory")
# the memory sanitizer requires compilation with -fPIC set
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(__flag "-fsanitize=memory;-fPIE;-pie")
#------------------------------------------------------------------ LEAK
elseif(${sanitizer} STREQUAL "leak")
if("memory" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Leak and memory sanitizers cannot be used together. "
"Leak sanitizer will not be added to target '${target}'.")
return()
endif()
if("thread" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Leak and thread sanitizers cannot be used together. "
"Leak sanitizer will not be added to target '${target}'.")
return()
endif()
list(APPEND __list_of_enabled_sanitizers "leak")
set(__flag "-fsanitize=leak")
#------------------------------------------------------------------ THREAD
elseif(${sanitizer} STREQUAL "thread")
if("address" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Thread and address sanitizers cannot be used together. "
"Thread sanitizer will not be added to target '${target}'.")
return()
endif()
if("memory" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Thread and memory sanitizers cannot be used together. "
"Thread sanitizer will not be added to target '${target}'.")
return()
endif()
if("leak" IN_LIST __list_of_enabled_sanitizers)
message(WARNING "Thread and leak sanitizers cannot be used together. "
"Thread sanitizer will not be added to target '${target}'.")
return()
endif()
list(APPEND __list_of_enabled_sanitizers "thread")
set(__flag "-fsanitize=thread")
#------------------------------------------------------------------ UNDEFINED
elseif(${sanitizer} STREQUAL "undefined")
list(APPEND __list_of_enabled_sanitizers "undefined")
set(__flag "-fsanitize=undefined")
endif()
message(STATUS "Checking if ${sanitizer} sanitizer flags successfully compile...")
check_cxx_compiler_flag("${__flag}" __sanitizer_flag_compiles)
if (__sanitizer_flag_compiles EQUAL 1)
set(__flags_to_add "${__support_flags}" "${__flag}")
else ()
message(WARNING "Compiler check of sanitizer flags failed! "
"The ${sanitizer} sanitizer will not be added to target '${target}'.")
return()
endif()
set_target_properties(${target} PROPERTIES ENABLED_SANITIZERS "${__list_of_enabled_sanitizers}")
target_link_libraries(${target} PUBLIC ${__flags_to_add})
target_compile_options(${target} PUBLIC ${__flags_to_add})
endfunction()
# Disables sanitizers
function (target_disable_sanitizers target)
target_link_libraries(${target} PUBLIC "-fno-sanitize=all")
target_compile_options(${target} PUBLIC "-fno-sanitize=all")
endfunction()
# Creates a clone of a target with a sanitizer enabled
function (add_sanitizer_target target sanitizer)
if (NOT ${sanitizer} MATCHES "(address|memory|leak|thread|undefined)")
return()
endif()
set(new-target "${target}_with_${sanitizer}_sanitizer")
if (${sanitizer} STREQUAL "memory")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
message(WARNING "Memory sanitizer is not available for the GNU compiler."
"Target ${new-target} will not be created.")
return()
endif()
endif()
clone_target(${target} ${new-target})
target_add_sanitizer(${new-target} ${sanitizer})
endfunction()
# Creates a clone of a target for every available sanitizer
function (add_sanitizer_targets target)
set(sanitizers "address;memory;leak;thread;undefined")
foreach(sanitizer ${sanitizers})
add_sanitizer_target(${target} "${sanitizer}")
endforeach(sanitizer)
endfunction()
<file_sep>/src/utilities/cli.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/cli.cpp
* @author <NAME>
* @brief Implementation of the command line parser class from @ref cli.h.
*/
#include <exot/utilities/cli.h>
namespace exot::utilities {
clipp::group JsonConfig::get_cli_configuration() {
using clipp::group;
using clipp::option;
using clipp::value;
auto file = (option("--json_file").required(true) &
value("json file")
.doc("Configure with a file")
.call([&](const char* value) { set_with_file(value); }));
auto string = (option("--json_string").required(true) &
value("json string")
.doc("Configure by passing a string")
.call([&](const char* value) { set_with_string(value); }));
auto config = (file | string);
config.doc("JSON-based configuration");
return config;
}
nlohmann::json JsonConfig::get() const {
return root_json_;
}
nlohmann::json::reference JsonConfig::get_ref() {
return root_json_;
}
nlohmann::json::const_reference JsonConfig::get_const_ref() const {
return root_json_;
}
std::string JsonConfig::get_filename_or_data() const {
return json_file_or_data_;
}
void JsonConfig::set_with_file(const char* file) {
json_file_or_data_ = std::string{file};
ingest(true);
}
void JsonConfig::set_with_file(const std::string& file) {
json_file_or_data_ = file;
ingest(true);
}
void JsonConfig::set_with_file(std::string&& file) {
json_file_or_data_ = std::move(file);
ingest(true);
}
void JsonConfig::set_with_string(const char* string) {
json_file_or_data_ = std::string{string};
ingest(false);
}
void JsonConfig::set_with_string(const std::string& string) {
json_file_or_data_ = string;
ingest(false);
}
void JsonConfig::set_with_string(std::string&& string) {
json_file_or_data_ = std::move(string);
ingest(false);
}
void JsonConfig::ingest(bool using_a_file) {
if (using_a_file) {
if (!is_readable(json_file_or_data_)) {
throw std::logic_error(
fmt::format("The supplied JSON-file \"{}\" is not readable.",
json_file_or_data_));
}
std::ifstream file{json_file_or_data_};
file >> root_json_; // may throw JSON-specific exceptions
} else {
root_json_ = nlohmann::json::parse(json_file_or_data_);
}
}
void CLI::prepend_section(const std::string& title,
const std::string& content) {
sections_to_prepend_.emplace(sections_to_prepend_.begin(), //
title, wrap(content, 80, 8));
}
void CLI::append_section(const std::string& title, const std::string& content) {
sections_to_append_.emplace_back(title, wrap(content, 80, 8));
}
void CLI::add_description(const std::string& description) {
prepend_section("DESCRIPTION", description);
}
void CLI::add_example(const std::string& example) {
append_section("EXAMPLE", example);
}
bool CLI::parse(int argc, char** argv) {
using clipp::make_man_page;
using clipp::option;
bool help{false};
auto cli = clipp::group{};
if (!base_.empty()) {
cli = clipp::group(
base_ | (option("-h", "--help").set(help)).doc("print help message"));
} else {
cli = clipp::group(option("-h", "--help").set(help))
.doc("print help message");
}
auto cli_result = clipp::parse(argc, argv, cli);
auto man_page = make_man_page(cli, argv[0]);
if (!sections_to_prepend_.empty()) {
for (const auto& section : sections_to_prepend_) {
man_page.prepend_section(section.title(), section.content());
}
}
if (!sections_to_append_.empty()) {
for (const auto& section : sections_to_append_) {
man_page.append_section(section.title(), section.content());
}
}
int missing{0};
int blocked{0};
int conflicted{0};
for (const auto& miss : cli_result.missing()) {
if (debug_) {
std::stringstream param;
param << miss.param();
fmt::print(stderr, "missing: {}, {}\n", param.str(), miss.after_index());
}
++missing;
}
for (const auto& match : cli_result) {
if (debug_) {
std::stringstream param;
param << match.param();
fmt::print(stderr, "match: {}, arg: {}, param: {}, repeat: {}", //
match.index(), match.arg(), param.str(), match.repeat());
}
if (match.blocked()) {
if (debug_) fmt::print(stderr, ", blocked");
++blocked;
}
if (match.conflict()) {
if (debug_) fmt::print(stderr, ", conflict");
++conflicted;
}
if (debug_) fmt::print(stderr, "\n");
}
if ((missing > 0 || conflicted > 0) || help) {
if (!help) {
fmt::print(stderr,
"Parsing error: {} missing/incorrect, "
"{} blocked, {} conflicts\n\n", //
missing, blocked, conflicted);
}
fmt::print(stderr, "{}", man_page);
return false;
}
return true;
}
} // namespace exot::utilities
<file_sep>/examples/README.md
The file *[example.json](example.json)* contains an sample config file used by a JSON-configured application.
- It includes the complete settings of all currently available configurable components.
- The values in the JSON file map to settings structures containing native data types.
- Appropriate value types should be used. Type mismatch will result in an exception, which should be descriptive enough to help correct the error.
- Specific JSON←→native converters may throw exceptions if values are malformed or incorrect. The exceptions should be fairly informative. This may commonly happen for values that map to C++ enum classes, allowing only a range of possible string values.
- To use defaults defined in the C++ files either remove a key-value pair from the config, or set it to null.
For further details please review the header files to determine data types, or consult the wiki.[^1]
---
[^1]: Coming soon.
<file_sep>/include/exot/meters/cache_ff.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/cache_ff.h
* @author <NAME>
* @brief Flush + Flush meter, measures the duration of the cache flushing
* operation.
*
* @note <NAME>, <NAME>, <NAME>, and <NAME>,
* “Flush+Flush: A Fast and Stealthy Cache Attack,” in Research in
* Attacks, Intrusions, and Defenses, vol. 9721, no. 3, Cham:
* Springer International Publishing, 2016, pp. 279–299.
*/
#pragma once
#include <cstdint>
#include <exot/meters/base_shared_memory.h>
#include <exot/primitives/cache.h>
#include <exot/utilities/timing.h>
#if defined(__x86_64__)
#include <exot/primitives/tsc.h>
#else
#include <exot/utilities/timing_source.h>
#endif
namespace exot::modules {
struct cache_ff : public meter_shared_memory_base {
using meter_shared_memory_base::meter_shared_memory_base;
const char* name() const override { return "cache_ff"; }
inline __attribute__((always_inline)) std::uint64_t perform_action_on_address(
void* addr) override {
using namespace exot::utilities;
using namespace exot::primitives;
#if defined(__x86_64__)
return timeit<MemoryFencedSerialisingFlushTSC>(flush, addr);
#else
return default_timing_facility(flush, addr);
#endif
}
};
} // namespace exot::modules
<file_sep>/include/exot/components/generator_host.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/generator_host.h
* @author <NAME>
* @brief Generator host component.
*/
#pragma once
#include <chrono>
#include <mutex>
#include <set>
#include <shared_mutex>
#include <thread>
#include <tuple>
#include <type_traits>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/framework/all.h> // for framework support
#include <exot/generators/base.h> // for generators base class
#include <exot/utilities/barrier.h> // for barriers
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/ostream.h> // for ostream overloading
#include <exot/utilities/thread.h> // for ThreadTraits
#include <exot/utilities/timing.h> // for TimeKeeper
#include <exot/utilities/workers.h> // for TemplatedWorker
#ifndef GENERATOR_HOST_PERFORM_VALIDATION
#define GENERATOR_HOST_PERFORM_VALIDATION false
#endif
#ifndef GENERATOR_HOST_PROVIDE_TIMING_STATISTICS
#define GENERATOR_HOST_PROVIDE_TIMING_STATISTICS false
#endif
namespace exot::components {
/**
* @brief Template type alias for generator token types.
*/
template <typename Duration, typename Generator>
using generator_token_type =
std::tuple<Duration, typename Generator::subtoken_type>;
/**
* @brief Timed generator host.
*
* @tparam Duration The duration type
* @tparam Generator The generator class, must conform to
*/
template <typename Duration, typename Generator>
class generator_host : public Generator,
public exot::framework::IProcess,
public exot::framework::Consumer<
generator_token_type<Duration, Generator>> {
public:
struct host_options {
static constexpr bool perform_validation{
static_cast<bool>(GENERATOR_HOST_PERFORM_VALIDATION)};
static constexpr bool provide_timing_statistics{
static_cast<bool>(GENERATOR_HOST_PROVIDE_TIMING_STATISTICS)};
static constexpr bool set_affinity{true};
};
/* Type aliases. */
using node_type =
exot::framework::Consumer<generator_token_type<Duration, Generator>>;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using token_type = typename node_type::interface_type::value_type;
using subtoken_type = typename Generator::subtoken_type;
using clock_type = std::chrono::steady_clock;
using duration_type = Duration;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using policy_type = exot::utilities::SchedulingPolicy;
using barrier_type = exot::utilities::Barrier;
using timer_duration = std::chrono::nanoseconds;
using timer_type = exot::utilities::TimeKeeper<
clock_type, host_options::provide_timing_statistics, timer_duration>;
using worker_type =
exot::utilities::TemplatedWorker<exot::utilities::BarrierSynchronisation,
exot::utilities::SpecialisedThreads>;
using node_type::in_;
static_assert(exot::utilities::is_duration_v<Duration>,
"Must be a valid chrono duration type");
static_assert(exot::modules::is_generator_module<Generator>::value,
"Must be a conforming generator module");
struct settings : public exot::utilities::configurable<settings>,
public Generator::settings {
using base_t = exot::utilities::configurable<settings>;
/// @defgroup gen_worker_settings Generator host's worker settings
/// @{
std::set<unsigned> cores; //! workers' allocated cores
bool should_pin_workers{true}; //! should pin the worker threads?
policy_type worker_policy{policy_type::Other}; //! workers' sched. policy
unsigned worker_priority{90u}; //! workers' scheduling priority
/// @}
/// @defgroup gen_host_settings Generator host's master thread settings
/// @{
unsigned host_pinning{//! cpu to pin host's master thread to
std::thread::hardware_concurrency() - 1};
bool should_pin_host{true}; //! should pin the master thread?
policy_type host_policy{policy_type::Other}; //! this node's policy
unsigned host_priority{99u}; //! this node's priority
/// @}
bool use_busy_sleep{false}; //! does the host use busy sleep?
bool busy_sleep_yield{false}; //! busy sleep yields calling thread
unsigned start_check_period{1}; //! how often to check if started in µs
static_assert(
exot::utilities::is_configurable_v<typename Generator::settings>,
"Generator modules must satisfy is_configurable to be used with JSON "
"configuration.");
/* @brief The combining settings structure needs to overload this to allow
* initialising JSON configs in inherited classes. */
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
Generator::settings::set_json(root);
}
const char* name() const { return "generator"; }
auto describe() {
return base_t::describe() + Generator::settings::describe();
}
/* @brief The JSON configuration function */
void configure() {
base_t::bind_and_describe_data(
"cores", cores, "cores to pin workers to |uint[]|, e.g. [0, 2]");
base_t::bind_and_describe_data(
"should_pin_workers", should_pin_workers,
"should pin the workers? |bool|, default 'true'");
base_t::bind_and_describe_data("worker_policy", worker_policy,
"scheduling policy of the workers |str, "
"policy_type|, e.g. \"round_robin\"");
base_t::bind_and_describe_data(
"worker_priority", worker_priority,
"scheduling priority of the workers |uint|, "
"in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"host_pinning", host_pinning,
"generator host core pinning |uint|, e.g. 5");
base_t::bind_and_describe_data(
"should_pin_host", should_pin_host,
"should pin the host? |bool|, default 'true'");
base_t::bind_and_describe_data("host_policy", host_policy,
"scheduling policy of the host |str, "
"policy_type|, e.g. \"round_robin\"");
base_t::bind_and_describe_data(
"host_priority", host_priority,
"scheduling priority of the host |uint|, in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"start_check_period", start_check_period,
"state change detection update period |uint, µs|, e.g. 100");
base_t::bind_and_describe_data("use_busy_sleep", use_busy_sleep,
"should use busy sleep loop? |bool|");
base_t::bind_and_describe_data(
"busy_sleep_yield", busy_sleep_yield,
"should yield thread in busy sleep loop? |bool|");
Generator::settings::configure();
}
};
/**
* @brief Constructor
*
* @param[in] conf The configuration structure
*/
explicit generator_host(settings& conf)
: Generator(conf),
barrier_{static_cast<unsigned int>(conf_.cores.size() + 1)},
conf_{validate_settings(conf)},
global_state_{exot::framework::GLOBAL_STATE->get()} {
worker_count_ = static_cast<unsigned int>(conf_.cores.size());
local_state_ = std::make_shared<state_type>();
if constexpr (host_options::set_affinity) {
if (conf_.host_pinning >= std::thread::hardware_concurrency()) {
throw std::logic_error("Supplied wrong CPU to pin the generator_host");
}
}
if (conf_.use_busy_sleep && !conf_.busy_sleep_yield) {
debug_log_->info("[generator_host] using busy sleep w/o thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, false>);
} else if (conf_.use_busy_sleep && conf_.busy_sleep_yield) {
debug_log_->info("[generator_host] using busy sleep with thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, true>);
} else {
timer_ = timer_type(debug_log_);
}
debug_log_->info("[generator_host] using workers on cores: {}",
conf_.cores);
/* Create as many workers as cores specified in settings. */
for (auto it = conf_.cores.begin(); it != conf_.cores.end(); ++it) {
/* Bacause cores do not necessarily map to indeces, get the position of
* the iterator relative to the beginning of the vector. */
auto index = std::distance(conf_.cores.begin(), it);
auto core = *it;
debug_log_->debug(
"[generator_host] creating worker with id: {}, cpu: {}", //
index, core);
worker_threads_.emplace_back(worker_type(
local_state_->get(),
// config for SynchronisationPolicy->BarrierSynchronisation
{std::ref(barrier_)},
// config for ThreadingPolicy->SpecialisedThreads
{core, conf_.should_pin_workers, conf_.worker_policy,
conf_.worker_priority},
/* Take core and index by value, this object by reference. */
[this, core, index] {
/* Safely access the `worker_bits_` bitset and set the `enable`
* flag. */
/* Uses the comma operator to access the subtoken while holding
* the shared lock. */
auto decomposed = this->decompose_subtoken(
(std::shared_lock{subtoken_mtx_}, subtoken_), core, index);
this->generate_load(decomposed, enable_flag_, core, index);
},
debug_log_));
}
}
~generator_host() {
debug_log_->debug("[generator_host] joining worker threads");
/* Join worker threads. */
for (auto& thread : worker_threads_) {
if (thread.joinable()) thread.join();
}
debug_log_->info("[generator_host] shutting down");
if constexpr (host_options::provide_timing_statistics) {
/* Dump timpestamped offset characteristics {actual, desired, offset}. */
auto dump = std::move(timer_.dump_log());
application_log_->info(
"{},{},{}",
exot::utilities::generate_header(
conf_.name(), "timestamp", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})),
exot::utilities::generate_header(
conf_.name(), "desired", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})),
exot::utilities::generate_header(
conf_.name(), "offset", "",
exot::utilities::duration_unit(
typename timer_type::reporting_granularity{})));
for (auto& row : dump) {
if constexpr (std::is_floating_point_v<
typename timer_type::reporting_granularity::rep>) {
application_log_->info("{:.2f},{:.2f},{:.2f}", //
row[0].count(), row[1].count(),
row[2].count());
} else {
application_log_->info("{},{},{}", //
row[0].count(), row[1].count(),
row[2].count());
}
}
/* Log mean and deviation timing statistics */
debug_log_->info("[{}] offset: {}", conf_.name(),
timer_.offset_statistics());
}
}
/**
* @brief The main process
*/
void process() override {
token_type token;
std::once_flag once;
if constexpr (host_options::set_affinity) {
if (conf_.should_pin_host)
exot::utilities::ThreadTraits::set_affinity(conf_.host_pinning);
}
exot::utilities::ThreadTraits::set_scheduling(conf_.host_policy,
conf_.host_priority);
debug_log_->info("[generator_host] running on {}",
exot::utilities::thread_info());
const auto check_p = std::chrono::microseconds{conf_.start_check_period};
/**
* Starting conditions:
* - Wait until the global state is started.
*/
while (!global_state_->is_started()) {
std::this_thread::sleep_for(check_p);
}
debug_log_->info("[generator_host] starting");
while (!local_state_->is_stopped()) {
in_.read(token); // read token from the input queue
SPDLOG_LOGGER_TRACE(debug_log_, "[generator_host] read token {}", token);
/* Decompose the input token into duration and subtoken. */
duration_ = std::get<duration_type>(token);
subtoken_ = std::get<subtoken_type>(token);
if constexpr (host_options::perform_validation) {
if (!this->validate_subtoken(subtoken_)) {
debug_log_->critical(
"[generator_host] Subtoken validation failed with value: {}. "
"Aborting.",
subtoken_);
debug_log_->flush();
throw std::out_of_range(fmt::format(
"Subtoken valudation failed with value: {}", subtoken_));
}
}
/* Init timing once after the first successful read from the queue. */
std::call_once(once, [this] { timer_.begin(); });
enable_flag_ = true; // Workers start processing...
barrier_.wait(); // ... after passing the first randezvous
timer_.sleep(duration_); // Main thread sleeps...
enable_flag_ = false; // Workers finish processing.
timer_.update_offset();
if (global_state_->is_stopped() && !in_.is_readable()) {
local_state_->stop();
} else if (global_state_->is_stopped() &&
global_state_->is_terminated()) {
token_type dummy;
while (!in_.is_readable()) { in_.read(dummy); }
local_state_->stop();
}
barrier_.wait(); // Second randezvous point
}
}
/**
* @brief Check if supplied configuration conforms to sensible values
*/
settings validate_settings(settings& conf) {
if (conf.cores.empty()) throw std::logic_error("Cores cannot be empty.");
auto core_valid = [](auto el) {
return el >= 0 && el < std::thread::hardware_concurrency();
};
if (!std::all_of(conf.cores.begin(), conf.cores.end(), core_valid)) {
throw std::out_of_range(
"At least one of specified cores is out of range.");
}
return conf;
}
private:
settings conf_;
state_pointer local_state_;
state_pointer global_state_;
barrier_type barrier_;
timer_type timer_;
duration_type duration_;
subtoken_type subtoken_;
logger_pointer application_log_ =
spdlog::get("app") ? spdlog::get("app") : spdlog::stdout_color_mt("app");
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
std::atomic_bool enable_flag_{false};
mutable std::shared_mutex subtoken_mtx_;
std::vector<std::thread> worker_threads_;
unsigned worker_count_;
}; // generator_host
} // namespace exot::components
<file_sep>/include/exot/utilities/mmap.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/mmap.h
* @author <NAME>
* @brief Wrapper for Linux memory mapped files
*/
#pragma once
#if defined(__linux__)
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <initializer_list>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/helpers.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* @brief Enumeration class for mmap memory protection argument
*/
enum class MMapProt : int {
Exec = PROT_EXEC,
Read = PROT_READ,
Write = PROT_WRITE,
None = PROT_NONE
};
/**
* JSON serialisation for MMapProt
*/
NLOHMANN_JSON_SERIALIZE_ENUM(MMapProt, {
{MMapProt::Exec, "Exec"},
{MMapProt::Read, "Read"},
{MMapProt::Write, "Write"},
{MMapProt::None, "None"},
})
#if !defined(MAP_HUGE_2MB) && defined(MAP_HUGE_SHIFT)
#define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
#endif
#if !defined(MAP_HUGE_1GB) && defined(MAP_HUGE_SHIFT)
#define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
#endif
/**
* @brief Enumeration class for reasonable mmap flags
* @note Some flags might not be available, depending on how the kernel
* was compiled. Some of these options are commented out below in
* the enum and the macro serialisation mapping.
*/
enum class MMapFlag : int {
Shared = MAP_SHARED,
Private = MAP_PRIVATE,
Anonymous = MAP_ANONYMOUS,
Fixed = MAP_FIXED,
GrowsDown = MAP_GROWSDOWN,
HugeTable = MAP_HUGETLB,
#if defined(MAP_HUGE_2MB)
HugeTable2MB = MAP_HUGETLB | MAP_HUGE_2MB,
#endif
#if defined(MAP_HUGE_1GB)
HugeTable1GB = MAP_HUGETLB | MAP_HUGE_1GB,
#endif
Locked = MAP_LOCKED,
Populate = MAP_POPULATE,
PopulateNonBlock = MAP_POPULATE | MAP_NONBLOCK,
NoReserve = MAP_NORESERVE,
Stack = MAP_STACK,
#if defined(MAP_SHARED_VALIDATE)
SharedValidate = MAP_SHARED_VALIDATE,
#endif
#if defined(MAP_SHARED_VALIDATE) && defined(MAP_SYNC)
SharedValidateSync = MAP_SHARED_VALIDATE | MAP_SYNC,
#endif
#if defined(MAP_FIXED_NOREPLACE)
FixedNoReplace = MAP_FIXED_NOREPLACE,
#endif
#if defined(MAP_UNINITIALIZED)
Uninitialized = MAP_UNINITIALIZED,
#endif
};
/**
* JSON serialisation form MMapFlag
*/
NLOHMANN_JSON_SERIALIZE_ENUM(MMapFlag, {
{MMapFlag::Shared, "Shared"}, {MMapFlag::Private, "Private"},
{MMapFlag::Anonymous, "Anonymous"}, {MMapFlag::Fixed, "Fixed"},
{MMapFlag::GrowsDown, "GrowsDown"}, {MMapFlag::HugeTable, "HugeTable"},
#ifdef MAP_HUGE_2MB
{MMapFlag::HugeTable2MB, "HugeTable2MB"},
#endif
#ifdef MAP_HUGE_1GB
{MMapFlag::HugeTable1GB, "HugeTable1GB"},
#endif
{MMapFlag::Locked, "Locked"}, {MMapFlag::Populate, "Populate"},
{MMapFlag::PopulateNonBlock, "PopulateNonBlock"},
{MMapFlag::NoReserve, "NoReserve"}, {MMapFlag::Stack, "Stack"},
#if defined(MAP_SHARED_VALIDATE)
{MMapFlag::SharedValidate, "SharedValidate"},
#endif
#if defined(MAP_SHARED_VALIDATE) && defined(MAP_SYNC)
{MMapFlag::SharedValidateSync, "SharedValidateSync"},
#endif
#if defined(MAP_FIXED_NOREPLACE)
{MMapFlag::FixedNoReplace, "FixedNoReplace"},
#endif
#if defined(MAP_UNINITIALIZED)
{MMapFlag::Uninitialized, "Uninitialized"},
#endif
})
/**
* @brief Wrapper for mapping files/devices into memory via mmap
*/
class MMap {
public:
using addr_type = void*; //! 1: starting address for the mapping
using length_type = size_t; //! 2: length of the mapping (>0)
using prot_type = int; //! 3: memory protection mode
using flags_type = int; //! 4: mmap flags
using fd_type = int; //! 5: file descriptor
using offset_type = off_t; //! 6: mapping offset (multiple of page size)
/**
* @brief No default constructor
*/
MMap() = delete;
/**
* @brief Map a file into the program's memory.
*
* @param[in] filename The filename
* @param[in] starting_address The starting address
* @param[in] length The length of the mapping
* @param[in] prots The mapping's memory protection modes
* @param[in] flags The flags to pass to mmap
* @param[in] offset The starting offset of file mapping
*/
explicit MMap(const std::string& filename, //
addr_type starting_address, //
length_type length, //
std::initializer_list<MMapProt> prots, //
std::initializer_list<MMapFlag> flags, //
offset_type offset)
: filename_{filename}, length_{length} {
using namespace exot::utilities;
/* Determine if the mapping is meant to be anonymous, i.e. not backed by
* any file. */
anonymous_ = contains(MMapFlag::Anonymous, flags);
/* Compute flags and the memory protection mode. */
for (auto prot : prots) prot_ |= to_underlying_type(prot);
for (auto flag : flags) flags_ |= to_underlying_type(flag);
/* If not anonymous... */
if (!anonymous_) {
/* ...Check if the path exists. */
if (!exists(filename_)) {
throw std::logic_error(fmt::format(
"file {} does not exist and cannot be memory mapped", filename_));
}
/* ...Determine the file access mode. */
auto open_mode = O_RDONLY;
if (prot_ == to_underlying_type(MMapProt::Write)) {
open_mode = O_WRONLY;
} else if (prot_ == to_underlying_type(MMapProt::Read) |
to_underlying_type(MMapProt::Write)) {
open_mode = O_RDWR;
}
/* ...Get a file descriptor. */
if (fd_ = ::open(filename_.c_str(), open_mode); fd_ == -1) {
throw std::logic_error(
fmt::format("could not open file {}", filename_));
}
/* ...Get the file stat, especially the size in bytes. */
struct stat stat_result;
if (::fstat(fd_, &stat_result) == -1) {
throw std::logic_error(
fmt::format("fstat failed on file {}", filename_));
}
/* ...If length of 0 (or no length) is provided, map the entire file. */
if (length_ == 0) {
length_ = stat_result.st_size;
} else if (length_ > stat_result.st_size) {
throw std::logic_error(
fmt::format("cannot create mapping of length {} > file size ({} B)",
length_, stat_result.st_size));
}
} /* If anonymous... */ else { fd_ = 0; }
/* Check if offset is a multiple of the page size. */
if (offset_ = offset; offset_ % page_size_ != 0) {
throw std::logic_error(
fmt::format("offset ({}) must be a multiple of page size ({})",
offset_, page_size_));
}
if (anonymous_ && offset_ != 0) {
throw std::logic_error("anonymous mapping did not have a 0 offset");
}
/* Call the unix mmap function. */
addr_ = ::mmap(starting_address, length_, prot_, flags_, fd_, offset_);
/* Close the file descriptor. */
if (fd_ != -1) ::close(fd_);
if (addr_ == (void*)(-1) || addr_ == static_cast<addr_type>(0)) {
throw std::logic_error(
fmt::format("mmap failed{}, reason: {}",
anonymous_ ? "" : fmt::format(" on file {}", filename_),
errno != 0 ? std::strerror(errno) : "unknown"));
}
}
/**
* @brief Delegated constructor which maps the entire file
*
* @param[in] filename The filename
* @param[in] prots The mapping's memory protection modes
* @param[in] flags The flags to pass to mmap
*/
explicit MMap(const std::string& filename,
std::initializer_list<MMapProt> prots,
std::initializer_list<MMapFlag> flags)
: MMap(filename, nullptr, 0, prots, flags, 0) {}
/**
* @brief Delegated constructor for anonymous mappings
*
* @param[in] length The length of the mapping (in bytes)
* @param[in] prots The mapping's memory protection modes
* @param[in] flags The flags to pass to mmap
*/
explicit MMap(length_type length, //
std::initializer_list<MMapProt> prots,
std::initializer_list<MMapFlag> flags)
: MMap(std::string{}, nullptr, length, prots, flags, 0) {}
/**
* @brief Destroys the object.
*/
~MMap() {
/* Unmap the memory. */
auto _ = ::munmap(addr_, length_);
}
/*
* Getters
*/
// clang-format off
addr_type get_address() const { return addr_; }
length_type get_length() const { return length_; }
prot_type get_prot() const { return prot_; }
flags_type get_flags() const { return flags_; }
fd_type get_fd() const { return fd_; }
offset_type get_offset() const { return offset_; }
offset_type get_page_size() const { return page_size_; }
// clang-format on
/*
* Other
*/
bool is_anonymous() { return anonymous_; }
private:
addr_type addr_{nullptr}; //! the address returned by mmap
length_type length_{0}; //! the length of the mapping
prot_type prot_{0}; //! the mmap protection mode
flags_type flags_{0}; //! the mmap flags
fd_type fd_{-1}; //! the mmap file descriptor
offset_type offset_{0}; //! the mapping offset
std::string filename_; //! the file to map, empty by default
long page_size_{::sysconf(_SC_PAGE_SIZE)}; //! the system's page size
bool anonymous_{false}; //! is the mapping anonymous?
};
} // namespace exot::utilities
#endif
<file_sep>/src/utilities/barrier.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/barrier.cpp
* @author <NAME>
* @brief Implementation of the barrier synchronisation primitive from @ref
* barrier.h.
*/
#include <exot/utilities/barrier.h>
namespace exot::utilities {
Barrier::Barrier(unsigned int count) : desired_count_{count} {
if (count == 0) {
throw std::logic_error("Barrier count should be larger than zero.");
}
};
bool Barrier::wait() {
/* Unique lock type is used in conjunction with a condition variable. */
std::unique_lock<mutex_type> lock{mutex_};
/* Since the barrier can be reused multiple times, the repetition count is
* used to determine the changes. Aliasing does not cause any issues. */
auto repetition_count = repetition_count_;
/**
* Increment the current count as the thread reaches the barrier
*/
if (++current_count_ == desired_count_) {
/* If the current count matches the desired count, increment the
* repetition count, reset the current counter... */
repetition_count_++;
current_count_ = 0;
/* ... unlock the mutex and notify all waiting threads. */
lock.unlock();
countdown_reached_cv_.notify_all();
return true;
} else {
/* Otherwise wait until the repetition count is incremented in the block
* above. */
countdown_reached_cv_.wait(
lock, [&, this] { return repetition_count != repetition_count_; });
return false;
}
}
void Barrier::force_progress() {
{
std::lock_guard<mutex_type> lg{mutex_};
current_count_ = 0;
++repetition_count_;
}
countdown_reached_cv_.notify_all();
}
} // namespace exot::utilities
<file_sep>/include/exot/meters/base_shared_memory.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/base_shared_memory.h
* @author <NAME>
* @brief Measures contention to the hardware random number generator.
*/
#pragma once
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <memory>
#include <random>
#include <thread>
#include <utility>
#include <vector>
#include <spdlog/spdlog.h>
#if defined(__x86_64__)
#include <thread>
#include <exot/primitives/cache.h>
#include <exot/primitives/x86_64.h>
#endif
#if defined(__arm__) || defined(__aarch64__)
#include <exot/utilities/timing_source.h>
#endif
#include <exot/meters/base.h>
#include <exot/utilities/allocator.h>
#include <exot/utilities/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/mmap.h>
#include <exot/utilities/pagemap.h>
#ifndef meter_shared_memory_base_CLEVER_FOR_LOOP
#define meter_shared_memory_base_CLEVER_FOR_LOOP true
#endif
#ifndef meter_shared_memory_base_SHUFFLED_ACCESS
#define meter_shared_memory_base_SHUFFLED_ACCESS true
#endif
namespace exot::modules {
/**
* @brief Base class for meters using shared memory.
*/
struct meter_shared_memory_base : module {
using return_type = std::vector<std::uint64_t>;
/**
* @brief Performs an action on an address from the address set
* @note Must be implemented by deriving classes.
*
* @param address The address
*
* @return Cycles measurement
*/
virtual std::uint64_t perform_action_on_address(void* address) = 0;
/**
* @brief Returns the specific meter's name
* @note This function is used because we rarely redefine the 'settings'
* structure, which usually contains the meter name. Creating new
* settings would increase the amount of boilerplate.
*
* @return The name
*/
virtual const char* name() const = 0;
struct options {
static const bool clever_for_loop =
meter_shared_memory_base_CLEVER_FOR_LOOP;
static const bool shuffled_access =
meter_shared_memory_base_SHUFFLED_ACCESS;
};
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::string shm_file; //! shared memory file
bool use_huge_pages = true; //! use huge pages?
unsigned set_count = 1u; //! number of LLC sets used for communication
unsigned set_increment = 64u; //! number of cache-line-sized spaces
//! between consecutive communication sets,
//! default: page offsets (64 * line = 4096)
using cache_maps_t =
std::vector<typename exot::utilities::CacheInfo::map_type>;
std::optional<cache_maps_t> cache_info;
const char* name() const { return "cache"; }
void configure() {
bind_and_describe_data(
"shm_file", shm_file,
"the shared memory file |str|, e.g. /mnt/shm/file");
bind_and_describe_data("use_huge_pages", use_huge_pages,
"map memory with the huge pages flag? |bool|");
bind_and_describe_data(
"set_count", set_count,
"the number of sets to use |uint|, in range [1, 64]");
bind_and_describe_data("set_increment", set_increment,
"choose every nth set |uint|, e.g. 16");
bind_and_describe_data("cache_info", cache_info,
"manual cache info maps |CacheInfo[]|");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings
*/
explicit meter_shared_memory_base(settings& conf) : conf_{conf} {
using namespace exot::utilities;
llc_ = std::make_unique<CacheInfo>(
(conf_.cache_info.has_value()
? std::make_unique<CPUCacheInfo>(0, conf_.cache_info.value())
: std::make_unique<CPUCacheInfo>(0))
->llc());
if (conf_.shm_file.empty())
throw std::logic_error("Shared memory file must be provided!");
if (!exot::utilities::exists(conf_.shm_file))
throw std::logic_error("Shared memory file must exist!");
if (!exot::utilities::is_readable(conf_.shm_file))
throw std::logic_error("Shared memory file must be readable!");
if (conf_.set_count == 0)
throw std::logic_error("At least 1 set is needed for the channel!");
if (conf_.set_increment < 1)
throw std::logic_error("Set increment must be at least 1!");
if (conf_.set_increment * conf_.set_count >
llc_->number_of_sets().value()) {
throw std::logic_error(
"Set increment * set count cannot exceed the available number of "
"sets!");
}
try {
/* Defined here because type deduction of the initialiser lists will fail
* in the make_unique helper. */
auto prot =
std::initializer_list<MMapProt>{MMapProt::Read, MMapProt::Write};
auto flag = conf_.use_huge_pages
? std::initializer_list<MMapFlag>{MMapFlag::Shared,
MMapFlag::HugeTable}
: std::initializer_list<MMapFlag>{MMapFlag::Shared};
/* Unique pointer is used due to the lack of a default constructor. May
* throw if unsuccessful. */
mapping_ = std::make_unique<MMap>(conf_.shm_file, prot, flag);
} catch (const std::exception& e) {
throw std::logic_error(fmt::format(
"Mapping shared memory failed.{}\n why(): {}",
conf_.use_huge_pages ? " Make sure to provide a huge pages "
"shared memory, e.g. via hugetlbfs."
: "",
e.what()));
}
/* Advice the kernel that the memory will be accessed randomly, hoping that
* would prevent unintended prefetching of consecutive addresses. */
advise(mapping_->get_address(), mapping_->get_length(), Advice::random);
decomposer_ = std::make_unique<AddressDecomposer>(*llc_);
base_ = reinterpret_cast<std::uintptr_t>(mapping_->get_address());
auto offset = static_cast<std::uintptr_t>(0ull);
debug_log_->debug(
"[meter] created mapping of size: {:#x} from address: {:#x} "
"(physical: {:#x})",
mapping_->get_length(), base_,
resolver_(reinterpret_cast<void*>(base_)));
#if defined(__x86_64__)
/* Only hyper-threaded multicore platforms are supported, hence '/ 2'. */
const auto core_count = std::thread::hardware_concurrency() / 2;
#endif
for (auto i = 0u; i < conf_.set_count; ++i) {
auto addr = base_ + offset;
auto phys = resolver_(reinterpret_cast<void*>(addr));
auto set_index = decomposer_->get_set(phys);
#if defined(__x86_64__)
auto slice_index =
exot::primitives::slice_selection_hash(phys, core_count);
#else
auto slice_index = -1;
#endif
debug_log_->debug(
"[meter] adding address {:#x} ({:#x}) to address set, offset from "
"base: {:#8x}, set/index: {:#6x}"
#if defined(__x86_64__)
", slice: {:#b}"
#endif
,
addr, phys, offset, set_index
#if defined(__x86_64__)
,
slice_index
#endif
);
address_set_.push_back(reinterpret_cast<void*>(addr));
address_set_info_.emplace_back(reinterpret_cast<void*>(addr), set_index,
slice_index);
offset += llc_->coherency_line_size().value() * conf_.set_increment;
}
readings_.resize(address_set_.size());
/* Initialise index array. */
indeces_.resize(address_set_.size());
std::iota(indeces_.begin(), indeces_.end(), 0);
}
/**
* @brief Perform module measurement
* @note Either access the address set sequentially, or in random
* fashion using shuffled indeces. No penalty due to the shuffle
* and index access has been observed.
*
* @return The result of actions on each address in the address set
*/
return_type measure() {
if constexpr (options::shuffled_access) {
/* Shuffle the indeces array. */
std::shuffle(indeces_.begin(), indeces_.end(), rd_gen_);
/* Access using shuffled indeces */
for (auto i : indeces_) {
readings_[i] = this->perform_action_on_address(address_set_[i]);
}
} else {
for (auto i = 0; i < address_set_.size(); ++i) {
readings_[i] = this->perform_action_on_address(address_set_[i]);
}
}
return readings_;
}
/**
* @brief Gets the address set.
*
* @return The address set.
*/
const auto& get_address_set() const { return address_set_; }
/**
* @brief Gets the address set information (address, set, slice).
*
* @return The address set information.
*/
const auto& get_address_set_info() const { return address_set_info_; }
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header() {
std::vector<std::string> descriptions;
for (auto i = 0; i < address_set_.size(); ++i) {
descriptions.push_back(exot::utilities::generate_header(
this->name(), "access_time", i, "cycles"));
}
return descriptions;
}
protected:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::default_logger();
settings conf_;
return_type readings_;
std::unique_ptr<exot::utilities::MMap> mapping_;
std::uintptr_t base_;
using address_type = void*;
using address_info_type = std::tuple<address_type, int, int>;
std::vector<address_type> address_set_;
std::vector<address_info_type> address_set_info_;
std::vector<unsigned char> indeces_;
std::random_device rd_;
std::mt19937 rd_gen_{rd_()};
std::unique_ptr<exot::utilities::CacheInfo> llc_ = nullptr;
exot::utilities::AddressTranslator resolver_;
std::unique_ptr<exot::utilities::AddressDecomposer> decomposer_ = nullptr;
};
} // namespace exot::modules
<file_sep>/include/exot/utilities/eviction.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/alignment.h
* @author <NAME>
* @brief Implementation of an evicter using an eviction strategy.
*/
#pragma once
#include <type_traits>
#if defined(Evicter_DEBUG)
#include <fmt/format.h>
#define EVICT_DBG_PRINT(txt, a1, i, j, k, a2, v) \
do { \
fmt::print( \
stderr, \
"{:>20s} (@ {:16} [ i, j, k] = [{:3},{:3},{:3}] <> @ {:16} = {}\n", \
txt, fmt::ptr(a1), i, j, k, fmt::ptr(a2), v); \
} while (false)
#else
#define EVICT_DBG_PRINT(txt, a1, i, j, k, a2, v)
#endif
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* @brief Accesses memory with specific patterns.
*/
struct Evicter {
private:
std::size_t addrs_;
std::size_t accss_;
std::size_t ovrlp_;
std::size_t fwd_i_lim;
std::size_t fwd_k_lim;
std::size_t rev_i_lim;
std::size_t rev_k_lim;
public:
/**
* @brief Constructs the evicter
*
* @param[in] addresses_per_loop The number of addresses per loop
* @param[in] accesses_per_loop The number of accesses to the same address
* per loop
* @param[in] overlap_parameter The overlap parameter (step size)
*/
explicit Evicter(std::size_t addresses_per_loop, //
std::size_t accesses_per_loop, //
std::size_t overlap_parameter)
: addrs_{addresses_per_loop},
accss_{accesses_per_loop},
ovrlp_{overlap_parameter} {}
/**
* @brief Constructs the evicter
*
* @param[in] addresses_per_loop The number of addresses per loop
* @param[in] accesses_per_loop The number of accesses to the same address
* per loop
*/
explicit Evicter(std::size_t addresses_per_loop,
std::size_t accesses_per_loop)
: Evicter(addresses_per_loop, accesses_per_loop, 1) {}
/**
* @brief Default constructor
*/
Evicter() : Evicter(1u, 1u) {}
/**
* @brief Accesses (reads) addresses using a buffer
*
* @param buffer The buffer
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with non-pointer value type)
*/
template <typename T,
typename = std::enable_if_t<(
exot::utilities::is_location_accessible<T>::value &&
!std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void read(T& buffer) {
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_end = size - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) { // [0, i_end]
for (auto j = std::size_t{0}; j < accss_; ++j) { // [0, accss_)
for (auto k = std::size_t{0}; k < addrs_; ++k) { // [0, addrs_)
volatile auto _ = buffer[i + k];
EVICT_DBG_PRINT("read", std::addressof(buffer), i, j, k,
std::addressof(buffer[i + k]), _);
}
}
}
}
/**
* @brief Accesses (reads) addresses contained in a buffer
*
* @param buffer The buffer
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with pointer value type)
*/
template <typename T,
typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void read_ptrs(T& buffer) {
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_end = size - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = std::size_t{0}; k < addrs_; ++k) {
volatile auto _ = *(buffer[i + k]);
EVICT_DBG_PRINT("read_ptrs", std::addressof(buffer), i, j, k,
buffer[i + k], _);
}
}
}
}
/**
* @brief Accesses (reads) addresses using a base pointer and length
*
* @param address The address
* @param[in] length The length
*
* @tparam T The type
* @tparam <unnamed> Template helper (only pointer types)
*/
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
void read(T address, std::size_t length) {
if (addrs_ >= length) throw std::out_of_range("addrs_ >= length");
auto i_end = length - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = std::size_t{0}; k < addrs_; ++k) {
volatile auto _ = *(address + i + k);
EVICT_DBG_PRINT("read", address, i, j, k, (address + i + k), _);
}
}
}
}
/**
* @brief Accesses (writes) addresses using a buffer
*
* @param buffer The buffer
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with non-pointer value type)
*/
template <typename T,
typename = std::enable_if_t<(
exot::utilities::is_location_accessible<T>::value &&
!std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void write(T& buffer, volatile typename T::value_type value) {
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_end = size - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = std::size_t{0}; k < addrs_; ++k) {
buffer[i + k] = value;
EVICT_DBG_PRINT("write", std::addressof(buffer), i, j, k,
std::addressof(buffer[i + k]), value);
}
}
}
}
/**
* @brief Accesses (writes) addresses contained in a buffer
*
* @param buffer The buffer
* @param[in] value The value
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with pointer value type)
*/
template <typename T,
typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void write_ptrs(T& buffer, volatile typename T::value_type value) {
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_end = size - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = std::size_t{0}; k < addrs_; ++k) {
*(buffer[i + k]) = value;
EVICT_DBG_PRINT("write_ptrs", std::addressof(buffer), i, j, k,
buffer[i + k], value);
}
}
}
}
/**
* @brief Accesses (writes) addresses using a base pointer and length
*
* @param address The address
* @param[in] length The length
*
* @tparam T The type
* @tparam <unnamed> Template helper (only pointer types)
*/
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
void write(T address, std::size_t length, volatile T value) {
if (addrs_ >= length) throw std::out_of_range("addrs_ >= length");
auto i_end = length - addrs_;
for (auto i = std::size_t{0}; i <= i_end; i += ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = std::size_t{0}; k < addrs_; ++k) {
*(address + i + k) = value;
EVICT_DBG_PRINT("write", address, i, j, k, (address + i + k), value);
}
}
}
}
/****************************************************************************
* REVERSED *
****************************************************************************/
/**
* @brief Accesses (reads) addresses using a buffer in reverse order
*
* @param buffer The buffer
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with non-pointer value type)
*/
template <typename T,
typename = std::enable_if_t<(
exot::utilities::is_location_accessible<T>::value &&
!std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void read_in_reverse(T& buffer) {
using ssize_t = signed long long;
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_begin = static_cast<ssize_t>(size - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) { // [i_begin, 0]
for (auto j = std::size_t{0}; j < accss_; ++j) { // [0, accss_)
for (auto k = k_begin; k >= ssize_t{0}; --k) { // [k_begin, 0]
volatile auto _ = buffer[i + k];
EVICT_DBG_PRINT("read_in_reverse", std::addressof(buffer), i, j, k,
std::addressof(buffer[i + k]), _);
}
}
}
}
/**
* @brief Accesses (reads) addresses contained in a buffer in reverse
* order
*
* @param buffer The buffer
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with pointer value type)
*/
template <typename T,
// typename = std::void_t<typename std::decay_t<T>::value_type>,
typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void read_ptrs_in_reverse(T& buffer) {
using ssize_t = signed long long;
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_begin = static_cast<ssize_t>(size - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = k_begin; k >= ssize_t{0}; --k) {
volatile auto _ = *(buffer[i + k]);
EVICT_DBG_PRINT("read_ptrs_in_reverse", std::addressof(buffer), i, j,
k, buffer[i + k], _);
}
}
}
}
/**
* @brief Accesses (reads) addresses using a base pointer and length in
* reverse order
*
* @param address The address
* @param[in] length The length
*
* @tparam T The type
* @tparam <unnamed> Template helper (only pointer types)
*/
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
void read_in_reverse(T address, std::size_t length) {
using ssize_t = signed long long;
if (addrs_ >= length) throw std::out_of_range("addrs_ >= length");
auto i_begin = static_cast<ssize_t>(length - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = k_begin; k >= ssize_t{0}; --k) {
volatile auto _ = *(address + i + k);
EVICT_DBG_PRINT("read_in_reverse", address, i, j, k,
(address + i + k), _);
}
}
}
}
/**
* @brief Accesses (writes) addresses using a buffer in reverse order
*
* @param buffer The buffer
* @param[in] value The value
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with non-pointer value type)
*/
template <typename T,
typename = std::enable_if_t<(
exot::utilities::is_location_accessible<T>::value &&
!std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void write_in_reverse(T& buffer, volatile typename T::value_type value) {
using ssize_t = signed long long;
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_begin = static_cast<ssize_t>(size - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = k_begin; k >= ssize_t{0}; --k) {
buffer[i + k] = value;
EVICT_DBG_PRINT("write_in_reverse", std::addressof(buffer), i, j, k,
std::addressof(buffer[i + k]), value);
}
}
}
}
/**
* @brief Accesses (writes) addresses contained in a buffer in reverse
* order
*
* @param buffer The buffer
* @param[in] value The value
*
* @tparam T The type of the buffer
* @tparam <unnamed> Template helper (only types with methods `size`,
* `at, `operator[]`, and with pointer value type)
*/
template <typename T,
typename = std::enable_if_t<
(exot::utilities::is_location_accessible<T>::value &&
std::is_pointer<typename std::decay_t<T>::value_type>::value)>>
void write_ptrs_in_reverse(T& buffer, volatile typename T::value_type value) {
using ssize_t = signed long long;
static auto size = buffer.size();
if (addrs_ >= size) throw std::out_of_range("addrs_ >= size");
auto i_begin = static_cast<ssize_t>(size - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = k_begin; k >= ssize_t{0}; --k) {
*(buffer[i + k]) = value;
EVICT_DBG_PRINT("write_ptrs_in_reverse", std::addressof(buffer), i, j,
k, buffer[i + k], value);
}
}
}
}
/**
* @brief Accesses (writes) addresses using a base pointer and length in
* reverse order
*
* @param address The address
* @param[in] length The length
* @param[in] value The value
*
* @tparam T The type
* @tparam <unnamed> Template helper (only pointer types)
*/
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
void write_in_reverse(T address, std::size_t length, volatile T value) {
using ssize_t = signed long long;
if (addrs_ >= length) throw std::out_of_range("addrs_ >= length");
auto i_begin = static_cast<ssize_t>(length - addrs_);
auto k_begin = static_cast<ssize_t>(addrs_) - 1;
for (auto i = i_begin; i >= ssize_t{0}; i -= ovrlp_) {
for (auto j = std::size_t{0}; j < accss_; ++j) {
for (auto k = k_begin; k >= ssize_t{0}; --k) {
*(address + i + k) = value;
EVICT_DBG_PRINT("write_in_reverse", address, i, j, k,
(address + i + k), value);
}
}
}
}
};
} // namespace exot::utilities
<file_sep>/src/meters/power_msr.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/power_msr.cpp
* @author <NAME>
* @brief Implementation of the MSR power metering module.
*/
#if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
#include <exot/meters/power_msr.h>
namespace exot::modules {
power_msr::power_msr(settings& conf) : conf_{conf}, msr_{} {
/* If no domains were provided, fall back to default. */
if (conf_.domains.empty()) {
conf_.domains = {rapl_domain::pp0, rapl_domain::pkg};
}
for (auto domain : conf_.domains) {
debug_log_->info("[power_msr] using domain: {}", domain_to_string(domain));
}
/* Allocate output vector. */
output_.resize(conf_.domains.size());
/* Get energy unit in which energy is reported, defined as "Energy related
* information (in Joules) is based on the multiplier, 1/2^ESU; where ESU is
* an unsigned integer represented by bits 12:8." in "Intel® 64 and IA-32
* Architectures Software Developer’s Manual", 2016. */
energy_status_unit_ =
1.0 / static_cast<double>(1ULL << exot::utilities::extract_bit_range(
msr_.read_first(RAPL_POWER_UNIT), 8u, 12u));
debug_log_->info("[power_msr] using RAPL power unit: {:e}",
energy_status_unit_);
/* Bootstrap readings */
previous_time_point_ = std::chrono::steady_clock::now();
for (auto domain : conf_.domains) {
old_readings_[domain] = get_energy(domain);
}
/* Sleeping for a short moment so that there is a meaningful value once the
* meter is started. In most processors the values in the MSR appear every
* ~1ms, if the time between consecutive reads is shorter, the power will be
* reported as 0. */
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
typename power_msr::return_type power_msr::measure() {
auto now = std::chrono::steady_clock::now();
double elapsed_time =
std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1>>>(
now - previous_time_point_)
.count(); // elapsed time in seconds
previous_time_point_ = now;
auto i = 0; /*! used to access output elements in a range-for loop. */
/* Iterate through configured power domains and compute average power over
* the elapsed_time period. */
for (auto domain : conf_.domains) {
readings_[domain] = get_energy(domain);
output_.at(i++) =
energy_to_power(readings_[domain], old_readings_[domain], elapsed_time);
}
old_readings_ = readings_;
return output_;
}
std::vector<std::string> power_msr::header() {
std::vector<std::string> description;
for (auto domain : conf_.domains) {
description.push_back(exot::utilities::generate_header(
conf_.name(), "rapl_domain", domain_to_string(domain),
DefaultUnits::power));
}
return description;
}
std::string power_msr::domain_to_string(rapl_domain d) {
switch (d) {
case rapl_domain::pp0:
return "pp0";
case rapl_domain::pp1:
return "pp1";
case rapl_domain::pkg:
return "pkg";
case rapl_domain::sys:
return "sys";
default:
return "";
}
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/meters/cache_l1.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/cache_l1.h
* @author <NAME>
* @brief Measures time to access a buffer filling the L1 cache.
*/
#pragma once
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory> // for std::shared_ptr
#include <string> // for std::string
#include <thread> // for threads
#include <vector> // for variable-size arrays
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/barrier.h>
#include <exot/utilities/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/helpers.h>
namespace exot::modules {
/**
* @brief The empirical frequency meter
*/
struct cache_l1 : module {
using return_type = std::vector<std::uint64_t>;
using barrier_type = exot::utilities::Barrier;
using probe_type = int;
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<unsigned> cores; //! vector of cores
using cache_maps_t =
std::vector<typename exot::utilities::CacheInfo::map_type>;
std::optional<cache_maps_t> cache_info;
const char* name() const { return "cache_l1"; }
/* @brief The JSON configuration function */
void configure() {
bind_and_describe_data(
"cores", cores, "cores to run workers on |uint[]|, e.g. [1, 2, 3]");
bind_and_describe_data("cache_info", cache_info,
"manual cache info maps |CacheInfo[]|");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings structure
*/
explicit cache_l1(settings&);
~cache_l1();
/**
* @brief Perform measurement
*
* @return A vector with time measurements (in cycles)
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
settings conf_;
return_type readings_;
std::vector<std::thread> threads_;
barrier_type barrier_;
std::atomic<bool> flag_{true};
std::atomic_flag worker_flag_ = ATOMIC_FLAG_INIT;
/**
* Parameters as defined by [1] in Algorithm 2 (p. 8):
*
* - n : number of L1 ways;
* - o : log2(L1 line size), width of the 'offset' field in the address;
* - s : log2(L1 set count), width of the 'set' field in the address;
* - b : size of the buffer to allocate.
*
* [1] <NAME>, <NAME>, <NAME>, and <NAME>, “C5: Cross-Cores
* Cache Exot Channel.,” DIMVA, vol. 9148, no. 3, pp. 46–64, 2015.
*/
int n_; //! number of L1 ways
int o_; //! offset field width
int s_; //! set/index field width
int b_; //! buffer size
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
} // namespace exot::modules
<file_sep>/include/exot/framework/interface.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/interface.h
* @author <NAME>
* @brief Interfaces abstracting to queues and other transmission media.
*/
#pragma once
#include <chrono> // for time_point and duration
#include <memory>
namespace exot::framework {
/**
* Mostly adapter classes.
*/
/**
* Virtual inheritance avoids copies of the base class object. */
/**
* @brief Basic reader interface, defining `read()` and `is_readable()`
* pure virtual methods.
*
* @tparam Token Data type used by the interface
*/
template <typename Token>
struct IReader {
virtual ~IReader() = default;
virtual void read(Token&) = 0;
virtual bool is_readable() = 0;
};
/**
* @brief Basic reader interface, defining `write()` and `is_writeable()`
* pure virtual methods.
*
* @tparam Token Data type used by the interface
*/
template <typename Token>
struct IWriter {
virtual ~IWriter() = default;
virtual void write(const Token&) = 0;
virtual void write(Token&&) = 0;
virtual bool is_writable() = 0;
};
/**
* @brief Base reader class
* @details Defines a shared pointer to the channel/container, a method to
* set that pointer, and a few member types, which can be used to
* access internal types from outside of the interfaces.
*
* @tparam Token Data type used by the interface
* @tparam Container Type of channel/container used for communication
*/
template <typename Token, template <typename...> typename Container>
class Reader {
public:
using value_type = Token; //! token type transported via the reader interface
using container_type =
Container<value_type>; //! container used by the reader
using container_pointer =
std::shared_ptr<container_type>; //! shared pointer to the container
Reader() = default;
explicit Reader(container_pointer container) : in_container_ptr_(container){};
/**
* @brief Set the pointer to the reader's container/channel
*
* @param[in] container The pointer to the container
*/
void set_read_container(container_pointer container) {
in_container_ptr_ = container;
}
/**
* @brief Get the pointer to the reader's container/channel
*
* @return The pointer to the container
*/
container_pointer get_read_container() const { return in_container_ptr_; }
protected:
container_pointer in_container_ptr_; //! internal container pointer,
//! accessible by derived classes
};
/**
* @brief Base writer class
* @details Defines a shared pointer to the channel/container, a method to
* set that pointer, and a few member types, which can be used to
* access internal types from outside of the interfaces.
*
* @tparam Token Data type used by the interface
* @tparam Container Type of channel/container used for communication
*/
template <typename Token, template <typename...> typename Container>
class Writer {
public:
using value_type = Token; //! token type transported via the reader interface
using container_type =
Container<value_type>; //! container used by the reader
using container_pointer =
std::shared_ptr<container_type>; //! shared pointer to the container
Writer() = default;
explicit Writer(container_pointer container)
: out_container_ptr_(container){};
/**
* @brief Set the pointer to the writer's container/channel
*
* @param[in] container The pointer to the container
*/
void set_write_container(container_pointer container) {
out_container_ptr_ = container;
}
/**
* @brief Get the pointer to the writer's container/channel
*
* @return The pointer to the container
*/
container_pointer get_write_container() const { return out_container_ptr_; }
protected:
container_pointer out_container_ptr_;
};
/**
* @brief Reader class for accessing queue-like structures.
*/
template <typename Token, template <typename...> typename Container>
class QueueReader : public IReader<Token>, public Reader<Token, Container> {
public:
/**
* This states that the class uses the constructor of the inherited class.
*/
using Reader<Token, Container>::Reader;
using Reader<Token,
Container>::in_container_ptr_; //! Necessary for name lookup
/**
* @brief Get the size of the underlying container
* @details In addition to the basic operations, the queue interface also
* provides methods to access the number of elements in the
* container.
*
* @return The size of the container
*/
inline unsigned long size() { return in_container_ptr_->size(); }
/**
* @brief Read and pop a token from the queue
* @details Each read operation is destructive, the interface does not
* allow peeking into the queue.
*
* @param token The popped token
*/
inline void read(Token& token) override {
token = in_container_ptr_->front();
in_container_ptr_->pop();
}
/**
* @brief Determines if the queue is readable
* @details The basic queue only provides methods to check if it is empty.
* A non-empty queue is considered readable, i.e. a read operation
* will return a value.
*
* @return True if readable, False otherwise.
*/
inline bool is_readable() override { return !in_container_ptr_->empty(); }
};
/**
* @brief Writer class for accessing queue-like structures.
*/
template <typename Token, template <typename...> typename Container>
class QueueWriter : public IWriter<Token>, public Writer<Token, Container> {
public:
/**
* This states that the class uses the constructor of the inherited class.
*/
using Writer<Token, Container>::Writer;
using Writer<Token, Container>::out_container_ptr_;
/**
* @brief Get the size of the underlying container
*
* @return The size of the container
*/
inline unsigned long size() { return out_container_ptr_->size(); }
/**
* @brief Write a token to the queue via its const reference
*
* @param[in] token The token to write to the queue
*/
inline void write(const Token& token) override {
out_container_ptr_->push(token);
}
/**
* @brief Write a token to the queue via a move operation
* @details The function only perfect-forwards its argument, the call to
* `std::move` must be performed in the calling code.
*
* @param[in] token The token to write to the queue
*/
inline void write(Token&& token) override {
out_container_ptr_->push(std::forward<decltype(token)>(token));
}
/**
* @brief Determines if the underlying container is writable.
* @details The basic queue is not bounded, therefore the call to this
* function will always return true.
*
* @return True
*/
inline bool is_writable() override { return true; }
};
/**
* @brief Reader class for accessing queue-like structures that provide
* additional functionality of `try_pop`, `try_pop_for`, etc.
*/
template <typename Token, template <typename...> typename Container>
class ExtendedQueueReader : public QueueReader<Token, Container> {
public:
/**
* This states that the class uses the constructor of the inherited class.
*/
using QueueReader<Token, Container>::QueueReader;
using QueueReader<Token, Container>::in_container_ptr_;
/**
* @brief Forwarding wrapper for the `try_pop` method.
*/
inline bool try_read(Token& token) {
return in_container_ptr_->try_pop(std::forward<decltype(token)>(token));
};
/**
* @brief Forwarding wrapper for the `try_pop_for` method.
*/
template <typename Rep, typename Period>
inline bool try_read_for(Token& token,
const std::chrono::duration<Rep, Period>& timeout) {
return in_container_ptr_->try_pop_for(
std::forward<decltype(token)>(token),
std::forward<decltype(timeout)>(timeout));
};
/**
* @brief Forwarding wrapper for the `try_pop_until` method.
*/
template <typename Clock, typename Duration>
inline bool try_read_until(
Token& token, const std::chrono::time_point<Clock, Duration>& time) {
return in_container_ptr_->try_pop_until(
std::forward<decltype(token)>(token),
std::forward<decltype(time)>(time));
};
};
/**
* @brief Reader class for accessing queue-like structures that provide
* additional functionality of `try_push`, `try_push_for`, etc.
*/
template <typename Token, template <typename...> typename Container>
class ExtendedQueueWriter : public QueueWriter<Token, Container> {
public:
/**
* This states that the class uses the constructor of the inherited class.
*/
using QueueWriter<Token, Container>::QueueWriter;
using QueueWriter<Token, Container>::out_container_ptr_;
/**
* @brief Forwarding wrapper for the `try_push` method.
*/
inline bool try_write(const Token& token) {
return out_container_ptr_->try_push(std::forward<decltype(token)>(token));
};
/**
* @brief Forwarding wrapper for the `try_push` method.
*/
inline bool try_write(Token&& token) {
return out_container_ptr_->try_push(std::forward<decltype(token)>(token));
};
/**
* @brief Forwarding wrapper for the `try_push_for` method.
*/
template <typename Rep, typename Period>
inline bool try_write_for(const Token& token,
const std::chrono::duration<Rep, Period>& timeout) {
return out_container_ptr_->try_push_for(
std::forward<decltype(token)>(token),
std::forward<decltype(timeout)>(timeout));
};
/**
* @brief Forwarding wrapper for the `try_push_for` method.
*/
template <typename Rep, typename Period>
inline bool try_write_for(Token&& token,
const std::chrono::duration<Rep, Period>& timeout) {
return out_container_ptr_->try_push_for(
std::forward<decltype(token)>(token),
std::forward<decltype(timeout)>(timeout));
};
/**
* @brief Forwarding wrapper for the `try_push_until` method.
*/
template <typename Clock, typename Duration>
inline bool try_write_until(
const Token& token,
const std::chrono::time_point<Clock, Duration>& time) {
return out_container_ptr_->try_push_until(
std::forward<decltype(token)>(token),
std::forward<decltype(time)>(time));
};
/**
* @brief Forwarding wrapper for the `try_push_until` method.
*/
template <typename Clock, typename Duration>
inline bool try_write_until(
Token&& token, const std::chrono::time_point<Clock, Duration>& time) {
return out_container_ptr_->try_push_until(
std::forward<decltype(token)>(token),
std::forward<decltype(time)>(time));
};
/**
* @brief Determines if the underlying container is writable.
* @details The extended queue can be bounded, and provides a `full()`
* method.
*
* @return True if writeable, false otherwise.
*/
inline bool is_writable() override { return out_container_ptr_->full(); }
};
} // namespace exot::framework
<file_sep>/include/exot/generators/base_shared_memory.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/base_shared_memory.h
* @author <NAME>
* @brief Base class for generators using shared memory.
*/
#pragma once
#include <cstdint>
#include <limits>
#include <memory>
#include <thread>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/utilities/allocator.h>
#include <exot/utilities/bits.h>
#include <exot/utilities/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/helpers.h>
#include <exot/utilities/mmap.h>
#include <exot/utilities/pagemap.h>
#if defined(__x86_64__)
#include <thread>
#include <exot/primitives/cache.h>
#include <exot/primitives/x86_64.h>
#endif
#ifndef shared_memory_generator_base_CLEVER_FOR_LOOP
#define shared_memory_generator_base_CLEVER_FOR_LOOP true
#endif
#ifndef shared_memory_generator_base_REPEAT
#define shared_memory_generator_base_REPEAT 1
#endif
#ifndef shared_memory_generator_base_YIELD_IN_GENERATE
#define shared_memory_generator_base_YIELD_IN_GENERATE true
#endif
#if defined(SPDLOG_TRACE_ON)
static auto count{0ull};
#define INCREMENT_COUNT() ++count
#else
#define INCREMENT_COUNT()
#endif
namespace exot::modules {
struct shared_memory_generator_base {
using subtoken_type = uint_fast64_t; //
using decomposed_type = uint_fast64_t; //
using core_type = unsigned; // core number
using index_type = std::size_t; // thread index
using enable_flag_type = std::atomic_bool;
using logger_pointer = std::shared_ptr<spdlog::logger>;
/**
* @brief Performs an action on an address from the address set
* @note Must be implemented by deriving classes.
*
* @param address The address
*/
virtual void perform_action_on_address(void* address) = 0;
struct options {
static const bool clever_for_loop =
shared_memory_generator_base_CLEVER_FOR_LOOP;
static const std::size_t repetitions = shared_memory_generator_base_REPEAT;
static const bool yield_in_generate =
shared_memory_generator_base_YIELD_IN_GENERATE;
};
struct settings : public exot::utilities::configurable<settings> {
std::string shm_file; //! shared memory file
bool use_huge_pages = false; //! use huge pages?
unsigned set_count = 1u; //! number of LLC sets used for communication
unsigned set_increment = 64u; //! number of cache-line-sized spaces
//! between consecutive communication sets,
//! default: page offsets (64 * line = 4096)
using cache_maps_t =
std::vector<typename exot::utilities::CacheInfo::map_type>;
std::optional<cache_maps_t> cache_info;
const char* name() const { return "generator"; }
void configure() {
bind_and_describe_data(
"shm_file", shm_file,
"the shared memory file |str|, e.g. /mnt/shm/file");
bind_and_describe_data("use_huge_pages", use_huge_pages,
"map memory with the huge pages flag? |bool|");
bind_and_describe_data(
"set_count", set_count,
"the number of sets to use |uint|, in range [1, 64]");
bind_and_describe_data("set_increment", set_increment,
"choose every nth set |uint|, e.g. 16");
bind_and_describe_data("cache_info", cache_info,
"manual cache info maps |CacheInfo[]|");
}
};
explicit shared_memory_generator_base(settings& conf) : conf_{conf} {
using namespace exot::utilities;
if (conf_.shm_file.empty())
throw std::logic_error("Shared memory file must be provided!");
if (!exot::utilities::exists(conf_.shm_file))
throw std::logic_error("Shared memory file must exist!");
if (!exot::utilities::is_readable(conf_.shm_file))
throw std::logic_error("Shared memory file must be readable!");
if (conf_.set_count == 0)
throw std::logic_error("At least 1 set is needed for the channel!");
if (conf_.set_count > 64)
throw std::logic_error(
"Shared memory-based generators support only up to 64 lines!");
if (conf_.set_increment < 1)
throw std::logic_error("Set increment must be at least 1!");
validator_ = conf_.set_count == 64
? std::numeric_limits<std::uint_fast64_t>::max()
: (std::uint_fast64_t{1} << conf_.set_count) -
std::uint_fast64_t{1};
try {
auto prot =
std::initializer_list<MMapProt>{MMapProt::Read, MMapProt::Write};
auto flag = conf_.use_huge_pages
? std::initializer_list<MMapFlag>{MMapFlag::Shared,
MMapFlag::HugeTable}
: std::initializer_list<MMapFlag>{MMapFlag::Shared};
/* May throw if unsuccessful. */
logger_->debug("[generator] creating mapping of {}", conf_.shm_file);
mapping_ = std::make_unique<MMap>(conf_.shm_file, prot, flag);
} catch (const std::exception& e) {
throw std::logic_error(fmt::format(
"Mapping shared memory failed.{}\n why(): {}",
conf_.use_huge_pages ? " Make sure to provide a huge pages "
"shared memory, e.g. via hugetlbfs."
: "",
e.what()));
}
/* Advice the kernel that the memory will be accessed randomly, hoping that
* would prevent unintended prefetching of consecutive addresses. */
logger_->debug("[generator] advising the kernel about the mapped mem.");
advise(mapping_->get_address(), mapping_->get_length(), Advice::random);
auto llc = (conf_.cache_info.has_value()
? CPUCacheInfo(0, conf_.cache_info.value())
: CPUCacheInfo(0))
.llc();
auto resolver = AddressTranslator();
auto decomposer = AddressDecomposer(llc);
base_ = reinterpret_cast<std::uintptr_t>(mapping_->get_address());
auto offset = static_cast<std::uintptr_t>(0ull);
logger_->debug(
"[generator] created mapping of size: {:#x} from address: {:#x} "
"(physical: {:#x})",
mapping_->get_length(), base_,
resolver(reinterpret_cast<void*>(base_)));
#if defined(__x86_64__)
/* Only hyper-threaded multicore platforms are supported, hence '/ 2'. */
const auto core_count = std::thread::hardware_concurrency() / 2;
#endif
for (auto i = 0u; i < conf_.set_count; ++i) {
auto addr = base_ + offset;
auto phys = resolver(reinterpret_cast<void*>(addr));
auto set_index = decomposer.get_set(phys);
#if defined(__x86_64__)
auto slice_index =
exot::primitives::slice_selection_hash(phys, core_count);
#else
auto slice_index = -1;
#endif
logger_->debug(
"[generator] adding address {:#x} ({:#x}) to address set, offset "
"from base: {:#8x}, set/index: {:#6x}"
#if defined(__x86_64__)
", slice: {:#b}"
#endif
,
addr, phys, offset, set_index
#if defined(__x86_64__)
,
slice_index
#endif
);
address_set_.push_back(reinterpret_cast<void*>(addr));
offset += llc.coherency_line_size().value() * conf_.set_increment;
}
}
inline decomposed_type decompose_subtoken(const subtoken_type& subtoken,
core_type core, index_type index) {
return subtoken;
}
inline bool validate_subtoken(const subtoken_type& subtoken) {
return subtoken <= validator_;
}
/**
* @note Must be implemented by inheriting classes.
*/
inline void generate_load(const decomposed_type& decomposed_subtoken,
const enable_flag_type& flag, core_type core,
index_type index) {
/* Skip if no bit set in decompose_subtoken. */
if (decomposed_subtoken != 0) {
SPDLOG_LOGGER_TRACE(logger_,
"Decomposed non-zero token on core {}: {:#b}", core,
decomposed_subtoken);
#if defined(SPDLOG_TRACE_ON)
count = 0ull;
#endif
/* Access until flag is set to false. */
while (flag) {
generate_load_helper(decomposed_subtoken);
if constexpr (options::yield_in_generate) { std::this_thread::yield(); }
} // while(flag)
SPDLOG_LOGGER_TRACE(logger_, "Performed {} actions on core {}",
count * options::repetitions, core);
} // if (decomposed_subtoken != 0)
}
/**
* @brief Generates "load" on the address set according to the subtoken
*
* @param[in] decomposed_subtoken The decomposed subtoken
*/
inline __attribute__((always_inline)) void generate_load_helper(
const decomposed_type& decomposed_subtoken) {
/* Method 1: efficiently access set bits in decomposed_subtoken. */
if constexpr (options::clever_for_loop) {
exot::utilities::loop_through_set_bits(
decomposed_subtoken, [&](std::size_t i) {
INCREMENT_COUNT();
exot::utilities::const_for<0, options::repetitions>(
[&, this](const auto) {
perform_action_on_address(address_set_[i]);
});
});
}
/* Method 2: iterate and test individual bits. */
else {
for (auto i{0u}; i < address_set_.size(); ++i) {
if (exot::utilities::test_bit(decomposed_subtoken, i)) {
INCREMENT_COUNT();
exot::utilities::const_for<0, options::repetitions>(
[&, this](const auto) {
perform_action_on_address(address_set_[i]);
});
}
}
} // if constexpr (options::clever_for_loop)
}
/**
* @brief Gets the address set.
*
* @return The address set.
*/
const auto& get_address_set() const { return address_set_; }
protected:
settings conf_;
logger_pointer logger_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
uint_fast64_t validator_;
std::unique_ptr<exot::utilities::MMap> mapping_;
std::vector<void*> address_set_;
std::uintptr_t base_;
};
} // namespace exot::modules
<file_sep>/include/exot/meters/rdseed_status.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/rdseed_status.h
* @author <NAME>
* @brief Measures contention to the hardware random number generator.
*/
#pragma once
#if defined(__x86_64__)
#include <atomic>
#include <cstdint>
#include <string>
#include <thread>
#include <vector>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/primitives/rng.h>
#include <exot/utilities/barrier.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/thread.h>
namespace exot::modules {
/**
* @brief Measurement module for checking if a RDSEED operation can
* complete immediately.
*/
struct rdseed_status : module {
using raw_type = std::uint8_t;
using return_type = bool;
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
unsigned core{0u};
const char* name() const { return "rdseed_status"; }
void configure() {
bind_and_describe_data("core", core, "worker pinning |uint|");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings
*/
explicit rdseed_status(settings& conf) : barrier_(2), conf_{conf} {
worker_thread_ = std::move(std::thread([this]() {
exot::utilities::ThreadTraits::set_affinity(conf_.core);
exot::utilities::ThreadTraits::set_scheduling(
exot::utilities::SchedulingPolicy::RoundRobin, 90);
debug_log_->debug("[rdseed_status] worker thread: {}",
exot::utilities::thread_info());
while (active_.load()) {
barrier_.wait();
exot::primitives::seed64();
exot::primitives::seed64();
exot::primitives::seed64();
exot::primitives::seed64();
exot::primitives::check_seed64(reading_);
barrier_.wait();
}
}));
}
~rdseed_status() {
active_.store(false);
barrier_.wait();
barrier_.wait();
if (!worker_thread_.joinable()) barrier_.force_progress();
worker_thread_.join();
}
/**
* @brief Perform module measurement
*
* @return The RDSEED operation status
*/
return_type measure() {
barrier_.wait();
barrier_.wait();
return static_cast<return_type>(reading_);
}
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header() {
return {exot::utilities::generate_header(conf_.name(), "status", "", "")};
}
private:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_;
raw_type reading_;
exot::utilities::Barrier barrier_;
std::thread worker_thread_;
std::atomic_bool active_{true};
};
} // namespace exot::modules
#endif
<file_sep>/include/exot/utilities/barrier.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/barrier.h
* @author <NAME>
* @brief Barrier synchronisation primitive using only the STL.
*/
#pragma once
#include <condition_variable> // for std::condition_variable
#include <mutex> // for mutexes
#include <stdexcept> // for throwing
namespace exot::utilities {
/**
* @brief The barrier thread synchronisation primitive, also known as a
* randezvous point
* @details As each thread arrives at the barrier, it increments a counter,
* which states how many threads in total have reached the
* randezvous point. Threads lock on a mutex and are descheduled
* until the number of threads at the barrier is equal to the
* specified count. The thread last to reach the barrier unlocks the
* mutex and notifies all waiting threads.
*
* The interface is modelled after barriers found in projects
* 'boost/thread' and 'boost/fiber'.
*/
class Barrier {
public:
using mutex_type = std::mutex;
using cv_type = std::condition_variable;
/**
* @brief No default constructor
*/
Barrier() = delete;
/**
* @brief Constructs the object with desired number of threads that need
* to reach the barrier
*
* @param[in] count The number of threads required for passing the barrier
*/
explicit Barrier(unsigned int count);
~Barrier() = default;
/**
* @brief Waits until the number of threads at the barrier is equal to
* the desired count.
*
* @return Last thread to enter the barrier returns true, others return
* false.
*/
bool wait();
/**
* @brief Forces progress even if not all threads have reached the barrier
*/
void force_progress();
private:
volatile unsigned int desired_count_; //! The number of threads that have to
//! reach the randezvous point
volatile unsigned int current_count_{0}; //! The current number of threads at
//! the randezvous point
volatile unsigned int repetition_count_{0}; //! The number of times the
//! barrier was reused
mutex_type mutex_; //! The mutex used for thread-safe access to variables
cv_type countdown_reached_cv_; //! The condition variable used for waiting
//! and notifications
};
} // namespace exot::utilities
<file_sep>/include/exot/generators/base.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/base.h
* @author <NAME>
* @brief Definition of the loadgen base class and template helpers.
*/
#pragma once
#include <type_traits>
#include <exot/utilities/configuration.h>
namespace exot::modules {
/**
* @brief Determine if a type is a valid generator type.
* @details A class is deemed a valid generator module, if it has a few
* member types (subtoken_type, core_type, index_type,
* decomposed_type, enable_flag_type, and settings), and at least 3
* main methods (decompose_subtoken, validate_subtoken,
* generate_load), with appropriate signatures.
*
* @tparam T The type to check
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_generator_module : std::false_type {};
template <typename T>
struct is_generator_module<
T,
std::void_t<
typename std::decay_t<T>::subtoken_type,
typename std::decay_t<T>::core_type,
typename std::decay_t<T>::index_type,
typename std::decay_t<T>::decomposed_type,
typename std::decay_t<T>::enable_flag_type,
typename std::decay_t<T>::settings,
decltype(std::declval<T&>().decompose_subtoken(
std::declval<typename std::decay_t<T>::subtoken_type const&>(),
std::declval<typename std::decay_t<T>::core_type>(),
std::declval<typename std::decay_t<T>::index_type>())),
decltype(std::declval<T&>().validate_subtoken(
std::declval<typename std::decay_t<T>::subtoken_type const&>())),
decltype(std::declval<T&>().generate_load(
std::declval<typename std::decay_t<T>::decomposed_type const&>(),
std::declval<typename std::decay_t<T>::enable_flag_type const&>(),
std::declval<typename std::decay_t<T>::core_type>(),
std::declval<typename std::decay_t<T>::index_type>()))>>
: public std::true_type {};
/**
* @brief The generator base class.
* @note It is not at all necessary to derive from the generator_base
* class, it mostly serves as an example of a valid class with
* appropriate function signatures, and provides documentation.
*/
struct generator_base {
using subtoken_type = unsigned; //! REQUIRED, subtoken type
using decomposed_type = bool; //! REQUIRED, determines if active
using core_type = unsigned; //! REQUIRED, must be 'unsigned'
using index_type = std::size_t; //! REQUIRED, must be 'size_t'
using enable_flag_type = std::atomic_bool; //! REQUIRED, must be atomic_bool
/**
* @brief Generator settings
* @note By using the same configuration namespace as the
* generator_host, we can also access all of its values.
* Generators are allowed to hold their own configuration.
*/
struct settings : public exot::utilities::configurable<settings> {
const char* name() const { return "generator"; }
void configure() {}
};
/**
* @brief Generator constructor.
* @note Similarly to metering modules and components, the settings
* object is passed to the constructor in the generator_host,
* therefore a constructor with such a signature must be
* available.
*
* @param conf The conf
*/
explicit generator_base(settings& conf) {}
/**
* @brief Decomposes the subtoken and determines activation
*
* @param[in] subtoken The subtoken
* @param[in] core The CPU core
* @param[in] index The thread index
*
* @return The decomposed token
*/
inline decomposed_type decompose_subtoken(const subtoken_type& subtoken,
core_type core, index_type index);
/**
* @brief Validates the subtoken.
*
* @param[in] subtoken The subtoken
*
* @return True if valid, false otherwise.
*/
inline bool validate_subtoken(const subtoken_type& subtoken);
/**
* @brief Generates the medium-specific load.
*
* @param[in] decomposed_subtoken The decomposed subtoken
* @param[in] flag The activation atomic flag
* @param[in] core The CPU core
* @param[in] index The thread index
*/
inline void generate_load(const decomposed_type& decomposed_subtoken,
const enable_flag_type& flag, core_type core,
index_type index);
};
} // namespace exot::modules
<file_sep>/cmake/modules/colour_message.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file colour_message.cmake
# @author <NAME>
# @brief Function to print a coloured message to the console
#
string(ASCII 27 Escape)
set(Reset "${Escape}[m")
set(Bold "${Escape}[1m")
set(Red "${Escape}[31m")
set(Green "${Escape}[32m")
set(Yellow "${Escape}[33m")
set(Blue "${Escape}[34m")
set(Magenta "${Escape}[35m")
set(Cyan "${Escape}[36m")
set(White "${Escape}[37m")
function(colour_message)
list(GET ARGV 0 message_type)
list(GET ARGV 1 colour)
list(GET ARGV 2 bold)
if (${bold} STREQUAL BOLD)
set(use_bold ON)
list(REMOVE_AT ARGV 2)
endif ()
list(REMOVE_AT ARGV 1)
list(REMOVE_AT ARGV 0)
if (${colour} STREQUAL RED)
if (${use_bold})
set(modifier "${Bold}${Red}")
else ()
set(modifier "${Red}")
endif ()
elseif (${colour} STREQUAL GREEN)
if (${use_bold})
set(modifier "${Bold}${Green}")
else ()
set(modifier "${Green}")
endif ()
elseif (${colour} STREQUAL YELLOW)
if (${use_bold})
set(modifier "${Bold}${Yellow}")
else ()
set(modifier "${Yellow}")
endif ()
elseif (${colour} STREQUAL BLUE)
if (${use_bold})
set(modifier "${Bold}${Blue}")
else ()
set(modifier "${Blue}")
endif ()
elseif (${colour} STREQUAL MAGENTA)
if (${use_bold})
set(modifier "${Bold}${Magenta}")
else ()
set(modifier "${Magenta}")
endif ()
elseif (${colour} STREQUAL CYAN)
if (${use_bold})
set(modifier "${Bold}${Cyan}")
else ()
set(modifier "${Cyan}")
endif ()
elseif (${colour} STREQUAL WHITE)
if (${use_bold})
set(modifier "${Bold}${White}")
else ()
set(modifier "${White}")
endif ()
else (${colour})
if (${use_bold})
set(modifier "${Bold}")
else ()
set(modifier "")
endif ()
endif ()
message(${message_type} "${modifier}${ARGV}${Reset}")
endfunction()
<file_sep>/test/test_configuration.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
#include <doctest.h>
#include <exot/utilities/configuration.h>
#include <algorithm>
#include <numeric>
#include <random>
#include <thread>
#include <vector>
using namespace exot::utilities;
TEST_SUITE("Configuration") {
std::random_device rd;
std::mt19937 rdg(rd());
TEST_CASE("Bootstrapping CPU core vectors") {
using vector = std::vector<unsigned>;
static unsigned core_count = std::thread::hardware_concurrency();
REQUIRE(core_count >= 1);
vector def;
def.resize(core_count);
std::iota(def.begin(), def.end(), 0);
REQUIRE(def.size() == core_count);
SUBCASE("Bootstrapping given an empty vector") {
vector empty;
bootstrap_cores(empty);
CHECK(std::is_sorted(empty.begin(), empty.end()));
CHECK(empty == def);
}
SUBCASE("Bootstrapping given an unsorted vector") {
vector provided = def;
while (provided == def) {
std::shuffle(provided.begin(), provided.end(), rdg);
}
REQUIRE(provided != def);
bootstrap_cores(provided);
CHECK(std::is_sorted(provided.begin(), provided.end()));
CHECK(provided == def);
}
SUBCASE("Bootstrapping given a vector with duplicates") {
vector duplicated = {0, 0, 1, 1, 0, 0, 1, 1};
vector required = {0, 1};
bootstrap_cores(duplicated);
CHECK(std::is_sorted(duplicated.begin(), duplicated.end()));
CHECK(duplicated == required);
}
SUBCASE("Bootstrapping given values exceeding core count") {
vector exceeding{core_count + 1, core_count + 2};
CHECK_THROWS(bootstrap_cores(exceeding));
}
}
}
<file_sep>/include/exot/framework/executor.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/executor.h
* @author <NAME>
* @brief Executors for running process network nodes and arbitrary
* callable objects.
*/
#pragma once
#include <algorithm> // for remove_if
#include <functional> // for std::invoke
#include <mutex> // for mutexes
#include <stdexcept> // for throwing
#include <thread> // for threading
#include <type_traits> // for type traits
#include <vector> // for holding thread workers
#ifdef EXOT_USE_FIBERS
#include <boost/fiber/all.hpp>
#endif
#include <exot/framework/node.h> // for IProcess
#include <exot/utilities/thread.h> // for thread specialisation
#include <exot/utilities/types.h> // for type traits
#if defined(__GNUC__) && !defined(__clang__)
#include <features.h>
#if __GNUC_PREREQ(8, 0)
#define PROVIDE_VARIADIC_SPAWN
#endif
#endif
namespace exot::framework {
using exot::utilities::SchedulingPolicy;
using exot::utilities::ThreadTraits;
/**
* @brief Base class for executors
* @details The generic spawning interface cannot be included in the base
* class, since function templates cannot be virtual.
*/
class IExecutor {
public:
/**
* @brief Spawns a node that derives from the IProcess class
*
* @param node The process network node
*/
virtual void spawn(IProcess& node) = 0;
virtual ~IExecutor() = default;
};
/**
* @brief Executor that spawns each callable object in a new thread.
*/
class ThreadExecutor : public virtual IExecutor {
public:
ThreadExecutor() = default;
void spawn(IProcess& obj) override {
std::lock_guard<std::mutex> lg(threads_mutex_);
threads_.emplace_back([&]() { obj.process(); });
}
#if defined(__clang__) || defined(PROVIDE_VARIADIC_SPAWN)
/**
* @brief A template function for spawning multiple process network nodes
* @details The template will only be enabled for objects that have a
* void(void) process() function, and only if more than 1 argument
* is provided, so that in the default case the spawn function
* above is used.
*/
template <typename... T,
typename = std::enable_if_t<
(exot::utilities::has_process_function_v<T> && ...)>,
typename = std::enable_if_t<(sizeof...(T) > 1)>>
void spawn(T&... objs) {
std::lock_guard<std::mutex> lg(threads_mutex_);
(..., threads_.emplace_back([&]() { objs.process(); }));
}
#endif
/**
* @brief Spawns a callable object, providing it with its arguments.
*
* @param[in] callable A callable object (can be invoked with std::invoke).
* @param[in] args Arguments passed to the callable object.
*
* @tparam Callable A callable object type.
* @tparam Args Callable object's argument types.
*/
#if defined(__cpp_lib_is_invocable)
template <
typename Callable, typename... Args,
typename = std::enable_if_t<std::is_invocable<Callable, Args...>::value>>
#else
template <
typename Callable, typename... Args,
typename = std::enable_if_t<std::__invokable<Callable, Args...>::value>>
#endif
void spawn(Callable&& callable, Args&&... args) {
std::lock_guard<std::mutex> lg(threads_mutex_);
/// Emplacing allows constructing the object in place, therefore the thread
/// object does not need to be constructed manually.
threads_.emplace_back(std::forward<Callable>(callable), args...);
};
/**
* @brief Spawns a callable object and assigns thread properties.
*
* @param[in] cpu CPU to pin the spawned thread to.
* @param[in] policy Scheduling policy of the spawned thread.
* @param[in] priority Scheduling priority of the spawned thread.
* @param[in] callable A callable object (can be invoked with std::invoke).
* @param[in] args Arguments passed to the callable object.
*
* @tparam Callable A callable object type.
* @tparam Args Callable object's argument types.
*/
template <typename Callable, typename... Args>
void spawn_with_properties(unsigned int cpu, SchedulingPolicy policy,
unsigned int priority, Callable&& callable,
Args&&... args) {
/* At the moment thread traits only accept arguments passed as values, so
* the lambda capture required for callable and args... does not behave
* correctly for simple values. Since arguments are very simple and small
* types, it is usually not preferred to have them passed as references. */
/**
* Before the function 'callable' is invoked the thread properties are set.
*/
auto function = [&](unsigned int cpu_, SchedulingPolicy policy_,
unsigned int priority_) {
ThreadTraits::set_affinity(cpu_);
ThreadTraits::set_scheduling(policy_, priority_);
std::invoke(callable, args...);
};
/* A thread is added to the registry */
{
std::lock_guard<std::mutex> lg(threads_mutex_);
threads_.emplace_back(function, cpu, policy, priority);
}
};
/**
* @brief Join all threads that belong to the executor.
* @details While joining threads in the destructor works most of the
* time, in some cases, especially when the callable contains
* objects (esp. objects with mutexes) that might be destroyed
* during program termination while the spawned thread was
* asleep. For example, consider the code:
*
* @code{C++}
* //...
* ThreadExecutor exec;
* ObjectWithLocking obj;
* //...
* exec.spawn([&obj]{ std::this_thread::sleep_for(10s); obj.use(); });
* //...
* @endcode
*
* Local objects are destroyed in reverse order of construction.
* Therefore `obj`'s destructor will be called first, followed by
* the destructor of `ThreadExecutor`. If the destructor is
* called before the spawned thread wakes up, there is a chance
* that `obj` will no longer exist. To avoid that, it is safer to
* join the executor before exiting from the main routine.
*
* The routine also removes joined threads from the thread
* vector, such that the executor can be reused.
*/
void join() {
std::lock_guard<std::mutex> lg(threads_mutex_);
threads_.erase(std::remove_if(threads_.begin(), threads_.end(),
[](auto& thread) -> bool {
if (thread.joinable()) {
thread.join();
return true;
} else {
return false;
}
}),
threads_.end());
};
/**
* @brief Thread safe access to current thread count.
*
* @return Number of working threads.
*/
typename std::vector<std::thread>::size_type thread_count() {
std::lock_guard<std::mutex> lg(threads_mutex_);
return threads_.size();
};
/**
* @brief Destructor joins held thread if they were not joined manually.
* @details No need to acquire the mutex protecting the `threads_` vector,
* as destructors are not executed concurrently.
*/
~ThreadExecutor() {
for (auto&& thread : threads_) {
if (thread.joinable()) thread.join();
}
};
private:
std::mutex threads_mutex_; //! Protects the vector of threads.
std::vector<std::thread> threads_;
}; // namespace exot::framework
#ifdef EXOT_USE_FIBERS
inline namespace fibers {
/**
* @brief Executor that spawns each callable object in a new fiber
* (userspace thread).
* @details The userland threads need to be provided at least one worker to
* allow execution.
*
* @tparam WorkAlgorithm Work algorithm used by the fiber scheduler, e.g.
* work sharing, or round robin.
*/
template <typename WorkAlgorithm = boost::fibers::algo::round_robin>
class FiberExecutor : public virtual IExecutor {
public:
using work_algorithm = WorkAlgorithm;
FiberExecutor() = default;
void spawn(IProcess& obj) override {
if (thread_count() == 0)
throw std::logic_error(
"no worker threads were present when a fiber was spawned");
std::lock_guard<std::mutex> lg(worker_fibers_mutex_);
worker_fibers_.emplace_back([&]() { obj.process(); });
}
#if defined(__clang__) || defined(PROVIDE_VARIADIC_SPAWN)
template <typename... T,
typename = std::enable_if_t<
(exot::utilities::has_process_function_v<T> && ...)>,
typename = std::enable_if_t<(sizeof...(T) > 1)>>
void spawn(T&... processes) {
if (thread_count() == 0)
throw std::logic_error(
"no worker threads were present when a fiber was spawned");
std::lock_guard<std::mutex> lg(worker_fibers_mutex_);
(..., worker_fibers_.emplace_back([&]() { objs.process(); }));
}
#endif
#if defined(__cpp_lib_is_invocable)
template <
typename Callable, typename... Args,
typename = std::enable_if_t<std::is_invocable<Callable, Args...>::value>>
#else
template <
typename Callable, typename... Args,
typename = std::enable_if_t<std::__invokable<Callable, Args...>::value>>
#endif
void spawn(Callable&& callable, Args&&... args) {
if (thread_count() == 0)
throw std::logic_error(
"no worker threads were present when a fiber was spawned");
std::lock_guard<std::mutex> lg(worker_fibers_mutex_);
worker_fibers_.emplace_back(callable, args...);
};
/**
* @brief Adds a worker thread for the fibers 'pool'. */
void add_worker_thread() {
std::lock_guard<std::mutex> lg(worker_threads_mutex_);
worker_threads_.emplace_back(
[] { boost::fibers::use_scheduling_algorithm<work_algorithm>(); });
};
/**
* @brief Registers calling thread as a fiber pool worker. */
inline void register_as_worker() {
boost::fibers::use_scheduling_algorithm<work_algorithm>();
};
/**
* @brief Joins all userland threads belonging to this executor
*/
void join_fibers() {
std::lock_guard<std::mutex> lg(worker_fibers_mutex_);
worker_fibers_.erase(
std::remove_if(worker_fibers_.begin(), worker_fibers_.end(),
[](auto& fiber) -> bool {
if (fiber.joinable()) {
fiber.join();
return true;
} else {
return false;
}
}),
worker_fibers_.end());
}
/**
* @brief Joins all worker threads belonging to this executor
*/
void join_workers() {
std::lock_guard<std::mutex> lg(worker_threads_mutex_);
worker_threads_.erase(
std::remove_if(worker_threads_.begin(), worker_threads_.end(),
[](auto& thread) -> bool {
if (thread.joinable()) {
thread.join();
return true;
} else {
return false;
}
}),
worker_threads_.end());
}
/**
* @brief Thread safe access to current thread count.
*
* @return Number of working worker threads.
*/
typename std::vector<std::thread>::size_type thread_count() {
std::lock_guard<std::mutex> lg(worker_threads_mutex_);
return worker_threads_.size();
};
/**
* @brief Thread safe access to current fiber count.
*
* @return Number of working fiber threads.
*/
typename std::vector<std::thread>::size_type fiber_count() {
std::lock_guard<std::mutex> lg(worker_fibers_mutex_);
return worker_fibers_.size();
};
~FiberExecutor() {
for (auto&& fiber : worker_fibers_) {
if (fiber.joinable()) fiber.join();
}
for (auto&& thread : worker_threads_) {
if (thread.joinable()) thread.join();
}
};
private:
std::mutex worker_threads_mutex_; //! Protects the vector of worker threads.
std::vector<std::thread> worker_threads_;
std::mutex worker_fibers_mutex_; //! Protects the vector of spawned fibers.
std::vector<boost::fibers::fiber> worker_fibers_;
};
} // namespace fibers
#endif
} // namespace exot::framework
<file_sep>/src/meters/process_android.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/process_android.cpp
* @author <NAME>
* @brief Implementation of the android foreground process metering module.
*/
#if defined(__linux__) && defined(__ANDROID__) && !defined(__x86_64__)
#include "../../include/exot/meters/process_android.h"
#include <exot/meters/process_android.h>
#include <jni.h>
namespace exot::modules {
process_android::process_android(settings& conf)
: conf_{validate_settings(conf)} {
}
process_android::~process_android() {
debug_log_->info("Detaching process measurement thread.");
}
typename process_android::return_type process_android::measure() {
JavaVM* jvm = reinterpret_cast<JavaVM*>(conf_.jvm);
// int getEnvStat = conf_.jvm->GetEnv((void**) &jenv_, conf_.jniversion);
int getEnvStat =
jvm->GetEnv((void**)&jenv_, static_cast<jint>(conf_.jniversion));
if (getEnvStat == JNI_EDETACHED) {
// debug_log_->info( "GetEnv: not attached");
// if (conf_.jvm->AttachCurrentThread(&jenv_, NULL) != 0) {
if (jvm->AttachCurrentThread(&jenv_, NULL) != 0) {
debug_log_->info("Failed to attach");
}
} else if (getEnvStat == JNI_OK) {
//
} else if (getEnvStat == JNI_EVERSION) {
debug_log_->info("GetEnv: version not supported");
}
// jstring processname = (jstring) (jenv_->CallObjectMethod(*conf_.jinstance,
// *conf_.jmid));
jstring processname = (jstring)(
jenv_->CallObjectMethod(reinterpret_cast<jobject>(conf_.jinstance),
reinterpret_cast<jmethodID>(conf_.jmid)));
std::string procname(jenv_->GetStringUTFChars(processname, 0));
if (jenv_->ExceptionCheck()) { jenv_->ExceptionDescribe(); }
// conf_.jvm->DetachCurrentThread();
jvm->DetachCurrentThread();
return procname;
}
std::vector<std::string> process_android::header() {
std::vector<std::string> description;
description.push_back(exot::utilities::generate_header(
conf_.name(), "ForegroundActivity", 0, DefaultUnits::process));
return description;
}
process_android::settings process_android::validate_settings(settings& conf) {
/* TODO If no JNE pointer is provided, die gracefully... */
return conf;
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/framework/node.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/node.h
* @author <NAME>
* @brief Definitions of the core process network node: processes,
* producers, consumers, and processors.
*/
#pragma once
#include <memory> // for shared_ptr
#include <exot/framework/interface.h> // for in/out interfaces
#include <exot/framework/state.h> // for State and GLOBAL_STATE
/**
* Declare GLOBAL_STATE as extern for linking.
*/
extern std::shared_ptr<exot::framework::State> exot::framework::GLOBAL_STATE;
namespace exot::framework {
/**
* @brief Separate process() and task() interfaces such that a node can
* implement either or both ivocation styles (loop and/or single
* task) */
/**
* @brief Class for executable nodes using the continuous process model,
* which run until a termination condition is set in the local or
* global state.
*/
class IProcess {
public:
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
/**
* @brief Constructs the object.
*
* @param[in] global_state The pointer to a state object
*/
explicit IProcess(state_pointer global_state)
: global_state_{global_state} {};
/**
* @brief Constructs the default object.
* @details The delegated constructor sets the state pointer to the global
* state object's shared pointer
*/
IProcess() : IProcess(GLOBAL_STATE->get()){};
/**
* @brief Destroys the object.
* @details Virtual constructors are necessary for base classes.
*/
virtual ~IProcess() = default;
/**
* @brief The main activity of the process, has to be implemented in
* deriving classes.
*/
virtual void process() = 0;
protected:
state_pointer
global_state_; //! A shared pointer to the (most likely) global state
};
/**
* @todo Currently there is no support for task-based nodes.
* @brief Enum class for the return type of a task.
*/
enum class TaskStatus;
/**
* @todo Currently there is no support for task-based nodes.
* @brief Class for executable nodes using the task model, which execute a
* single block of code and return, i.e. do not have an internal
* processing loop.
*
* @tparam Args Argument types used for task arguments.
*/
template <typename... Args>
class ITask {
public:
virtual ~ITask() = default;
virtual TaskStatus task(Args... args) = 0;
};
/**
* @brief Base class for node classes, used possibly for polymorphic
* access/storage, or type traits.
*/
struct Node {
virtual ~Node() = default;
};
/**
* @brief Helper base class for determining if node is a consumer in
* templates.
*/
struct TConsumer {
virtual ~TConsumer() = default;
};
/**
* @brief Helper base class for determining if node is a producer in
* templates.
*/
struct TProducer {
virtual ~TProducer() = default;
};
/**
* @brief Helper base class for determining if node is a processor in
* templates.
*/
struct TProcessor {
virtual ~TProcessor() = default;
};
/**
* @details The subsequent classes use template template parameters, which
* work as follows: the first template argument is passed to the
* second, then second is passed to the third. Thanks to that there
* is no need to write e.g. `Consumer<T, Container<T>, Reader<T,
* Container<T>>`, instead it is sufficient to write `Consumer<T,
* Container, Reader>`. This approach is used in many STL classes.
*
* Virtual inheritance of the base class prevents multiple base
* objects being present in classes which derive from both Consumer
* and Producer classes.
*/
/**
* @brief The consumer node class, which defines an input interface for
* specific token type, with a specific communication channel.
*
* @tparam Token The data type carried via the channel/container
* @tparam Container The type of the communication channel/container
* @tparam Reader The interface type used to access the communication
* channel/container.
*/
template <typename Token, template <typename...> typename Container,
template <typename, template <typename...> typename> typename Reader>
class IConsumer : public virtual Node, public virtual TConsumer {
public:
using consumer_type = IConsumer<Token, Container, Reader>;
using interface_type = Reader<Token, Container>;
IConsumer() = default;
explicit IConsumer(typename interface_type::container_pointer input_queue)
: in_(input_queue){};
virtual ~IConsumer() = default;
void set_input(typename interface_type::container_pointer input) {
in_.set_read_container(input);
}
typename interface_type::container_pointer get_input() const {
return in_.get_read_container();
}
protected:
interface_type in_; //! Input interface, accessible by derived classes.
};
/**
* @brief The producer node class, which defines an output interface for
* specific token type, with a specific communication channel.
*
* @tparam Token The data type carried via the channel/container
* @tparam Container The type of the communication channel/container
* @tparam Writer The interface type used to access the communication
* channel/container.
*/
template <typename Token, template <typename...> typename Container,
template <typename, template <typename...> typename> typename Writer>
class IProducer : public virtual Node, public virtual TProducer {
public:
using producer_type = IProducer<Token, Container, Writer>;
using interface_type = Writer<Token, Container>;
IProducer() = default;
explicit IProducer(typename interface_type::container_pointer output_queue)
: out_(output_queue){};
virtual ~IProducer() = default;
void set_output(typename interface_type::container_pointer output) {
out_.set_write_container(output);
}
typename interface_type::container_pointer get_output() const {
return out_.get_write_container();
}
protected:
interface_type out_; //! Output interface, accessible by derived classes.
};
/**
* @brief The processor node class, which combines the functionality of a
* producer and a consumer, with both input and output interfaces
* and distinct token types.
*
* @tparam InputToken The input data type carried via the input
* channel/container
* @tparam InputContainer The type of the input communication
* channel/container
* @tparam Reader The interface type used to access the input
* communication channel/container.
* @tparam OutputToken The output data type carried via the output
* channel/container
* @tparam OutputContainer The type of the output communication
* channel/container
* @tparam Writer The interface type used to access the
* communication channel/container.
*/
template <typename InputToken, template <typename...> typename InputContainer,
template <typename, template <typename...> typename> typename Reader,
typename OutputToken, template <typename...> typename OutputContainer,
template <typename, template <typename...> typename> typename Writer>
class IProcessor : public IConsumer<InputToken, InputContainer, Reader>,
public IProducer<OutputToken, OutputContainer, Writer>,
public virtual TProcessor {
public:
/**
* These types are used both internally and externally.
*/
using consumer_type =
typename IConsumer<InputToken, InputContainer, Reader>::consumer_type;
using producer_type =
typename IProducer<OutputToken, OutputContainer, Writer>::producer_type;
/* Since the base classes are template classes, this declaration is
* necessary for easy access to the interface, without the need of stating
* thebase class every time.*/
using consumer_type::in_;
using producer_type::out_;
IProcessor() = default;
explicit IProcessor(
typename consumer_type::interface_type::container_pointer input_queue,
typename producer_type::interface_type::container_pointer output_queue)
: consumer_type(input_queue), producer_type(output_queue){};
virtual ~IProcessor() = default;
};
}; // namespace exot::framework
<file_sep>/include/exot/components/meter_host_logger.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/meter_host_logger.h
* @author <NAME>
* @brief Meter hosting node immediately logging measurements.
*/
#pragma once
#include <chrono>
#include <ctime>
#include <string>
#include <thread>
#include <type_traits>
#include <fmt/format.h> // for string formatting
#include <fmt/ostream.h> // for ostream support
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/framework/all.h> // for framework support
#include <exot/meters/base.h> // for meter type trait
#include <exot/utilities/configuration.h> // for configurable
#include <exot/utilities/formatting.h> // for duration_{unit, to_string}
#include <exot/utilities/ostream.h> // for ostream support
#include <exot/utilities/thread.h> // for thread specialisation
#include <exot/utilities/timing.h> // for TimeKeeper
#if !defined(__x86_64__)
#include <exot/utilities/timing_source.h>
#endif
#ifndef METER_SET_AFFINITY
#define METER_SET_AFFINITY true
#endif
#ifndef METER_USE_STATISTICS
#define METER_USE_STATISTICS false
#endif
#ifndef METER_LOG_SYSTEM_TIME
#define METER_LOG_SYSTEM_TIME false
#endif
#ifndef METER_NOW_FROM_TIMER
#define METER_NOW_FROM_TIMER true
#endif
namespace exot::components {
namespace details {
template <typename Duration, typename... Meters>
using meter_token_type = std::tuple<Duration, typename Meters::return_type...>;
struct MeterOptions {
static constexpr bool use_statistics =
static_cast<bool>(METER_USE_STATISTICS);
static constexpr bool set_affinity = //
static_cast<bool>(METER_SET_AFFINITY);
static constexpr bool log_system_time =
static_cast<bool>(METER_LOG_SYSTEM_TIME);
static constexpr bool now_from_timer =
static_cast<bool>(METER_NOW_FROM_TIMER);
};
inline constexpr MeterOptions meter_options;
template <typename Lhs, typename Rhs>
inline constexpr bool is_same_vd =
std::is_same_v<std::decay_t<Lhs>, std::decay_t<Rhs>>;
} // namespace details
/**
* @brief Class for a meter host with integrated logging
*
* @tparam Duration The duration type used by the logger
* @tparam Meters The meter modules
*/
template <typename Duration, typename... Meters>
class meter_host_logger : public Meters...,
public exot::framework::IProcess,
public exot::framework::Producer<
details::meter_token_type<Duration, Meters...>> {
public:
using node_type =
exot::framework::Producer<details::meter_token_type<Duration, Meters...>>;
using token_type = typename node_type::interface_type::value_type;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using clock_type = std::chrono::steady_clock;
using policy_type = exot::utilities::SchedulingPolicy;
using timer_type =
exot::utilities::TimeKeeper<clock_type,
details::meter_options.use_statistics,
std::chrono::nanoseconds>;
using timer_duration = typename timer_type::chrono_granularity;
using node_type::out_;
using configurable_type =
exot::utilities::configurable<meter_host_logger<Duration, Meters...>>;
/**
* @brief The settings structure, inherits from all module settings
*/
struct settings : public exot::utilities::configurable<settings>,
Meters::settings... {
Duration period{std::chrono::milliseconds{10}}; //! sampling period
/// @defgroup meter_host_l_settings Meter host's master thread settings
/// @{
unsigned host_pinning{0}; //! core to pin host to
bool should_pin_host{false}; //! should pin host?
unsigned host_priority{90}; //! host's priority
policy_type host_policy{policy_type::Other}; //! host's sched. policy
/// @}
bool log_header{true}; //! should log header?
bool start_immediately{false}; //! should start immediately?
bool use_busy_sleep{false}; //! should use busy sleep?
bool busy_sleep_yield{false}; //! should yield in busy sleep?
unsigned start_check_period{1}; //! how often to check if started in µs
using base_t = exot::utilities::configurable<settings>;
static_assert(
(exot::utilities::is_configurable_v<typename Meters::settings> && ...),
"Meters must satisfy is_configurable to be used with JSON "
"configuration.");
/* @brief The configurable's component identifier */
const char* name() const { return "meter"; }
/* @brief The combining settings structure needs to overload this to allow
* initialising JSON configs in inherited classes. */
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
/* Fold expression over all meter module configure functions. */
(..., Meters::settings::set_json(root));
}
std::string describe() {
auto description = base_t::describe();
(..., description.append(Meters::settings::describe()));
return description;
}
/* @brief The JSON configuration function */
void configure() {
base_t::bind_and_describe_data("period", period,
"sampling period |s|, e.g. 1.0e-3");
base_t::bind_and_describe_data("host_pinning", host_pinning,
"host's core pinning |uint|, e.g. 1");
base_t::bind_and_describe_data(
"should_pin_host", should_pin_host,
"should pin the host? |bool|, default 'true'");
base_t::bind_and_describe_data(
"host_priority", host_priority,
"host's scheduling priority |uint|, in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"host_policy", host_policy,
"hosts's scheduling policy |str, policy_type|, e.g. \"round_robin\"");
base_t::bind_and_describe_data("log_header", log_header,
"should log header? |bool|");
base_t::bind_and_describe_data("start_immediately", start_immediately,
"should start immediately? |bool|");
base_t::bind_and_describe_data("use_busy_sleep", use_busy_sleep,
"should use busy sleep loop? |bool|");
base_t::bind_and_describe_data(
"busy_sleep_yield", busy_sleep_yield,
"should yield thread in busy sleep loop? |bool|");
base_t::bind_and_describe_data(
"start_check_period", start_check_period,
"state change detection update period |µs|, e.g. 100");
/* Fold expression over all meter module configure functions. */
(..., Meters::settings::configure());
}
};
static_assert((exot::modules::has_meter_function<Meters>::value && ...),
"Mixins need to provide a measure() function.");
meter_host_logger(settings& conf) : Meters(conf)..., conf_{conf} {
debug_log_->info("[meter] using period: {}",
exot::utilities::duration_to_string(conf_.period));
if (conf_.use_busy_sleep && !conf_.busy_sleep_yield) {
debug_log_->info("[meter] using busy sleep without thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, false>);
} else if (conf_.use_busy_sleep && conf_.busy_sleep_yield) {
debug_log_->info("[meter] using busy sleep with thread yield");
timer_ = timer_type(
debug_log_,
&exot::utilities::busysleep<typename timer_duration::rep,
typename timer_duration::period, true>);
} else {
debug_log_->info("[meter] using regular sleep function");
timer_ = timer_type(debug_log_);
}
if constexpr (details::meter_options.set_affinity) {
debug_log_->info("[meter] will run pinned to {}", conf_.host_pinning);
}
logging_header_ = fmt::format("{}", header());
}
void process() override {
auto until = [this]() { return !global_state_->is_stopped(); };
auto action = [this]() {
if constexpr (details::meter_options.log_system_time) {
application_log_->info("{},{:%FT%T}", measure(),
exot::utilities::get_utc_time());
} else {
application_log_->info("{}", measure());
}
};
if constexpr (details::meter_options.set_affinity) {
if (conf_.should_pin_host)
exot::utilities::ThreadTraits::set_affinity(conf_.host_pinning);
}
exot::utilities::ThreadTraits::set_scheduling(conf_.host_policy,
conf_.host_priority);
if (!logging_header_.empty() && conf_.log_header) {
application_log_->info("{}", logging_header_);
debug_log_->info("[meter] logging header: {}", logging_header_);
}
debug_log_->info("[meter] running on {}", exot::utilities::thread_info());
#if !defined(__x86_64__)
/* Call the timing facility for 1-time initialisation, if needed. */
volatile auto _no_discard = exot::utilities::default_timing_facility([] {
volatile auto _ = 0ull;
_;
});
#endif
const auto check_p = std::chrono::microseconds{conf_.start_check_period};
while (!global_state_->is_started() && !conf_.start_immediately) {
std::this_thread::sleep_for(check_p);
}
debug_log_->info("[meter] started logging");
/* Run `action` till `until` returns false. */
timer_.run_every(conf_.period, until, action);
}
/**
* @brief Perform measurement
*
* @return Timestamped results of all individual meters
*/
inline token_type measure() {
if constexpr (details::meter_options.now_from_timer) {
if constexpr (details::is_same_vd<
Duration, decltype(timer_.now().time_since_epoch())>) {
auto timestamp = timer_.now().time_since_epoch();
return std::make_tuple(std::move(timestamp),
std::move(Meters::measure())...);
} else {
auto timestamp = std::chrono::duration_cast<Duration>(
timer_.now().time_since_epoch());
return std::make_tuple(std::move(timestamp),
std::move(Meters::measure())...);
}
} else {
if constexpr (details::is_same_vd<
Duration, decltype(std::chrono::steady_clock::now()
.time_since_epoch())>) {
auto timestamp = std::chrono::steady_clock::now().time_since_epoch();
return std::make_tuple(std::move(timestamp),
std::move(Meters::measure())...);
} else {
auto timestamp = std::chrono::duration_cast<Duration>(
std::chrono::steady_clock::now().time_since_epoch());
return std::make_tuple(std::move(timestamp),
std::move(Meters::measure())...);
}
}
}
auto header() {
if constexpr (details::meter_options.log_system_time) {
return std::make_tuple(timestamp_header(), Meters::header()...,
datetime_header());
} else {
return std::make_tuple(timestamp_header(), Meters::header()...);
}
}
~meter_host_logger() {
debug_log_->info("[meter] finished logging on {:%c %Z}",
exot::utilities::get_utc_time());
if constexpr (details::meter_options.use_statistics) {
debug_log_->info("[meter] timing offset statistics: {}",
timer_.offset_statistics());
debug_log_->info("[meter] timing interval statistics: {}",
timer_.interval_statistics());
}
debug_log_->flush();
}
private:
state_pointer global_state_{exot::framework::GLOBAL_STATE->get()};
logger_pointer application_log_ =
spdlog::get("app") ? spdlog::get("app") : spdlog::stdout_color_mt("app");
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
timer_type timer_;
std::string logging_header_;
settings conf_;
std::string timestamp_header() {
return exot::utilities::generate_header(
conf_.name(), "timestamp", "",
exot::utilities::duration_unit(conf_.period));
}
std::string datetime_header() {
return exot::utilities::generate_header(conf_.name(), "datetime", "",
"iso8601");
}
};
} // namespace exot::components
<file_sep>/src/meters/utilisation_procfs.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/utilisation_procfs.cpp
* @author <NAME>
* @brief Implementation of the /proc/stat utilisation metering module.
*/
#include <exot/meters/utilisation.h>
using namespace exot::modules;
utilisation_procfs::utilisation_procfs(settings& conf) : conf_{conf} {
exot::utilities::bootstrap_cores(conf_.cores);
debug_log_->info("[utilisation_procfs] using cores: {}", conf_.cores);
if (conf_.raw) {
debug_log_->info("[utilisation_procfs] reading raw /proc/stat values");
}
if (conf_.states.empty()) {
conf_.states = {utilisation_procfs::cpu_state::user,
utilisation_procfs::cpu_state::idle};
}
/**
* @brief Lambda to check if a state is contained in the
* `conf_.states` vector.
* @details The function will also log the state, if found.
*
* @param[in] state The state
*
* @return True if contained, false otherwise.
*/
auto contains = [this](utilisation_procfs::cpu_state state) -> bool {
auto state_to_string =
[](utilisation_procfs::cpu_state state) -> std::string {
if (state == utilisation_procfs::cpu_state::user)
return "user";
else if (state == utilisation_procfs::cpu_state::nice)
return "nice";
else if (state == utilisation_procfs::cpu_state::system)
return "system";
else
return "idle";
};
if (std::find(conf_.states.begin(), conf_.states.end(), state) !=
conf_.states.end()) {
debug_log_->debug("[utilisation_procfs] reading state: {}",
state_to_string(state));
return true;
} else {
return false;
}
};
/* Set enable_flags_ to determine which state is to be accessed. */
enable_flags_[0] = contains(utilisation_procfs::cpu_state::user);
enable_flags_[1] = contains(utilisation_procfs::cpu_state::nice);
enable_flags_[2] = contains(utilisation_procfs::cpu_state::system);
enable_flags_[3] = contains(utilisation_procfs::cpu_state::idle);
auto state_count = conf_.states.size();
auto core_count = conf_.cores.size();
auto readings_size = core_count * state_count;
debug_log_->debug(
"[utilisation_procfs] reading {} states from {} cores, {} readings in "
"total",
state_count, core_count, readings_size);
previous_readings_.resize(readings_size);
current_readings_.resize(readings_size);
output_.resize(readings_size);
if (std::ifstream ifs{filepath_}; !ifs.is_open()) {
throw std::logic_error("/proc/stat is not readable");
}
/* The _SC_CLK_TCK sysconf value contains the number of ticks per second used
* in utilisation reporting. */
ticks_per_second_ = ::sysconf(_SC_CLK_TCK);
debug_log_->trace("[utilisation_procfs] ticks per second: {}",
ticks_per_second_);
/* First reading. */
previous_time_ = std::chrono::steady_clock::now();
once(previous_readings_);
std::this_thread::sleep_for(std::chrono::milliseconds{100});
}
typename utilisation_procfs::return_type utilisation_procfs::measure() {
auto current_time = std::chrono::steady_clock::now();
once(current_readings_);
/* If using the *processed* setting, take the current and previous readings
* and elapsed time to obtain a relative utilisation reading, usually in the
* range [0, 1]. Otherwise simply log the raw readings from procfs access. */
if (!conf_.raw) {
using float_second = std::chrono::duration<double, std::ratio<1>>;
auto delta_time =
std::chrono::duration_cast<float_second>(current_time - previous_time_);
previous_time_ = current_time;
std::transform(current_readings_.begin(), current_readings_.end(),
previous_readings_.begin(), output_.begin(),
[&](auto current, auto previous) {
return ((static_cast<double>(current - previous) /
static_cast<double>(ticks_per_second_)) /
delta_time.count());
});
previous_readings_ = current_readings_;
} else {
for (size_t idx{0}; idx < output_.size(); ++idx) {
output_.at(idx) = static_cast<double>(current_readings_.at(idx));
}
}
return output_;
}
void utilisation_procfs::once(
typename utilisation_procfs::reading_type& readings) {
static std::string regex_string{
"cpu(\\d+)\\s+(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\d+)"};
static std::regex regex(regex_string, std::regex_constants::ECMAScript);
std::smatch regex_matches;
std::ifstream file{filepath_};
std::string string_buffer{std::istreambuf_iterator<char>(file), {}};
auto add_readings = [&](unsigned core, size_t& idx) {
if (core == std::stoi(regex_matches[1].str())) {
if (enable_flags_[0]) { readings[idx++] = stoi(regex_matches[2].str()); }
if (enable_flags_[1]) { readings[idx++] = stoi(regex_matches[3].str()); }
if (enable_flags_[2]) { readings[idx++] = stoi(regex_matches[4].str()); }
if (enable_flags_[3]) { readings[idx++] = stoi(regex_matches[5].str()); }
}
};
size_t idx{0};
while (std::regex_search(string_buffer, regex_matches, regex)) {
SPDLOG_LOGGER_TRACE(debug_log_, "[utilisation_procfs] line: {}",
regex_matches[0].str());
SPDLOG_LOGGER_TRACE(debug_log_, "[utilisation_procfs] core: {}",
regex_matches[1].str());
SPDLOG_LOGGER_TRACE(debug_log_,
"[utilisation_procfs] total matches: {}, values: {}",
regex_matches.size(), regex_matches.size() - 2);
for (auto core : conf_.cores) { add_readings(core, idx); }
string_buffer = regex_matches.suffix();
}
}
std::vector<std::string> utilisation_procfs::header() {
std::vector<std::string> description;
for (auto core : conf_.cores) {
if (enable_flags_[0])
description.push_back(
exot::utilities::generate_header(conf_.name(), "user", core, ""));
if (enable_flags_[1])
description.push_back(
exot::utilities::generate_header(conf_.name(), "nice", core, ""));
if (enable_flags_[2])
description.push_back(
exot::utilities::generate_header(conf_.name(), "system", core, ""));
if (enable_flags_[3])
description.push_back(
exot::utilities::generate_header(conf_.name(), "idle", core, ""));
}
return description;
}
<file_sep>/include/exot/components/meter_host.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file components/meter_host.h
* @author <NAME>
* @brief Node combining multiple metering modules together into a single
* process network node.
* @warning Current development is only done on the 'meter_host_logger'
* component, therefore the following code might not be the most
* recent or have equal level of support.
*/
#pragma once
#include <chrono>
#include <string>
#include <thread>
#include <fmt/format.h> // for string formatting
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/framework/all.h> // for framework support
#include <exot/meters/base.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/formatting.h>
#include <exot/utilities/thread.h>
#include <exot/utilities/timing.h>
#include <exot/utilities/ostream.h>
#include <fmt/ostream.h>
namespace exot::components {
namespace details {
template <typename Duration, typename... Meters>
using meter_token_type = std::tuple<Duration, typename Meters::return_type...>;
}
/**
* @brief The process network component hosting meter modules
*
* @tparam Duration The duration type
* @tparam Meters The meter modules
*/
template <typename Duration, typename... Meters>
class meter_host : public Meters...,
public exot::framework::IProcess,
public exot::framework::Producer<
details::meter_token_type<Duration, Meters...>> {
public:
using node_type =
exot::framework::Producer<details::meter_token_type<Duration, Meters...>>;
using token_type = typename node_type::interface_type::value_type;
using state_type = exot::framework::State;
using state_pointer = std::shared_ptr<state_type>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using clock_type = std::chrono::steady_clock;
using policy_type = exot::utilities::SchedulingPolicy;
using node_type::out_;
/**
* Flag set at compile time for logging times and providing timing statistics.
*/
static constexpr bool use_statistics = false;
/**
* @brief The settings structure, inherits from individual modules
* settings.
*/
struct settings : public exot::utilities::configurable<settings>,
Meters::settings... {
Duration period{std::chrono::milliseconds{10}};
/// @defgroup meter_host_settings Meter host's master thread settings
/// @{
unsigned host_pinning{0}; //! core to pin host to
bool should_pin_host{false}; //! should pin host?
unsigned host_priority{90}; //! host's priority
policy_type host_policy{policy_type::Other}; //! host's sched. policy
/// @}
using base_t = exot::utilities::configurable<settings>;
const char* name() const { return "meter"; }
/* @brief The combining settings structure needs to overload this to allow
* initialising JSON configs in inherited classes. */
void set_json(const nlohmann::json& root) {
json_config_ = base_t::set_json(root);
/* Fold expression over all meter module configure functions. */
(..., Meters::settings::set_json(root));
}
std::string describe() {
auto description = base_t::describe();
(..., description.append(Meters::settings::describe()));
return description;
}
/* @brief The JSON configuration function */
void configure() {
base_t::bind_and_describe_data("period", period,
"sampling period |s|, e.g. 1.0e-3");
base_t::bind_and_describe_data(
"host_priority", host_priority,
"host's scheduling priority |uint|, in range [0, 99], e.g. 99");
base_t::bind_and_describe_data(
"host_policy", host_policy,
"host's scheduling policy |str, policy_type|, e.g. \"round_robin\"");
static_assert(
(exot::utilities::is_configurable_v<Meters::settings> && ...),
"Meters must satisfy is_configurable to be used with JSON "
"configuration.");
/* Fold expression over all meter module configure functions. */
(..., Meters::settings::configure());
}
};
static_assert((exot::modules::has_meter_function<Meters>::value && ...),
"Mixins need to provide a measure() function.");
/**
* @brief Constructs the meter host
*
* @param conf The settings object
*/
meter_host(settings& conf) : Meters(conf)..., conf_{conf} {
debug_log_->info("[meter] using period: {}",
exot::utilities::duration_to_string(conf_.period));
if (conf_.should_pin_host) {
debug_log_->info("[meter] will run pinned to {}", conf_.host_pinning);
} else {
debug_log_->info("[meter] will run not pinned");
}
}
/**
* @brief The main process
*/
void process() override {
auto until = [this]() { return !global_state_->is_stopped(); };
auto action = [this]() { out_.write(measure()); };
if (conf_.should_pin_host)
exot::utilities::ThreadTraits::set_affinity(conf_.host_pinning);
exot::utilities::ThreadTraits::set_scheduling(conf_.host_policy,
conf_.host_priority);
debug_log_->info("[meter] running on {}", exot::utilities::thread_info());
while (!global_state_->is_started()) {
std::this_thread::sleep_for(std::chrono::milliseconds{100});
}
/* Run `action` till `until` returns false. */
timer_.run_every(conf_.period, until, action);
}
/**
* @brief Perform measurement
*
* @return Timestamped results of all individual meters
*/
inline token_type measure() {
return std::make_tuple(
std::chrono::duration_cast<Duration>(
std::chrono::steady_clock::now().time_since_epoch()),
std::move(Meters::measure())...);
}
auto variable_names() {
return std::make_tuple(timestamp_name(), Meters::variable_names()...);
}
auto variable_units() {
return std::make_tuple(timestamp_unit(), Meters::variable_units()...);
}
auto header() {
return std::make_tuple(timestamp_name_and_unit(), Meters::header()...);
}
~meter_host() {
if constexpr (use_statistics) {
debug_log_->info("[meter] timing offset statistics: {}",
timer_.offset_statistics());
debug_log_->info("[meter] timing interval statistics: {}",
timer_.interval_statistics());
}
}
private:
state_pointer global_state_{exot::framework::GLOBAL_STATE->get()};
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
exot::utilities::TimeKeeper<clock_type, use_statistics,
std::chrono::microseconds>
timer_;
settings conf_;
std::string timestamp_name() { return "timestamp"; }
std::string timestamp_unit() {
return exot::utilities::duration_unit(conf_.period);
}
std::string timestamp_name_and_unit() {
return fmt::format("{}_[{}]", timestamp_name(), timestamp_unit());
}
};
//
} // namespace exot::components
<file_sep>/examples/meter.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file examples/meter.cpp
* @author <NAME>
* @brief An example meter application, combining all available modules.
*/
/* Step 1: Include necessary headers: */
#define METER_LOG_SYSTEM_TIME false
#include <exot/components/meter_host_logger.h> // Meter host
#include <exot/framework/all.h> // Connector, executor, etc.
#include <exot/meters/frequency.h> // Frequency modules
#include <exot/meters/power.h> // Power modules
#include <exot/meters/thermal.h> // Thermal modules
#include <exot/meters/utilisation.h> // Utilisation modules
#include <exot/utilities/cli.h> // Command-line parsing
#include <exot/utilities/configuration.h> // Configuration/JSON
#include <exot/utilities/logging.h> // Logging facilities
/* Other available meter modules. */
// #include <exot/meters/cache.h> // Cache modules
// #include <exot/meters/rdseed.h> // RDSEED modules
using namespace exot;
int main(int argc, char** argv) {
/* Step 2: Declare aliases for convienience. */
using Meter = components::meter_host_logger<std::chrono::microseconds, //
modules::utilisation_procfs, //
modules::frequency_sysfs, //
modules::frequency_rel, //
modules::thermal_sysfs, //
modules::thermal_msr, //
modules::power_msr>;
using utilities::Logging;
/* Step 3: Create objects for command-line parsing and JSON configuration. */
utilities::CLI cli;
utilities::JsonConfig jc;
/* Step 4: Create settings objects for used components. */
Meter::settings meter_settings;
Logging::settings logging_settings;
/* Step 5: Add components or JSON cli-configuration to the CLI parser. */
cli.add_configurations(jc.get_cli_configuration());
/* Step 6: Parse the command-line arguments. */
if (!cli.parse(argc, argv)) return 1;
/* Step 7: Configure the settings objects with the loaded JSON object. */
utilities::configure(jc, meter_settings, logging_settings);
/* Step 8: Initialise global state handlers (INT, USR1). */
framework::init_global_state_handlers();
/* Step 9: Create top-level components: logging and the executable. */
Logging logging(logging_settings);
Meter meter(meter_settings);
/* Step 10: Spawn the executable components on an executor and wait. */
framework::ThreadExecutor exec;
exec.spawn(meter);
exec.join();
return 0;
}
<file_sep>/include/exot/meters/power_msr.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/power_msr.h
* @author <NAME>
* @brief Module for measuring power via energy values accessed through
* Intel's MSRs.
*/
#pragma once
#if defined(__linux__) && defined(__x86_64__)
#include <chrono> // for durations and time points
#include <map> // for std::map
#include <string> // for std::string
#include <thread> // for sleep_for
#include <vector> // for variable-size arrays
#include <fmt/format.h> // for formatting strings
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/primitives/msr.h> // for MSR
#include <exot/utilities/bits.h> // for bit manipulation functions
#include <exot/utilities/configuration.h> // for configurable
namespace exot::modules {
struct power_msr : module {
using return_type = std::vector<double>;
enum class rapl_domain : unsigned short { pp0 = 0, pp1, pkg, sys };
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<rapl_domain> domains;
const char* name() const { return "power_msr"; }
/* @brief The JSON configuration function */
void configure() {
bind_and_describe_data(
"rapl_domains", domains,
"list of RAPL domains to use |rapl_domain[]|, choose "
"from [\"pp0\", \"pp1\", \"pkg\", \"sys\"]");
}
};
/**
* @brief Construct the MSR power module
*
* @param conf Module settings
*/
explicit power_msr(settings& conf);
/**
* @brief Main measurement function
*
* @return A vector of
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_; //! local settings
exot::primitives::MSR msr_; //! the MSR access component
/**
* Variables used for performing measurements
*/
double energy_status_unit_; /*! multiplier defining units in which the
* processor communicates energy readings */
std::chrono::time_point<std::chrono::steady_clock>
previous_time_point_; /*! time points need to be stored to get elapsed
* time */
return_type output_; /*! vector holding computed output values */
std::map<rapl_domain, std::uint64_t>
readings_; /*! map for holding new raw energy readings */
std::map<rapl_domain, std::uint64_t>
old_readings_; /*! map for holding old raw energy readings */
/**
* @brief Compute power from energy readings
*
* @param[in] new_energy The new energy
* @param[in] old_energy The old energy
* @param[in] elapsed_time The elapsed time
*
* @return Average power over the interval in Watts
*/
inline double energy_to_power(std::uint64_t new_energy,
std::uint64_t old_energy, double elapsed_time) {
auto overflow = (new_energy < old_energy) ? (1ULL << 32) : 0ULL;
return (static_cast<double>((new_energy + overflow) - old_energy) *
energy_status_unit_ / elapsed_time);
}
/**
* @brief Wrapper for reading energy values via MSR
*
* @param[in] domain The power domain to read
*
* @return The energy reading, in processor-specific units
*/
inline std::uint64_t get_energy(rapl_domain domain) {
return exot::utilities::extract_bit_range(
msr_.read_first(domain_to_msr_[domain]), 0u, 31u);
}
std::string domain_to_string(rapl_domain d);
/**
* Relevant MSR register addresses
*/
const std::uint64_t PP0_ENERGY_STATUS{0x639};
const std::uint64_t PP1_ENERGY_STATUS{0x641};
const std::uint64_t PKG_ENERGY_STATUS{0x611};
const std::uint64_t PLATFORM_ENERGY_STATUS{0x64d};
const std::uint64_t RAPL_POWER_UNIT{0x606};
/**
* Map between domains and relevant registers
*/
std::map<rapl_domain, std::uint64_t> domain_to_msr_{
{rapl_domain::pp0, PP0_ENERGY_STATUS},
{rapl_domain::pp1, PP1_ENERGY_STATUS},
{rapl_domain::pkg, PKG_ENERGY_STATUS},
{rapl_domain::sys, PLATFORM_ENERGY_STATUS}};
};
/* @note The following overload will also work with arrays of data. */
/**
* @brief Overload for rapl_domain enumeration.
*
* @param[in] j The json object
* @param d The enum object to write data to
*/
inline void from_json(const nlohmann::json& j, power_msr::rapl_domain& d) {
if (!j.is_string()) {
throw nlohmann::json::type_error::create(
302, fmt::format("type must be a string, but was a {}", j.type_name()));
} else {
auto value = j.get<nlohmann::json::string_t>();
if (value == "pp0") {
d = power_msr::rapl_domain::pp0;
} else if (value == "pp1") {
d = power_msr::rapl_domain::pp1;
} else if (value == "pkg") {
d = power_msr::rapl_domain::pkg;
} else if (value == "sys") {
d = power_msr::rapl_domain::sys;
} else {
throw nlohmann::json::other_error::create(
501, fmt::format("provided rapl domain value \"{}\" is not "
"featured in the enum class",
value));
}
}
}
/**
* @brief Overload for serialising rapl_domain enumeration.
*
* @param[in] j The json object
* @param d The enum object to serialise
*/
inline void to_json(nlohmann::json& j, const power_msr::rapl_domain& d) {
switch (d) {
case power_msr::rapl_domain::pp0:
j = "pp0";
break;
case power_msr::rapl_domain::pp1:
j = "pp1";
break;
case power_msr::rapl_domain::pkg:
j = "pkg";
break;
case power_msr::rapl_domain::sys:
j = "sys";
break;
}
}
} // namespace exot::modules
#endif
<file_sep>/include/exot/primitives/rng.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file primitives/rng.h
* @author <NAME>
* @brief Utilities to call hardware random number generator.
*/
#pragma once
/**
* Only supported on x86_64 platforms (Intel in particular)
*/
#if defined(__x86_64__)
#include <cstdint> // for explicit size ints
#include <utility> // for std::pair
namespace exot::primitives {
inline namespace x86_64 {
/**
* @brief Gets a 16-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto rand16()
-> std::pair<std::uint8_t, std::uint16_t> {
unsigned char ok;
std::uint16_t rand;
/* rdrand (and rdseed) indicate whether the operation was successful by
* setting the carry flag (CF), therefore 'cc' is added as a clobber argument,
* since the code modifies the flag registers. */
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Gets a 32-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto rand32()
-> std::pair<std::uint8_t, std::uint32_t> {
unsigned char ok;
std::uint32_t rand;
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Gets a 64-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto rand64()
-> std::pair<std::uint8_t, std::uint64_t> {
unsigned char ok;
std::uint64_t rand;
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Gets a 16-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto seed16()
-> std::pair<std::uint8_t, std::uint16_t> {
unsigned char ok;
std::uint16_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Gets a 32-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto seed32()
-> std::pair<std::uint8_t, std::uint32_t> {
unsigned char ok;
std::uint32_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Gets a 64-bit random number and operation status
*
* @return a pair <status, value>
*/
static inline __attribute__((always_inline)) auto seed64()
-> std::pair<std::uint8_t, std::uint64_t> {
unsigned char ok;
std::uint64_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
return {ok, rand};
}
/**
* @brief Tries to get a 16-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto rand16_until_ok()
-> std::uint16_t {
std::uint16_t rand;
asm volatile(
"1: \n\t"
"rdrand %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Tries to get a 32-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto rand32_until_ok()
-> std::uint32_t {
std::uint32_t rand;
asm volatile(
"1: \n\t"
"rdrand %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Tries to get a 64-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto rand64_until_ok()
-> std::uint64_t {
std::uint64_t rand;
asm volatile(
"1: \n\t"
"rdrand %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Tries to get a 16-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto seed16_until_ok()
-> std::uint16_t {
std::uint16_t rand;
asm volatile(
"1: \n\t"
"rdseed %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Tries to get a 32-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto seed32_until_ok()
-> std::uint32_t {
std::uint32_t rand;
asm volatile(
"1: \n\t"
"rdseed %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Tries to get a 64-bit random number until successful
*
* @return The random number
*/
static inline __attribute__((always_inline)) auto seed64_until_ok()
-> std::uint64_t {
std::uint64_t rand;
asm volatile(
"1: \n\t"
"rdseed %0 \n\t"
"jnc 1b \n\t"
: "=r"(rand)
:
: "cc");
return rand;
}
/**
* @brief Check if a 16-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_rand16(
std::uint8_t& ok) {
std::uint16_t rand;
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
/**
* @brief Check if a 32-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_rand32(
std::uint8_t& ok) {
std::uint32_t rand;
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
/**
* @brief Check if a 64-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_rand64(
std::uint8_t& ok) {
std::uint64_t rand;
asm volatile("rdrand %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
/**
* @brief Check if a 16-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_seed16(
std::uint8_t& ok) {
std::uint16_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
/**
* @brief Check if a 32-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_seed32(
std::uint8_t& ok) {
std::uint32_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
/**
* @brief Check if a 64-bit random number can be obtained
*
* @param ok The status
*/
static inline __attribute__((always_inline)) void check_seed64(
std::uint8_t& ok) {
std::uint64_t rand;
asm volatile("rdseed %0; setc %1" : "=r"(rand), "=rm"(ok) : : "cc");
}
} // namespace x86_64
} // namespace exot::primitives
#endif
<file_sep>/include/exot/utilities/platform_id.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/platform_id.h
* @author <NAME>
* @brief Platform identification utilities.
*
* @todo Abstract discovery into a JSON-serialisable class
*/
#pragma once
#include <array>
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace exot::utilities {
/**
* @brief Gets the kernel version.
*
* @return The kernel version. Nullopt if unsuccessful.
*/
std::optional<std::string> get_kernel_version();
/**
* @brief Gets all the available cpuinfo keys.
*
* @return The cpuinfo keys.
*/
std::vector<std::string> get_cpuinfo_keys();
/**
* @brief Gets the cpuinfo key-value pairs as a map for a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The cpuinfo as map. Empty if unsuccessful.
*/
std::optional<std::map<std::string, std::string>> get_cpuinfo_as_map(
unsigned cpu);
/**
* @brief Gets the complete cpuinfo as map array.
*
* @return The complete cpuinfo as map array.
*/
std::vector<std::map<std::string, std::string>>
get_complete_cpuinfo_as_map_array();
/**
* @brief Gets the cpuinfo value for a given key for a specific cpu.
*
* @param[in] cpu The cpu
* @param[in] key The key
*
* @return The cpuinfo value. Nullopt if unsuccessful.
*/
std::optional<std::string> get_cpuinfo_value(unsigned cpu,
const std::string& key);
/**
* @brief Gets the cpuinfo values for a given key for all cpus.
*
* @param[in] key The key
*
* @return The cpuinfo values. Empty if unsuccessful.
*/
std::vector<std::string> get_cpuinfo_values(const std::string& key);
/**
* @brief Gets the cpu count.
*
* @return The cpu count.
*/
unsigned get_cpu_count();
/**
* @brief Gets the thread count.
*
* @return The thread count.
*/
unsigned get_thread_count();
/**
* @brief Gets the core count.
*
* @return The core count.
*/
unsigned get_core_count();
/**
* @brief Gets the socket count.
*
* @return The socket count.
*/
unsigned get_socket_count();
/**
* @brief Gets the thread per core. Derived from get_thread_count and
* get_core_count.
*
* @return The thread per core.
*/
unsigned get_thread_per_core();
/**
* @brief Gets the core per socket. Derived from get_core_count and
* get_socket_count.
*
* @return The core per socket.
*/
unsigned get_core_per_socket();
/**
* @brief Gets the target architecture. Returns a compile-time value.
*
* @return The target architecture for which the binary was compiled.
*/
const char* get_target_architecture() noexcept;
/**
* @brief Gets the cpu vendor of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The cpu vendor. Nullopt if unsuccessful, or if provided cpu does
* not exist.
*/
std::optional<std::string> get_cpu_vendor(unsigned cpu);
/**
* @brief Gets the cpu model of a specific cpu.
* @details For x86_64 chips the model will be reported as:
* name: "{}", family: {}, model: {}, stepping: {}
* For ARM-based chips the model will be reported as:
* arch: {}, variant: {}, part: "{}", revision: {}
*
* @param[in] cpu The cpu
*
* @return The cpu model. Nullopt if unsuccessful, or if provided cpu does
* not exist.
*/
std::optional<std::string> get_cpu_model(unsigned cpu);
/**
* @brief Gets all unique cpu models and their associated cpus.
*
* @return A vector with unique cpu models and the associated cpu list.
* Nullopt if unsuccessful.
*/
std::optional<std::vector<std::string>> get_unique_cpu_models();
/**
* @brief Gets the cpu flags of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The cpu flags. Nullopt if unsuccessful, or if provided cpu does
* not exist.
*/
std::optional<std::string> get_cpu_flags(unsigned cpu);
/**
* @brief Gets the cpu flags as an array for a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The cpu flags array. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::vector<std::string>> get_cpu_flags_array(unsigned cpu);
/**
* @brief Gets the scaling governor of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The scaling governor. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::string> get_scaling_governor(unsigned cpu);
/**
* @brief Gets the min and max cpu frequencies of a specific cpu. The
* frequencies are given in Hz.
*
* @param[in] cpu The cpu
*
* @return The cpu frequencies. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::array<unsigned long, 2>> get_cpu_frequencies(unsigned cpu);
/**
* @brief Gets the minimum cpu frequency of a specific cpu. The frequency
* is given in Hz.
*
* @param[in] cpu The cpu
*
* @return The minimum cpu frequency. Nullopt if unsuccessful, or if
* provided cpu does not exist.
*/
std::optional<unsigned long> get_min_cpu_frequency(unsigned cpu);
/**
* @brief Gets the maximum cpu frequency of a specific cpu. The frequency
* is given in Hz.
*
* @param[in] cpu The cpu
*
* @return The maximum cpu frequency. Nullopt if unsuccessful, or if
* provided cpu does not exist.
*/
std::optional<unsigned long> get_max_cpu_frequency(unsigned cpu);
/**
* @brief Gets the string representation of online cpus.
* @details The string representation usually informs about a range of active
* cpus, e.g. in the form "0-7" for active cpus from 0 to 7.
*
* @return The online cpus. An empty string if unsuccessful.
*/
std::string get_online_cpus();
/**
* @brief Gets the string representation of offline cpus.
*
* @return The offline cpus. An empty string if unsuccessful.
*/
std::string get_offline_cpus();
/**
* @brief Gets the string representation of possible cpus. Possible cpus
* are those that can be either brought online, or made offline.
*
* @return The possible cpus. An empty string if unsuccessful.
*/
std::string get_possible_cpus();
/**
* @brief Gets the online cpus array.
*
* @return The online cpus array. Empty if unsuccessful.
*/
std::vector<bool> get_online_cpus_array();
/**
* @brief Determines if a cpu online.
*
* @param[in] cpu The cpu
*
* @return True if cpu online, False otherwise. Also false for non-existent
* cpus.
*/
bool is_cpu_online(unsigned int cpu);
/**
* @brief Gets the topology value given a valid key for a specific cpu.
* @details The possible keys are: "core_id", "core_siblings",
* "physical_package_id", "thread_siblings", "core_siblings_list",
* "thread_siblings_list", "book_id", "drawer_id", "book_siblings",
* "drawer_siblings".
*
* @param[in] cpu The cpu
* @param[in] key The key
*
* @return The topology value. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::string> get_topology_value(unsigned cpu,
const std::string& key);
/**
* @brief Gets the core identifier of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The core identifier.Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<unsigned> get_core_id(unsigned cpu);
/**
* @brief Gets the core siblings of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The core siblings. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<unsigned> get_core_siblings(unsigned cpu);
/**
* @brief Gets the core siblings as an array for a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The core siblings array. Nullopt if unsuccessful, or if provided
* cpu does not exist.
*/
std::optional<std::vector<unsigned>> get_core_siblings_array(unsigned cpu);
/**
* @brief Gets the core siblings count of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The core siblings count. Nullopt if unsuccessful, or if provided
* cpu does not exist.
*/
std::optional<unsigned> get_core_siblings_count(unsigned cpu);
/**
* @brief Gets the physical package identifier of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The physical package identifier. Nullopt if unsuccessful, or if
* provided cpu does not exist.
*/
std::optional<unsigned> get_physical_package_id(unsigned cpu);
/**
* @brief Gets the thread siblings of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The thread siblings. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<unsigned> get_thread_siblings(unsigned cpu);
/**
* @brief Gets the thread siblings as an array for a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The thread siblings array. Nullopt if unsuccessful, or if
* provided cpu does not exist.
*/
std::optional<std::vector<unsigned>> get_thread_siblings_array(unsigned cpu);
/**
* @brief Gets the thread siblings count of a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The thread siblings count. Nullopt if unsuccessful, or if
* provided cpu does not exist.
*/
std::optional<unsigned> get_thread_siblings_count(unsigned cpu);
/**
* @brief Gets the complete cpu topology as a map for a specific cpu.
*
* @param[in] cpu The cpu
*
* @return The cpu topology map. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::map<std::string, std::string>> get_cpu_topology_map(
unsigned cpu);
/**
* @brief Gets the serialised cpu topology of a specific cpu as a string.
* The result is JSON-like formatted.
*
* @param[in] cpu The cpu
*
* @return The cpu topology. Nullopt if unsuccessful, or if provided cpu
* does not exist.
*/
std::optional<std::string> get_cpu_topology(unsigned cpu);
/**
* @brief Gets a description of the complete topology for all cpus. The
* result is JSON-like formatted.
*
* @return The complete topology.
*/
std::vector<std::string> get_complete_topology();
} // namespace exot::utilities
<file_sep>/include/exot/utilities/main.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/main.h
* @author <NAME>
* @brief Wrappers for spawning typical applications with or without CLI.
*
* @details The following function templates perform the typical
* bootstrapping of applications composed with the framework. The
* functions are given framework components, like meter_host_logger,
* as template arguments. The components' settings structures
* are created and configured with JSON, and passed to the
* respective constructors. In the `cli_wrapper` the command line
* arguments are also parsed (as given to `main`). Components are
* then spawned with the `ThreadExecutor`.
*/
#include <string>
#include <tuple>
#include <type_traits>
#include <nlohmann/json.hpp>
#include <exot/framework/all.h>
#include <exot/utilities/cli.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/helpers.h>
#include <exot/utilities/logging.h>
#include <exot/utilities/types.h>
namespace exot::utilities {
/**
* @brief Provides a cli main wrapper for typical applications
*
* @tparam Components The component types
* @param argc The argc from main
* @param argv The argv from main
* @return Return code [0, 1]
*/
template <typename... Components>
auto cli_wrapper(int argc, char** argv) {
using component_ptrs_t = unique_ptr_tuple<Logging, Components...>;
using settings_tuple_t =
std::tuple<Logging::settings, typename Components::settings...>;
settings_tuple_t settings;
component_ptrs_t components;
CLI cli;
JsonConfig jc;
cli.add_configurations(jc.get_cli_configuration());
#ifdef __cpp_lib_apply
std::apply([&](auto&... v) { cli.collect_descriptions(v...); }, settings);
#else
const_for<0, std::tuple_size_v<settings_tuple_t>>(
[&](const auto I) { cli.collect_descriptions(std::get<I>(settings)); });
#endif
if (!cli.parse(argc, argv)) return 1;
#ifdef __cpp_lib_apply
std::apply([&](auto&... v) { configure(jc, v...); }, settings);
#else
const_for<0, std::tuple_size_v<settings_tuple_t>>(
[&](const auto I) { configure(jc, std::get<I>(settings)); });
#endif
exot::framework::init_global_state_handlers();
const_for<0, std::tuple_size_v<component_ptrs_t>>([&](const auto I) {
using component_t =
typename std::decay_t<decltype(std::get<I>(components))>::element_type;
std::get<I>(components) =
std::make_unique<component_t>(std::get<I>(settings));
});
if constexpr (sizeof...(Components) > 1ull) {
auto connector = exot::framework::Connector();
const_for<1ull, sizeof...(Components)>([&](const auto I) {
connector.connect(*std::get<I>(components),
*std::get<I + 1ull>(components));
});
}
exot::framework::ThreadExecutor executor;
#ifdef __cpp_lib_apply
std::apply([&](const auto&... v) { executor.spawn((*v)...); },
tail(std::move(components)));
#else
const_for<1, std::tuple_size_v<settings_tuple_t>>(
[&](const auto I) { executor.spawn(*std::get<I>(components)); });
#endif
executor.join();
return 0;
}
} // namespace exot::utilities<file_sep>/include/exot/generators/cache_maurice_mt.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/cache_maurice_mt.h
* @author <NAME>
* @brief Multi-threaded generator causing LLC cache eviction.
*/
#pragma once
#include <cmath>
#include <cstdint>
#include <mutex>
#include <vector>
#include <spdlog/spdlog.h>
#include <nlohmann/json.hpp>
#include <exot/generators/base_bitset.h>
#include <exot/utilities/alignment.h>
#include <exot/utilities/allocator.h>
#include <exot/utilities/cache.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/literals.h>
namespace exot::modules {
struct generator_cache_maurice_mt
: public exot::modules::bitset_generator_base {
struct settings : public exot::utilities::configurable<settings>,
public exot::modules::bitset_generator_base::settings {
/* Since settings inherits from base's settings, we need to provide a way
* to resolve to the right functions. The `set_json` and `configure` need to
* work on current structure's data as well as the derived one. The same
* pattern is used, for example, in the `meter_host`. */
using base_t = exot::utilities::configurable<settings>;
std::set<unsigned> cores;
double overprovision_factor{1.0};
using cache_maps_t =
std::vector<typename exot::utilities::CacheInfo::map_type>;
std::optional<cache_maps_t> cache_info;
const char* name() const { return "generator"; }
void set_json(const nlohmann::json& root) {
base_t::set_json(root);
exot::modules::bitset_generator_base::settings::set_json(root);
}
auto describe() {
return base_t::describe() +
exot::modules::bitset_generator_base::settings::describe();
}
void configure() {
base_t::bind_and_describe_data(
"cores", cores, "cores to run workers on |uint[]|, e.g. [0, 2]");
base_t::bind_and_describe_data(
"overprovision_factor", overprovision_factor,
"the memory overprovisioning factor |float|, e.g. 1.2");
base_t::bind_and_describe_data("cache_info", cache_info,
"manual cache info maps |CacheInfo[]|");
exot::modules::bitset_generator_base::settings::configure();
}
};
explicit generator_cache_maurice_mt(settings& conf);
void generate_load(const decomposed_type& decomposed_subtoken,
const enable_flag_type& flag, core_type core,
index_type index);
private:
/**
* Parameters as defined by [1] in Algorithm 1 (p. 8):
*
* - n : number of LLC ways;
* - o : log2(LLC line size), width of the 'offset' field in the address;
* - s : log2(LLC set count), width of the 'set' field in the address;
* - c : "multiplicative parameter c", overprovisioning of the buffer;
* - b : size of the buffer to allocate.
*
* Ignored parameters:
*
* - w : delay before sending a '1', or time to send '0'. This generator
* uses strict timing and executes the memory access loop continuously
* until a flag has been cleared by the generator_host.
*
* [1] <NAME>, <NAME>, <NAME>, and <NAME>, “C5: Cross-Cores
* Cache Exot Channel.,” DIMVA, vol. 9148, no. 3, pp. 46–64, 2015.
*/
double c_; //! multiplicative parameter
int n_; //! number of LLC ways
int o_; //! offset field width
int s_; //! set/index field width
int m_; //! stores n_ * c_
int b_; //! buffer size
/* Allocate a buffer of single byte units. */
using T = std::uint8_t;
/* Allocate the buffer at page boundaries. */
using Alloc =
exot::utilities::AlignedAllocator<std::uint8_t,
exot::utilities::operator""_KiB(4)>;
inline thread_local static std::once_flag once_flag_; //! per thread flag
inline thread_local static std::vector<T, Alloc> buffer_; //! per thread buf
settings lconf_; //! local settings
};
} // namespace exot::modules
<file_sep>/include/exot/utilities/workers.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/workers.h
* @author <NAME>
* @brief Workers for running callable objects.
*/
#pragma once
#include <functional> // for invoke
#include <fmt/format.h>
#include <spdlog/spdlog.h> // for logging
#include <exot/framework/state.h> // for State type
#include <exot/utilities/barrier.h> // for Barrier
#include <exot/utilities/thread.h> // for ThreadTraits
namespace exot::utilities {
inline namespace workers {
/**
* @brief Basic worker
*
* @tparam Work A callable type
* @tparam Args Argument types to the callable object
*/
template <class Work, typename... Args>
struct Worker {
using state_pointer = std::shared_ptr<exot::framework::State>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using work_type = Work;
/**
* No default constructor
*/
Worker() = delete;
/**
* @brief Constructor for the basic worker
*
* @param[in] state The pointer to a state object
* @param[in] work A callable object
* @param[in] logger A pointer to a debug logger
*/
Worker(state_pointer state, work_type&& work, logger_pointer logger = nullptr)
: state_(state), work_(std::forward<work_type>(work)){};
/**
* @brief Main operation
*
* @param[in] args Arguments to the callable object `work_`
*/
void operator()(Args&&... args) {
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[Worker] {}", exot::utilities::thread_info());
#endif
/* Repeatedly invoke the work function with its arguments until the state is
* marked as stopped. */
while (!state_->is_stopped()) {
std::invoke(std::forward<work_type>(work_), std::forward<Args>(args)...);
}
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr) logger_->trace("[Worker] {}", "exiting");
#endif
};
private:
state_pointer state_; //! A pointer to a state object
work_type work_; //! The callable object invoked in the processing loop
logger_pointer logger_; //! A pointer to a debug logger
};
/**
* @brief Synchronised worker with barriers
* @details The work function is performed between two barriers.
*
* @tparam Work A callable object of signature void()
*/
template <class Work = std::function<void()>>
struct BarrierWorker {
using state_pointer = std::shared_ptr<exot::framework::State>;
using barrier_type = exot::utilities::Barrier;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using work_type = Work;
/**
* No default constructor
*/
BarrierWorker() = delete;
/**
* @brief Constructor for the barrier worker
*
* @param[in] state The pointer to a state object
* @param barrier The reference to a barrier object
* @param[in] logger A pointer to a debug logger
* @param[in] work A callable object
*/
BarrierWorker(state_pointer state, barrier_type& barrier, work_type&& work,
logger_pointer logger = nullptr)
: state_(state), barrier_{barrier}, work_(work), logger_{logger} {};
/**
* @brief Main operation
*
* @param[in] barrier A reference to a barrier
*/
void operator()() {
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[BarrierWorker] {}", exot::utilities::thread_info());
#endif
while (!state_->is_stopped()) {
barrier_.wait();
work_();
barrier_.wait();
}
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr) logger_->trace("[BarrierWorker] {}", "exiting");
#endif
};
private:
state_pointer state_; //! A pointer to a state object
work_type work_; //! The callable object invoked in the processing loop
logger_pointer logger_; //! A pointer to a debug logger
barrier_type& barrier_; //! The barrier object
};
/**
* @brief Worker with custom thread properties
*
* @tparam Work A callable object of signature void()
*/
template <class Work = std::function<void()>>
struct PinnedWorker {
using state_pointer = std::shared_ptr<exot::framework::State>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using work_type = Work;
/**
* No default constructor
*/
PinnedWorker() = delete;
/**
* @brief Constructor for the pinned worker
*
* @param[in] state The pointer to a state object
* @param[in] pin The core to which the function is to be pinned
* @param[in] policy The scheduling policy of the executing thread
* @param[in] priority The scheduling priority of the executing thread
* @param[in] work A callable object
* @param[in] logger A pointer to a debug logger
*/
PinnedWorker(state_pointer state, unsigned int pin,
exot::utilities::SchedulingPolicy policy, unsigned int priority,
work_type&& work, logger_pointer logger = nullptr)
: state_(state),
work_(work),
pin_(pin),
policy_(policy),
priority_(priority),
logger_(logger){};
/**
* @brief Main operation
*/
void operator()() {
/* Set thread affinity and scheduling properties. */
ThreadTraits::set_affinity(pin_);
ThreadTraits::set_scheduling(policy_, priority_);
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[PinnedWorker] {}", exot::utilities::thread_info());
#endif
while (!state_->is_stopped()) { work_(); }
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr) logger_->trace("[PinnedWorker] {}", "exiting");
#endif
};
private:
state_pointer state_; //! A pointer to a state object
work_type work_; //! The callable object invoked in the processing loop
logger_pointer logger_; //! A pointer to a debug logger
unsigned int pin_; //! Core to which the executing thread is pinned
exot::utilities::SchedulingPolicy
policy_; //! The scheduling policy of the executing thread
unsigned int priority_; //! The scheduling priority of the executing thread
};
/**
* @brief Synchronised worker with barriers
* @details The work function is performed between two barriers.
*
* @tparam Work A callable object of signature void()
*/
template <class Work = std::function<void()>>
struct PinnedBarrierWorker {
using state_pointer = std::shared_ptr<exot::framework::State>;
using barrier_type = exot::utilities::Barrier;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using work_type = Work;
/* No default constructor */
PinnedBarrierWorker() = delete;
/**
* @brief Constructor for the pinned barrier worker
*
* @param[in] state The pointer to a state object
* @param[in] pin The core to which the function is to be pinned
* @param[in] policy The scheduling policy of the executing thread
* @param[in] priority The scheduling priority of the executing thread
* @param[in] work A callable object
* @param[in] logger A pointer to a debug logger
*/
PinnedBarrierWorker(state_pointer state, unsigned int pin,
exot::utilities::SchedulingPolicy policy,
unsigned int priority, barrier_type& barrier,
work_type&& work, logger_pointer logger = nullptr)
: state_(state),
work_(work),
pin_(pin),
policy_(policy),
priority_(priority),
barrier_{barrier},
logger_(logger){};
/**
* @brief Main operation
*
* @param[in] barrier A reference to a barrier
*/
void operator()() {
/* Set thread affinity and scheduling properties. */
ThreadTraits::set_affinity(pin_);
ThreadTraits::set_scheduling(policy_, priority_);
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[PinnedBarrierWorker] {}",
exot::utilities::thread_info());
#endif
while (!state_->is_stopped()) {
barrier_.wait();
work_();
barrier_.wait();
}
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[PinnedBarrierWorker] {}", "exiting");
#endif
};
private:
state_pointer state_; //! A pointer to a state object
work_type work_; //! The callable object invoked in the processing loop
logger_pointer logger_; //! A pointer to a debug logger
unsigned int pin_; //! Core to which the executing thread is pinned
exot::utilities::SchedulingPolicy
policy_; //! The scheduling policy of the executing thread
unsigned int priority_; //! The scheduling priority of the executing thread
barrier_type& barrier_; //! The barrier object
};
/**
* The following implementation uses the concept of policy-based design, where
* policy/mixin classes are used to provide functionality and structure.
*
* Classes have internally defined configuration structures, such that the class
* using the mixins can provide generic constructors. Constructors can be
* provided with configuration inline, by using initialiser lists `{}`.
*/
inline namespace policy_classes {
/**
* Mixin classes that provide a function `run()`, which executes a non-returning
* function with the desired synchronisation method.
*/
inline namespace synchronisation {
/**
* @brief Executes a function without any synchronisation.
*/
struct NoSynchronisation {
struct Configuration {};
Configuration conf_;
NoSynchronisation(Configuration& conf) : conf_(conf){};
virtual ~NoSynchronisation() = default;
inline void run(std::function<void()>&& f) { f(); };
};
/**
* @brief Executes a function between two calls to thread barriers.
*/
struct BarrierSynchronisation {
struct Configuration {
exot::utilities::Barrier& barrier;
};
Configuration conf_;
BarrierSynchronisation(Configuration& conf) : conf_(conf){};
virtual ~BarrierSynchronisation() = default;
inline void run(std::function<void()>&& f) {
conf_.barrier.wait();
f();
conf_.barrier.wait();
};
};
} // namespace synchronisation
/**
* Mixin classes that allow setting thread parameters prior inside the used
* thread. They provide an `enforce()` function, which sets thread affinity
* and/or scheduling.
*/
inline namespace threading {
struct BasicThreads {
struct Configuration {};
Configuration conf_;
BasicThreads(Configuration& conf) : conf_(conf){};
virtual ~BasicThreads() = default;
inline void enforce() {}
};
/**
* @brief Workers with pinned threads and scheduling policies
*
*/
struct PinnedThreads {
struct Configuration {
const unsigned int pin; //! Core to pin
const exot::utilities::SchedulingPolicy policy; //! Scheduling policy
const unsigned int priority; //! Scheduling priority
};
Configuration conf_;
PinnedThreads(Configuration& conf) : conf_(conf){};
virtual ~PinnedThreads() = default;
inline void enforce() {
ThreadTraits::set_affinity(conf_.pin);
ThreadTraits::set_scheduling(conf_.policy, conf_.priority);
};
};
/**
* @brief Workers with pinned/un-pinned threads and scheduling policies
*
*/
struct SpecialisedThreads {
struct Configuration {
const unsigned int pin; //! Core to pin
const bool should_pin; //! Should pin?
const exot::utilities::SchedulingPolicy policy; //! Scheduling policy
const unsigned int priority; //! Scheduling priority
};
Configuration conf_;
SpecialisedThreads(Configuration& conf) : conf_(conf){};
virtual ~SpecialisedThreads() = default;
inline void enforce() {
if (conf_.should_pin) ThreadTraits::set_affinity(conf_.pin);
ThreadTraits::set_scheduling(conf_.policy, conf_.priority);
};
};
} // namespace threading
} // namespace policy_classes
/**
* @brief Class for templated worker, which uses policy-based design.
* @details Uses one of the mixin classes above to provide additional
* functionality.
*
* @tparam SynchronisationPolicy A synchronisation mixin class type
* @tparam ThreadingPolicy A threading policy mixin class type
*/
template <typename SynchronisationPolicy, typename ThreadingPolicy>
class TemplatedWorker : public SynchronisationPolicy, public ThreadingPolicy {
public:
using state_pointer = std::shared_ptr<exot::framework::State>;
using logger_pointer = std::shared_ptr<spdlog::logger>;
using work_type = std::function<void()>;
/**
* @brief Constructs the templated worker
*
* @param[in] state A pointer to a state object
* @param[in] synch Synchronisation configuration
* @param[in] thread. Threading configuration
* @param[in] work The callable work object
* @param[in] logger A pointer to a debug logger
*/
TemplatedWorker(state_pointer state,
typename SynchronisationPolicy::Configuration&& synch,
typename ThreadingPolicy::Configuration&& thread,
work_type&& work, logger_pointer logger = nullptr)
: state_(state),
logger_(logger),
SynchronisationPolicy(synch),
ThreadingPolicy(thread),
work_(work){};
void operator()() {
ThreadingPolicy::enforce();
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr)
logger_->trace("[TemplatedWorker] {}", exot::utilities::thread_info());
#endif
while (!state_->is_stopped()) {
SynchronisationPolicy::run(std::forward<work_type>(work_));
}
#if defined(SPDLOG_TRACE_ON)
if (logger_ != nullptr) logger_->trace("[TemplatedWorker] {}", "exiting");
#endif
};
private:
work_type work_;
state_pointer state_;
logger_pointer logger_;
};
} // namespace workers
} // namespace exot::utilities
<file_sep>/include/exot/meters/base.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/base.h
* @author <NAME>
* @brief Definition of the module base class and template helpers.
*/
#pragma once
#include <string> // for std::string
#include <type_traits> // for enable_if_t, void_t, declval, true_type, false_type
namespace exot::modules {
/**
* @brief Default measurement units
*/
namespace DefaultUnits {
static inline constexpr const char* temperature = "°C";
static inline constexpr const char* frequency = "kHz";
static inline constexpr const char* power = "W";
static inline constexpr const char* process = "";
} // namespace DefaultUnits
/**
* @brief Base class from which meter modules inherit
* @details At the moment the class is only used for potential type trait
* operations.
*/
struct module {};
/**
* @brief Type trait for determining if a type inherits from module
*
* @tparam T The type
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_meter_module : std::false_type {};
template <typename T>
struct is_meter_module<
T,
std::enable_if_t<std::is_base_of_v<exot::modules::module, std::decay_t<T>>>>
: std::true_type {};
template <typename T>
inline constexpr bool is_meter_module_v = is_meter_module<T>::value;
/**
* @brief Type trait for determining if a type contains a measure function
*
* @tparam T The type
* @tparam <unnamed> Template helper
*/
template <typename T, typename = std::void_t<>>
struct has_meter_function : std::false_type {};
template <typename T>
struct has_meter_function<T,
std::void_t<decltype(std::declval<T&>().measure())>>
: std::true_type {};
template <typename T>
inline constexpr bool has_meter_function_v = has_meter_function<T>::value;
} // namespace exot::modules
<file_sep>/include/exot/utilities/types.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/types.h
* @author <NAME>
* @brief Custom type traits.
*/
#pragma once
#include <chrono> // for chrono types and clocks
#include <iostream> // for streams
#include <tuple> // for tuples
#include <type_traits> // for true_type, false_type, declval, decay_t...
#include <vector> // for variable-size arrays
/**
* Forward declarations of TConsumer, TProducer, TProcessor.
*/
namespace exot::framework {
struct TConsumer;
struct TProducer;
struct TProcessor;
} // namespace exot::framework
namespace exot::utilities {
/**
* @brief Is the given type a std::chrono::duration?
*
* @tparam T The type to check
*/
template <typename T>
struct is_duration //
: public std::false_type {};
template <typename Rep, typename Period>
struct is_duration<std::chrono::duration<Rep, Period>> //
: public std::true_type {};
template <typename T>
inline constexpr bool is_duration_v = is_duration<T>::value;
/**
* @brief Is the given type a std::chrono-like clock?
*
* @tparam T The type to check
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_clock : std::false_type {};
template <typename T>
struct is_clock<T,
std::void_t<typename std::decay_t<T>::duration, //
typename std::decay_t<T>::rep, //
typename std::decay_t<T>::period, //
typename std::decay_t<T>::time_point, //
decltype(std::declval<std::decay_t<T>>().now())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_clock_v = is_clock<T>::value;
/**
* @brief Determines if a type is EqualityComparable (named C++ req.)
*
* @tparam T The type
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_equality_comparable : std::false_type {};
template <typename T>
struct is_equality_comparable<
T, std::void_t<decltype(std::declval<T&>() == std::declval<T&>())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_equality_comparable_v =
is_equality_comparable<T>::value;
/**
* @brief Determines if a type is LessThanComparable (named C++ req.)
*
* @tparam T The type
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_lessthan_comparable : std::false_type {};
template <typename T>
struct is_lessthan_comparable<
T, std::void_t<decltype(std::declval<T&>() < std::declval<T&>())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_lessthan_comparable_v =
is_lessthan_comparable<T>::value;
/**
* @brief Determines if a type is EqualityComparable and LessThanComparable
*
* @tparam T The type
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_comparable : std::false_type {};
template <typename T>
struct is_comparable<
T, std::void_t<decltype(std::declval<T&>() == std::declval<T&>()),
decltype(std::declval<T&>() < std::declval<T&>())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_comparable_v = is_comparable<T>::value;
/**
* Helper compile-time contant for checking if integral types are of same size.
*/
template <typename T1, typename T2>
inline constexpr bool are_same_size = (sizeof(T1) == sizeof(T2));
/**
* @brief Provides the larger of two types as a member type
*
* @tparam T1 lhs type
* @tparam T2 rhs type
*/
template <typename T1, typename T2>
struct larger_of : std::conditional<(sizeof(T1) >= sizeof(T2)), T1, T2> {};
/**
* Helper alias for larger_of
*/
template <typename T1, typename T2>
using larger_of_t = typename larger_of<T1, T2>::type;
/**
* @brief Provides the smaller of two types as a member type
*
* @tparam T1 lhs type
* @tparam T2 rhs type
*/
template <typename T1, typename T2>
struct smaller_of : std::conditional<(sizeof(T1) >= sizeof(T2)), T2, T1> {};
/**
* Helper alias for smaller_of
*/
template <typename T1, typename T2>
using smaller_of_t = typename smaller_of<T1, T2>::type;
/**
* Helper compile-time contant for checking if all types are integral types
*/
template <typename... Ts>
inline constexpr bool are_integral = (std::is_integral_v<std::decay_t<Ts>> &&
...);
/**
* Helper compile-time contant for checking if all types are unsigned types
*/
template <typename... Ts>
inline constexpr bool are_unsigned = (std::is_unsigned_v<std::decay_t<Ts>> &&
...);
/**
* Helper compile-time contant for checking if all types are unsigned itegrals
*/
template <typename... Ts>
inline constexpr bool are_unsigned_integral = (are_integral<Ts...> &&
are_unsigned<Ts...>);
/**
* Alias for a decayed is_same type trait.
*/
template <typename T, typename U>
using is_same_d = typename std::is_same<std::decay_t<T>, std::decay_t<U>>;
/**
* Alias for a decayed is_same type trait.
*/
template <typename T, typename U>
using is_convertible_d =
typename std::is_convertible<std::decay_t<T>, std::decay_t<U>>;
/**
* @brief Compile-time helper for decayed string-convertible check
*/
template <typename T>
inline constexpr bool is_string_d = is_convertible_d<T, std::string>::value;
/**
* @brief Compile-time helper for decayed arithmetic check
*/
template <typename T>
inline constexpr bool is_arithmetic_d =
std::is_arithmetic<std::decay_t<T>>::value;
/**
* @brief Compile-time helper for decayed pointer check
*/
template <typename T>
inline constexpr bool is_pointer_d =
(std::is_pointer<std::decay_t<T>>::value ||
std::is_member_pointer<std::decay_t<T>>::value ||
std::is_null_pointer<std::decay_t<T>>::value);
/**
* @brief Type trait for character types
* @details Enabled if CharT is a standard or wide character.
*
* @tparam CharT The character type
* @tparam _ Template helper
*/
template <typename CharT, typename _ = void>
struct is_character : std::false_type {};
template <typename CharT>
struct is_character<CharT, std::enable_if_t<(std::is_same_v<CharT, char> ||
std::is_same_v<CharT, wchar_t> ||
std::is_same_v<CharT, char16_t> ||
std::is_same_v<CharT, char32_t>)>>
: std::true_type {};
/**
* @brief Compile time value for the `is_character` structure.
*/
template <typename CharT>
inline constexpr bool is_character_v = is_character<CharT>::value;
/**
* @brief Casts a type (e.g. scoped enum class) to its underlying type.
* @details This function may come useful when used in conjunction with a
* typed enum, e.g. `enum class X : int {};`, for which the
* operation `to_underlying_type(X::x)` will return an `int`.
*
* @param[in] t An object to cast
*
* @tparam T The type of the object
*
* @return The object statically casted to its underlying type.
*/
template <typename T>
constexpr auto to_underlying_type(T t) {
return static_cast<std::underlying_type_t<T>>(t);
}
namespace details {
/**
* @brief Type trait which determines if a type is a std::tuple.
*/
template <typename>
struct is_tuple : public std::false_type {};
/**
* @tparam Types A parameter pack of types used in a tuple. Matches any
* valid `std::tuple`.
*/
template <typename... Types>
struct is_tuple<std::tuple<Types...>> : public std::true_type {};
} // namespace details
/**
* @brief Type trait which determines if a type is a std::tuple specialisation.
*
* @tparam T The type
*/
template <typename T>
struct is_tuple : public details::is_tuple<std::decay_t<T>> {};
template <typename T>
inline constexpr bool is_tuple_v = is_tuple<T>::value;
/**
* @brief Type trait which determines if a type is a std::vector.
*/
template <typename>
struct is_vector : public std::false_type {};
template <typename T, typename Alloc>
struct is_vector<std::vector<T, Alloc>> : public std::true_type {};
template <typename T>
inline constexpr bool is_vector_v = is_vector<T>::value;
/**
* @brief Type trait which determines if a type satisfies the properties of
* an iterable type.
*
* @tparam T The type to check
* @tparam Enable A helper template parameter
*/
template <typename T, typename Enable = void>
struct is_iterable : std::false_type {};
/**
* @brief Valid if the template parameter `std::void_t` is well formed,
* when all types given to it as parameters are present/valid.
*
* `std::declval` is used to check if class methods exist.
* `std::decay` removes const/volatile qualifiers, references,
* giving just the plain type.
*/
template <typename T>
struct is_iterable<
T, std::void_t<typename std::decay_t<T>::value_type,
typename std::decay_t<T>::iterator,
decltype(std::declval<std::decay_t<T>>().begin()),
decltype(std::declval<std::decay_t<T>>().end())>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_iterable_v = is_iterable<T>::value;
/**
* @brief Type trait which determines if a type satisfies the properties of
* an iterable type.
*
* @tparam T The type to check
* @tparam Enable A helper template parameter
*/
template <typename T, typename Enable = void>
struct is_iterable_and_clearable : std::false_type {};
/**
* @brief Valid if the template parameter `std::void_t` is well formed,
* when all types given to it as parameters are present/valid.
*
* `std::declval` is used to check if class methods exist.
* `std::decay` removes const/volatile qualifiers, references,
* giving just the plain type.
*/
template <typename T>
struct is_iterable_and_clearable<
T, std::void_t<typename std::decay_t<T>::value_type,
typename std::decay_t<T>::iterator,
decltype(std::declval<std::decay_t<T>>().begin()),
decltype(std::declval<std::decay_t<T>>().end()),
decltype(std::declval<std::decay_t<T>>().clear())>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_iterable_and_clearable_v =
is_iterable_and_clearable<T>::value;
/**
* @brief Type trait which determines if a type is const-iterable.
*
* @tparam T The type to check
* @tparam Enable A helper template parameter
*/
template <typename T, typename Enable = void>
struct is_const_iterable : std::false_type {};
template <typename T>
struct is_const_iterable<
T, std::void_t<typename std::decay_t<T>::value_type,
typename std::decay_t<T>::const_iterator,
decltype(std::declval<std::decay_t<T>>().cbegin()),
decltype(std::declval<std::decay_t<T>>().cend())>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_const_iterable_v = is_const_iterable<T>::value;
/**
* @brief Type trait which determines if a type is CopyInsertable and can
* be appended to.
*
* @tparam T The type
* @tparam Enable Template helper
*/
template <typename T, typename Enable = void>
struct has_push_back : std::false_type {};
template <typename T>
struct has_push_back<T, std::void_t<decltype(std::declval<T>().push_back(
typename T::value_type{}))>> : std::true_type {};
template <typename T>
inline constexpr bool has_push_back_v = has_push_back<T>::value;
/**
* @brief Type trait which determines if a type has some Container
* facilities: size, and element-wise access.
*
* @tparam T The type to check
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct is_location_accessible : std::false_type {};
template <typename T>
struct is_location_accessible<
T, std::void_t<typename std::decay_t<T>::value_type,
typename std::decay_t<T>::size_type,
decltype(std::declval<T&>().size()),
decltype(std::declval<T&>().at(
std::declval<typename std::decay_t<T>::size_type>())),
decltype(std::declval<T&>().operator[](
std::declval<typename std::decay_t<T>::size_type>()))>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_location_accessible_v =
is_location_accessible<T>::value;
/**
* @brief Determines if a type can be writen to an output stream (<<)
*
* @tparam T The type
* @tparam S The stream
* @tparam <unnamed> Template helper
*/
template <typename T, typename S = std::ostream, typename = void>
struct is_writable_to_stream : std::false_type {};
template <typename T>
struct is_writable_to_stream<
T, std::ostream,
std::void_t<decltype(std::declval<std::ostream&>() << std::declval<T&>())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_writable_to_stream_v = is_writable_to_stream<T>::value;
/**
* @brief Determines if a type can be read from an input stream (>>)
*
* @tparam T The type
* @tparam S The stream
* @tparam <unnamed> Template helper
*/
template <typename T, typename S = std::istream, typename = void>
struct is_readable_from_stream : std::false_type {};
template <typename T>
struct is_readable_from_stream<
T, std::istream,
std::void_t<decltype(std::declval<std::istream&>() >> std::declval<T&>())>>
: std::true_type {};
template <typename T>
inline constexpr bool is_readable_from_stream_v =
is_readable_from_stream<T>::value;
template <typename... Ts>
using unique_ptr_tuple = std::tuple<std::unique_ptr<Ts>...>;
/* The following type traits determine framework node type. Nodes were provided
* additional inherited classes to simplify dealing with template
* instantiations. Therefore, to check if a node is a consumer, the only check
* necessary is to verify if the type inherits from TConsumer. */
template <typename T, typename Enable = void>
struct is_consumer : public std::false_type {};
template <typename T>
struct is_consumer<T, std::enable_if_t<std::is_base_of_v<
exot::framework::TConsumer, std::decay_t<T>>>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_consumer_v = is_consumer<T>::value;
template <typename T, typename Enable = void>
struct is_producer : public std::false_type {};
template <typename T>
struct is_producer<T, std::enable_if_t<std::is_base_of_v<
exot::framework::TProducer, std::decay_t<T>>>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_producer_v = is_producer<T>::value;
template <typename T, typename Enable = void>
struct is_processor : public std::false_type {};
template <typename T>
struct is_processor<T, std::enable_if_t<std::is_base_of_v<
exot::framework::TProcessor, std::decay_t<T>>>>
: public std::true_type {};
template <typename T>
inline constexpr bool is_processor_v = is_processor<T>::value;
template <typename T, typename Enable = void>
struct has_input_interface : public std::false_type {};
template <typename T>
struct has_input_interface<T, std::enable_if_t<is_consumer_v<T>>>
: public std::true_type {};
template <typename T>
inline constexpr bool has_input_interface_v = has_input_interface<T>::value;
template <typename T, typename Enable = void>
struct has_output_interface : public std::false_type {};
template <typename T>
struct has_output_interface<T, std::enable_if_t<is_producer_v<T>>>
: public std::true_type {};
template <typename T>
inline constexpr bool has_output_interface_v = has_output_interface<T>::value;
/**
* @brief Type trait to determine if a class has a void(void) process()
* function
*
* @tparam T The class
* @tparam <unnamed> Template helper
*/
template <typename T, typename = void>
struct has_process_function : public std::false_type {};
template <typename T>
struct has_process_function<
T, std::void_t<decltype(std::declval<std::decay_t<T>>().process())>>
: public std::true_type {};
template <typename T>
inline constexpr bool has_process_function_v = has_process_function<T>::value;
} // namespace exot::utilities
<file_sep>/include/exot/meters/thermal_msr.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/thermal_msr.h
* @author <NAME>
* @brief Thermal metering module utilising Intel's MSRs.
*/
#pragma once
#if defined(__linux__) && !defined(__ANDROID__) && defined(__x86_64__)
#include <cstdint> // for std::uint*
#include <string> // for std::string
#include <vector> // for variable-size arrays
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/primitives/msr.h> // for MSR
#include <exot/utilities/configuration.h> // for configurable
namespace exot::modules {
/**
* @brief Module to read temperatures via model specific registers on Intel
* processors
* @details The module supports reading core temperatures, and package
* temperatures, as long as the processor supports it. Support for
* package-level thermal information is checked upon instantiation.
*/
struct thermal_msr : module {
using return_type = std::vector<unsigned short>;
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
std::vector<unsigned> cores; //! vector of cores
bool use_package{false}; //! flag to access package temperatures
const char* name() const { return "thermal_msr"; }
void configure() {
bind_and_describe_data(
"cores", cores, "cores to read temperature of |uint[]|, e.g. [0, 2]");
bind_and_describe_data("package", use_package,
"access the package temperatures? |bool|");
}
};
/**
* @brief Construct the MSR thermal module
*
* @param conf Module settings
*/
explicit thermal_msr(settings& conf);
/**
* @brief Main measurement function
*
* @return A vector of desired temperatures
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
settings conf_; //! local settings
exot::primitives::MSR msr_; //! the MSR access component
std::uint64_t temperature_target_; //! the reference temperature
std::vector<std::uint64_t> readings_; //! vector holding temperature readings
/**
* @brief Provide sensible settings
* @details The used MSR components will throw when any of the selected
* cores exceed hardware concurrency, so there is no need to
* perform that check here.
*
* @param conf Module settings
*
* @return Module settings
*/
settings validate_settings(settings& conf);
/**
* @brief Convienience wrapper for getting the temperature reading
*
* @param[in] raw The raw MSR value
*
* @return The temperature.
*/
unsigned short get_temperature(std::uint64_t raw);
/**
* @brief Convienience wrapper for getting temperature readings
*
* @param[in] raw The raw MSR values
*
* @return The temperatures.
*/
return_type get_temperatures(std::vector<std::uint64_t>&& raw);
/**
* Relevant MSR register addresses
*/
const std::uint64_t IA32_TEMPERATURE_TARGET = 0x1A2;
const std::uint64_t IA32_THERM_STATUS = 0x19C;
const std::uint64_t IA32_PACKAGE_THERM_STATUS = 0x1B1;
};
} // namespace exot::modules
#endif
<file_sep>/cmake/modules/configure_clang_tidy.cmake
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
#
##
# @file configure_clang_tidy.cmake
# @author <NAME>
# @brief Function that bootstraps the clang-tidy static analyser.
#
include(colour_message)
function(configure_clang_tidy enable)
if(${enable})
# Find the necessary executables
find_program(clang_tidy_exe NAMES
"clang-tidy"
"clang-tidy-6" "clang-tidy-7" "clang-tidy-8"
"clang-tidy-6.0" "clang-tidy-7.0" "clang-tidy-8.0"
"/usr/local/opt/llvm/bin/clang-tidy")
find_program(clang_apply_replacements_exe NAMES
"clang-apply-replacements"
"clang-apply-replacements-6"
"clang-apply-replacements-7"
"clang-apply-replacements-8"
"clang-apply-replacements-6.0"
"clang-apply-replacements-7.0"
"clang-apply-replacements-8.0"
"/usr/local/opt/llvm/bin/clang-apply-replacements")
find_program(python NAMES "python" "python2.7")
if (clang_tidy_exe AND clang_apply_replacements_exe)
message(STATUS "Found clang-tidy: " ${clang_tidy_exe})
message(STATUS "Found clang-apply-replacements: " ${clang_apply_replacements_exe})
if (NOT CMAKE_EXPORT_COMPILE_COMMANDS)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
endif ()
list(GET CMAKE_CXX_CLANG_TIDY 1 checks)
if (${checks} STREQUAL NOTFOUND)
set(checks "-checks=-*,-fuchsia*,-clang-diagnostic-unused-parameter,-objc*,llvm-*,bugprone-*,cppcoreguidelines-*,llvm-include-order,clang-analyzer-alpha.*,modernize-*,readability-*,performance-*")
endif()
# Enable CLANG_TIDY for each build
if (${CMAKE_CXX_CLANG_TIDY})
else ()
set(CMAKE_CXX_CLANG_TIDY "")
list(APPEND CMAKE_CXX_CLANG_TIDY ${clang_tidy_exe} ${checks})
endif ()
find_program(run_clang_tidy_exe NAMES
"run-clang-tidy.py" "run_clang_tidy"
"run-clang-tidy-6.0" "run-clang-tidy-6.0.py")
if (NOT run_clang_tidy_exe)
set(run_clang_tidy_exe ${CMAKE_CURRENT_LIST_DIR}/cmake/scripts/run-clang-tidy.py)
endif ()
# Provide a global target for linting all library sources
if(TARGET tidy-all)
else ()
add_custom_target(
tidy-all
COMMAND "${run_clang_tidy_exe}"
${checks}
-clang-tidy-binary="${clang_tidy_exe}"
-clang-apply-replacements-binary="${clang_apply_replacements_exe}"
-extra-arg='-std=c++17'
-style=Google
-export-fixes='fixes.yaml'
COMMENT "Running clang-tidy")
endif ()
else ()
colour_message(WARNING RED "Binaries for clang-tidy were not found")
endif()
endif()
endfunction()
<file_sep>/examples/generator.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file examples/generator.cpp
* @author <NAME>
* @brief An example generator application, producing synthetic load.
*/
#include <exot/components/generator_host.h>
#include <exot/components/schedule_reader.h>
#include <exot/framework/all.h>
#include <exot/generators/utilisation_mt.h>
#include <exot/utilities/cli.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/logging.h>
int main(int argc, char** argv) {
using loadgen =
exot::components::generator_host<std::chrono::microseconds,
exot::modules::generator_utilisation_mt>;
using reader =
exot::components::schedule_reader<typename loadgen::token_type>;
using logger = exot::utilities::Logging;
using exot::utilities::CLI;
using exot::utilities::JsonConfig;
CLI cli;
JsonConfig jc;
cli.add_description(
"This multithreaded generator can be used to generate synthetic load on
a specified number of cores.");
cli.add_configurations(jc.get_cli_configuration());
if (!cli.parse(argc, argv)) return 1;
loadgen::settings loadgen_settings;
reader::settings reader_settings;
logger::settings logger_settings;
exot::utilities::configure(jc.get_const_ref(), loadgen_settings,
reader_settings, logger_settings);
exot::framework::init_global_state_handlers();
logger log(logger_settings);
reader read(reader_settings);
loadgen load(loadgen_settings);
exot::framework::Connector().pipeline(read, load);
exot::framework::ThreadExecutor exec;
exec.spawn(read, load);
exec.join();
return 0;
}
<file_sep>/include/exot/generators/base_ffb.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file generators/base_ffb.h
* @author <NAME>
* @brief
*/
#pragma once
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/utilities/configuration.h>
#include <exot/utilities/ostream.h>
namespace exot::modules {
/**
* @brief The bitset generator base class.
* @note Many generators share the same input interface: the activation is
* "binary", and determined by a bit value set on an unsigned
* number.
*/
struct base_generator_ffb {
using subtoken_type = int; // number of desired frequency changes
using core_type = unsigned; // core number
using decomposed_type = int; // number of desired frequency changes
using index_type = std::size_t; // thread index
using enable_flag_type = std::atomic_bool;
using logger_pointer = std::shared_ptr<spdlog::logger>;
struct settings : public exot::utilities::configurable<settings> {
unsigned core;
const char* name() const { return "generator"; }
void configure() {
bind_and_describe_data(
"cores", core, "cores to run workers on |uint[]|, e.g. [1, 2, 3]");
}
};
explicit base_generator_ffb(settings& conf) : conf_{conf} {
SPDLOG_LOGGER_DEBUG(logger_, "[generator] cores: {}", conf_.core);
}
inline decomposed_type decompose_subtoken(const subtoken_type& subtoken,
core_type core, index_type index) {
return 0;
}
inline bool validate_subtoken(const subtoken_type& subtoken) { return true; }
inline void generate_load(const decomposed_type& decomposed_subtoken,
const enable_flag_type& flag, core_type core,
index_type index) {}
virtual inline std::chrono::nanoseconds get_sleep_time(
int subtoken, std::chrono::nanoseconds measurment_time) = 0;
protected:
settings conf_;
logger_pointer logger_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
} // namespace exot::modules
<file_sep>/include/exot/utilities/cache.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/cache.h
* @author <NAME>
* @brief Cache identification utility.
*/
#pragma once
#include <array>
#include <cmath>
#include <map>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <fmt/format.h>
#include <exot/utilities/bits.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/formatting.h>
#include <exot/utilities/types.h>
/**
* Accesses values defined in sysfs. For example, for the CPU directory
* /sys/devices/system/cpu/cpu0/ the values are (Intel(R) Core(TM) i7-6700):
*
* ./cache/index0/physical_line_partition 1
* ./cache/index0/number_of_sets 64
* ./cache/index0/ways_of_associativity 8
* ./cache/index0/id 0
* ./cache/index0/shared_cpu_list 0,4
* ./cache/index0/type Data
* ./cache/index0/size 32K
* ./cache/index0/level 1
* ./cache/index0/coherency_line_size 64
* ./cache/index0/shared_cpu_map 11
* ./cache/index1/physical_line_partition 1
* ./cache/index1/number_of_sets 64
* ./cache/index1/ways_of_associativity 8
* ./cache/index1/id 0
* ./cache/index1/shared_cpu_list 0,4
* ./cache/index1/type Instruction
* ./cache/index1/size 32K
* ./cache/index1/level 1
* ./cache/index1/coherency_line_size 64
* ./cache/index1/shared_cpu_map 11
* ./cache/index2/physical_line_partition 1
* ./cache/index2/number_of_sets 1024
* ./cache/index2/ways_of_associativity 4
* ./cache/index2/id 0
* ./cache/index2/shared_cpu_list 0,4
* ./cache/index2/type Unified
* ./cache/index2/size 256K
* ./cache/index2/level 2
* ./cache/index2/coherency_line_size 64
* ./cache/index2/shared_cpu_map 11
* ./cache/index3/physical_line_partition 1
* ./cache/index3/number_of_sets 8192
* ./cache/index3/ways_of_associativity 16
* ./cache/index3/id 0
* ./cache/index3/shared_cpu_list 0-7
* ./cache/index3/type Unified
* ./cache/index3/size 8192K
* ./cache/index3/level 3
* ./cache/index3/coherency_line_size 64
* ./cache/index3/shared_cpu_map ff
*/
namespace exot::utilities {
/**
* @brief Cache type enumeration
*/
enum class CacheType : int {
Data = 0,
Instruction = 1,
Unified = 2,
Unknown = -1
};
/**
* @brief Cache info structure, accessed per core and cache index
*/
struct CacheInfo {
using key_type = std::string; //! mapping key type
using value_type = std::optional<int>; //! mapping value type
using map_type = std::map<key_type, value_type>; //! mapping type
/**
* No default constructor
*/
CacheInfo() = delete;
/**
* @brief Manually assigns cache info for a cpu & index pair.
* @note The provided mapping must have all keys already present in the
* empty `cache_params_`.
*
* @param[in] cpu The cpu
* @param[in] index The index
* @param[in] manual_mapping The manual mapping
*/
CacheInfo(unsigned cpu, unsigned index, const map_type& manual_mapping)
: cpu_{cpu}, index_{index} {
/* Checks if a key 'key' is present in mapping 'map'. */
auto contains = [](const key_type& key, const map_type& map) -> bool {
return map.find(key) != map.end();
};
/* Make sure that all cache_params_ keys are present in the mapping. */
for (const auto& [key, _] : cache_params_) {
if (!contains(key, manual_mapping)) {
throw std::logic_error(
fmt::format("At least 1 key required by CacheInfo missing in the "
"provided mapping: {}",
key));
} else {
cache_params_.at(key) = manual_mapping.at(key);
}
}
}
/**
* @brief Get the cache info for a cpu & index pair.
*
* @param[in] cpu The cpu
* @param[in] index The index
*/
explicit CacheInfo(unsigned cpu, unsigned index) : cpu_{cpu}, index_{index} {
/* The sysfs cache info is not available on ARM platforms! */
static constexpr auto source_fmt_ =
"/sys/devices/system/cpu/cpu{}/cache/index{}/";
const auto root_path_ = fmt::format(source_fmt_, cpu, index);
/* The root path must be a valid directory. If it's not, it's either not
* accessible, or does not exist (like in the case of ARM processors). */
if (!is_directory(root_path_)) {
throw std::logic_error(fmt::format(
"the cpu-index pair ({}, {}) does not resolve to a valid path ({})",
cpu, index, root_path_));
}
/* Loop through keys in cache_params_ and fill with values, if possible. */
for (auto& [key, ___] : cache_params_) {
auto value = value_type{std::nullopt};
auto path = root_path_ + key;
if (key == "size") {
/* "size" has a 'K' appended to it, extract just the number. */
auto _ = exot::utilities::get_value_from_file<std::string>(path);
if (_.has_value())
value = kibibytes_to_bytes(
static_cast<int>(exot::utilities::extract_number(_.value())));
} else if (key == "type") {
/* "type" returns a string, either Data, Instruction, or Unified. */
auto _ = exot::utilities::get_value_from_file<std::string>(path);
if (_.has_value()) {
if (_.value() == "Data") {
value = static_cast<int>(CacheType::Data);
} else if (_.value() == "Instruction") {
value = static_cast<int>(CacheType::Instruction);
} else if (_.value() == "Unified") {
value = static_cast<int>(CacheType::Unified);
} else {
value = static_cast<int>(CacheType::Unknown);
}
}
} else if (key == "shared_cpu_map") {
/* 'shared_cpu_map' is reported as a hexadecimal value-bitfield. */
auto _ = exot::utilities::get_value_from_file<std::string>(path);
if (_.has_value()) {
value = exot::utilities::read_hex_value(_.value());
}
} else {
value = exot::utilities::get_value_from_file<int>(path);
}
/* If no value has been set so far, a nullopt will be written. */
cache_params_[key] = value;
}
}
/**
* @brief Convert kibibytes to bytes.
* @note Sysfs provides values in KiB, e.g. 8192K is 8 MiB, not 8MB.
*
* @param[in] KiB The value in kibibytes
*
* @return The corresponding bytes value.
*/
constexpr static auto kibibytes_to_bytes(int KiB) -> int {
return KiB * 1024;
}
// clang-format off
const auto& get_params() const { return cache_params_; }
inline unsigned cpu() const { return cpu_; }
inline unsigned index() const { return index_; }
inline value_type physical_line_partition() const { return cache_params_.at("physical_line_partition"); }
inline value_type number_of_sets() const { return cache_params_.at("number_of_sets"); }
inline value_type ways_of_associativity() const { return cache_params_.at("ways_of_associativity"); }
inline value_type id() const { return cache_params_.at("id"); }
inline value_type type() const { return cache_params_.at("type"); }
inline value_type size() const { return cache_params_.at("size"); }
inline value_type level() const { return cache_params_.at("level"); }
inline value_type coherency_line_size() const { return cache_params_.at("coherency_line_size"); }
inline value_type shared_cpu_map() const { return cache_params_.at("shared_cpu_map"); }
// clang-format on
bool is_valid() const {
return level().has_value() //
&& type().has_value() //
&& size().has_value() //
&& number_of_sets().has_value() //
&& ways_of_associativity().has_value() //
&& coherency_line_size().has_value() //
&& shared_cpu_map().has_value();
}
auto to_string() const {
return fmt::format(
R"({{"physical_line_partition": {}, "number_of_sets": {}, )"
R"(ways_of_associativity": {}, "id": {}, "type": {}, "size": {}, )"
R"("level": {}, "coherency_line_size": {}, "shared_cpu_map": {}}})",
physical_line_partition().value_or(-1), number_of_sets().value_or(-1),
ways_of_associativity().value_or(-1), id().value_or(-1),
type().value_or(-1), size().value_or(-1), level().value_or(-1),
coherency_line_size().value_or(-1), shared_cpu_map().value_or(-1));
}
private:
unsigned cpu_;
unsigned index_;
/**
* The internal map holding the valid keys and values
*/
map_type cache_params_{
{"physical_line_partition", {}},
{"number_of_sets", {}},
{"ways_of_associativity", {}},
{"id", {}},
{"type", {}},
{"size", {}},
{"level", {}},
{"coherency_line_size", {}},
{"shared_cpu_map", {}},
};
};
/**
* @brief Cache info for a specific CPU
*/
struct CPUCacheInfo {
/**
* No default constructor.
*/
CPUCacheInfo() = delete;
/**
* @brief Initialise CPUCacheInfo with CacheInfo objects
*
* @param[in] cpu The cpu
* @param[in] infos_or_maps The infos or maps
*
* @tparam C The iterable container holding the infos or maps
* @tparam <unnamed> Template helper
*/
template <typename C,
typename = std::enable_if_t<
(exot::utilities::is_iterable_v<C> &&
(std::is_same_v<CacheInfo, typename C::value_type> ||
std::is_same_v<typename CacheInfo::map_type,
typename C::value_type>))>>
explicit CPUCacheInfo(unsigned cpu, const C& infos_or_maps) : cpu_{cpu} {
if constexpr (std::is_same_v<typename C::value_type, CacheInfo>) {
for (const auto& info : infos_or_maps) {
caches_.push_back(info);
caches_map_.insert({{info.level().value(), info.type().value()}, info});
}
} else {
unsigned i{0};
for (const auto& map : infos_or_maps) {
auto info = CacheInfo(cpu_, i, map);
if (!info.is_valid()) {
throw std::logic_error(
"CacheInfo for cpu {} created with an CacheInfo or a mapping is "
"not valid.");
}
caches_.push_back(info);
caches_map_.insert({{info.level().value(), info.type().value()}, info});
++i;
}
}
}
/**
* @brief Get info of all caches for a given CPU
*
* @param[in] cpu The cpu
*/
explicit CPUCacheInfo(unsigned cpu) : cpu_{cpu} {
if (cpu > std::thread::hardware_concurrency()) {
throw std::logic_error(fmt::format("cpu () > hw. concurrency ()", cpu,
std::thread::hardware_concurrency()));
}
root_path_ = fmt::format("/sys/devices/system/cpu/cpu{}/cache", cpu);
/* The root path must be a valid directory. If it's not, it's either not
* accessible, or does not exist (like in the case of ARM processors). */
if (!is_directory(root_path_)) {
throw std::logic_error(fmt::format(
"the root path is not available/accessible: {}", root_path_));
}
for (auto i = int{0};; ++i) {
if (!is_directory(fmt::format("{}/index{}", root_path_, i))) {
cache_count_ = i;
break;
}
}
for (auto i = int{0}; i < cache_count_; ++i) {
auto _ = CacheInfo(cpu, i);
if (!_.is_valid()) {
throw std::logic_error(
"CacheInfo for cpu {} created from sysfs is not valid.");
}
caches_.push_back(_);
caches_map_.insert({{_.level().value(), _.type().value()}, _});
}
}
auto cpu() const -> unsigned { return cpu_; }
auto count() const -> unsigned { return cache_count_; }
const auto& at(size_t idx) const { return caches_.at(idx); }
const auto& at(int level, int type) const {
return caches_map_.at({level, type});
}
const auto& llc() const { return caches_map_.at({levels(), 2}); }
const auto& caches() const { return caches_; }
const auto& caches_map() const { return caches_map_; }
auto levels() const -> int {
auto _ = std::vector<int>{};
for (auto& cache : caches_) {
if (cache.level().has_value()) { _.push_back(cache.level().value()); }
}
return *std::max_element(_.begin(), _.end());
}
private:
unsigned cpu_;
std::string root_path_;
unsigned cache_count_{0};
std::vector<CacheInfo> caches_;
std::map<std::pair<int, int>, CacheInfo> caches_map_;
};
/**
* @brief Decomposes a physical address to tag, set, and offset.
*/
struct AddressDecomposer {
private:
unsigned line_size, number_of_sets;
unsigned long long o, s;
std::pair<unsigned long long, unsigned long long> olim, slim, tlim;
void set_limits(const CacheInfo& info) {
/* Will throw `std::bad_optional_access` if no value is available in cache
* info. */
line_size = info.coherency_line_size().value();
number_of_sets = info.number_of_sets().value();
o = static_cast<unsigned long long>(std::log2(line_size));
s = static_cast<unsigned long long>(std::log2(number_of_sets));
olim = std::make_pair(0ull, o - 1ull);
slim = std::make_pair(o, o + s - 1ull);
tlim = std::make_pair(o + s, 63ull);
}
public:
/**
* @brief Default constructor, uses LLC address.
*/
AddressDecomposer() : AddressDecomposer(3u, CacheType::Unified) {}
AddressDecomposer(const CacheInfo& info) { set_limits(info); }
/**
* @brief Constructs the decomposer for a given cache level (2 or 3)
*
* @param[in] level The cache level
*/
explicit AddressDecomposer(unsigned level, CacheType type,
std::optional<CPUCacheInfo> info = std::nullopt) {
if (level > 3 || level < 1) throw std::out_of_range("only L1, L2 and L3");
/* This assumes that all cores share same cache characteristics (in terms of
* sizes, ways, etc., not sharing). If a (level, type) pair is not found, a
* key error will be thrown. */
auto cache_info = info.has_value() ? info.value() : CPUCacheInfo(0);
auto cache = cache_info.at(level, static_cast<int>(type));
set_limits(cache);
}
/**
* @brief Get field lengths (tag, set, offset)
* @note The length of the tag field will likely not correspond to the
* actual length, which is architecture-specific. For example,
* on x86_64 processors the physical address can be 48 bits, even
* though the ISA allows the entire 64 bit value to be used.
* The calculation below assumes a 64 bit address.
*
* @return The field lengths as a tuple.
*/
auto get_field_lengths() { return std::make_tuple(64ull - (o + s), s, o); }
/**
* @brief Decomposes a physical address to (tag, set, offset)
*
* @param[in] physical_address The physical address
*
* @return The decomposed address (tag, set, offset)
*/
auto operator()(unsigned long long physical_address)
-> std::array<unsigned long long, 3> {
using namespace exot::utilities;
return {extract_bit_range(physical_address, tlim.first, tlim.second),
extract_bit_range(physical_address, slim.first, slim.second),
extract_bit_range(physical_address, olim.first, olim.second)};
}
/**
* @brief Gets the tag.
*
* @param[in] physical_address The physical address
*
* @return The tag.
*/
inline auto get_tag(unsigned long long physical_address) {
return extract_bit_range(physical_address, tlim.first, tlim.second);
}
/**
* @brief Gets the set.
*
* @param[in] physical_address The physical address
*
* @return The set.
*/
inline auto get_set(unsigned long long physical_address) {
return extract_bit_range(physical_address, slim.first, slim.second);
}
/**
* @brief Gets the offset.
*
* @param[in] physical_address The physical address
*
* @return The offset.
*/
inline auto get_offset(unsigned long long physical_address) {
return extract_bit_range(physical_address, olim.first, olim.second);
}
};
} // namespace exot::utilities
<file_sep>/include/exot/framework/connect.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file framework/connect.h
* @author <NAME>
* @brief Facilities for connecting process network nodes together.
*/
#pragma once
#include <stdexcept> // for throwing
#include <tuple> // for packing into tuples and forward_as_tuple
#include <type_traits> // for is_base_of_v
#include <exot/framework/node.h> // for node types
#include <exot/utilities/helpers.h> // for const_for
#include <exot/utilities/types.h> // for node type traits
namespace exot::framework {
/**
* @brief Functor that connects compatible nodes together
* @details The simple connect functions were factored into the Connector
* functor to allow defining the desired capacity of the created
* container interfaces.
*
* If capacity of 0 is used, the default container constructor is
* used.
*/
class Connector {
private:
const size_t capacity_;
public:
/**
* @brief Constructs the object with desired capacity.
*
* @param[in] capacity The deriser capacity
*/
constexpr Connector(size_t capacity) : capacity_{capacity} {};
/**
* @brief Constructs the object with the default capacity.
*/
constexpr Connector() : Connector{0} {};
/**
* @brief Connects a valid set of nodes in a pipeline
* @details { detailed_item_description }
*
* @param[in] nodes The nodes to connect together
*
* @tparam Nodes The types of nodes
*/
template <typename... Nodes>
void pipeline(Nodes&&... nodes) {
/**
* It does not make sense to connect less than 2 nodes.
*/
static_assert(sizeof...(nodes) >= 2,
"At least two nodes are required to make a pipeline");
/* Make sure, at compile time, that all node objects inherit from base node
* class. */
static_assert(
(std::is_base_of_v<exot::framework::Node, std::decay_t<Nodes>> && ...),
"All arguments must be compatible nodes.");
/* Since it is not possible to simply iterate over a template parameter
* pack, for convienience a tuple is created, and then accessed through the
* const-for-loop. */
auto tuple = std::forward_as_tuple(std::forward<Nodes>(nodes)...);
/* A valid pipeline has to have a producer and a consumer at the opposite
* edges. */
static_assert(exot::utilities::is_producer_v<decltype(std::get<0>(tuple))>,
"First node has to be a producer.");
static_assert(exot::utilities::is_consumer_v<decltype(
std::get<sizeof...(nodes) - 1>(tuple))>,
"Last node has to be a consumer.");
/* 'Loop' through nodes and call the pair-wise `connect()` function. */
exot::utilities::const_for<0, sizeof...(nodes) - 1>([&](auto I) {
connect_((std::get<I>(tuple)), (std::get<I + 1>(tuple)));
});
}
/**
* @brief Perfect forwarding wrapper for internal `connect_` function
*/
template <typename Left, typename Right>
void connect(Left&& left, Right&& right) {
connect_(std::forward<Left>(left), std::forward<Right>(right));
}
/**
* @brief A variadic connector wrapper, which doesn't validate the
* pipeline
*
* @param left The first node to connect
* @param right The second node to connect
* @param rest The other nodes
*
* @tparam Left The type of the first node
* @tparam Right The type of the second node
* @tparam Rest The types of the other nodes
*/
template <typename Left, typename Right, typename... Rest>
void connect(Left&& left, Right&& right, Rest&&... rest) {
connect_(std::forward<Left>(left), right);
connect(std::forward<Right>(right), std::forward<Rest>(rest)...);
}
private:
/**
* @brief Connects two compatible nodes together.
* @details Also serves as the base case for the recursive-like call to
* `connect` through the other template function.
*
* @param left The node providing an output interface
* @param right The node providing an input interface
*
* @tparam Left The type of the left node
* @tparam Right The type of the right node
*/
template <typename Left, typename Right>
void connect_(Left& left, Right& right) {
static_assert(exot::utilities::has_output_interface_v<Left>,
"Left operand needs to have an output interface defined");
static_assert(exot::utilities::has_input_interface_v<Right>,
"Right operand needs to have an input interface defined");
static_assert(
std::is_same_v<
typename Left::producer_type::interface_type::value_type,
typename Right::consumer_type::interface_type::value_type>,
"The value types of Left and Right nodes have to match");
using container_type =
typename Left::producer_type::interface_type::container_type;
static_assert(
std::is_same_v<
container_type,
typename Right::consumer_type::interface_type::container_type>,
"The container types of Left and Right nodes have to match");
std::shared_ptr<container_type> container_pointer;
/* Create the communication interface/container, but do not keep the
* original pointer/reference. */
if (capacity_ != 0) {
container_pointer = std::make_shared<container_type>(capacity_);
} else {
container_pointer = std::make_shared<container_type>();
}
/* Set output and input containers for left and right nodes. */
left.set_output(container_pointer);
right.set_input(container_pointer);
/* Make sure that both interfaces can access the same container. */
if (left.get_output() != right.get_input())
throw std::logic_error(
"Output and input interfaces point to a different container/channel");
};
};
namespace details {
template <typename Left, typename Right>
void connect(Left& left, Right& right) {
static_assert(exot::utilities::has_output_interface_v<Left>,
"Left operand needs to have an output interface defined");
static_assert(exot::utilities::has_input_interface_v<Right>,
"Right operand needs to have an input interface defined");
static_assert(
std::is_same_v<typename Left::producer_type::interface_type::value_type,
typename Right::consumer_type::interface_type::value_type>,
"The value types of Left and Right nodes have to match");
using container_type =
typename Left::producer_type::interface_type::contaitner_type;
static_assert(
std::is_same_v<
container_type,
typename Right::consumer_type::interface_type::container_type>,
"The container types of Left and Right nodes have to match");
/* Create the communication interface/container, but do not keep the original
* pointer/reference. */
auto container_pointer = std::make_shared<container_type>();
/* Set output and input containers for left and right nodes. */
left.set_output(container_pointer);
right.set_input(container_pointer);
/* Make sure that both interfaces can access the same container. */
if (left.get_output() != right.get_input())
throw std::logic_error(
"Output and input interfaces point to a different container/channel");
};
} // namespace details
/**
* @brief A free-standing variant of the node-connecting function
* @details Performs basic validation of passed arguments, makes sure that
* the left node has an output, and the right node has an input, an
* that they use the same value types and interface container types.
*
* This free-standing function `connect` uses the default container
* size.
*
* @param left The left node
* @param right The right node
*
* @tparam Left The type of the left node
* @tparam Right The type of the right node
*/
template <typename Left, typename Right>
void connect(Left&& left, Right&& right) {
details::connect(std::forward<Left>(left), std::forward<Right>(right));
}
/**
* @brief A variadic function wrapper to create a sequence of calls to
* `connect` via template parameter pack expansion
*
* @param left The first node to connect
* @param right The second node to connect
* @param rest The other nodes
*
* @tparam Left The type of the first node
* @tparam Right The type of the second node
* @tparam Rest The types of the other nodes
*/
template <typename Left, typename Right, typename... Rest>
void connect(Left&& left, Right&& right, Rest&&... rest) {
connect(std::forward<Left>(left), right);
connect(std::forward<Right>(right), std::forward<Rest>(rest)...);
};
} // namespace exot::framework
<file_sep>/include/exot/utilities/timing_source.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/timing_source.h
* @author <NAME>
* @brief Single point configuration for special timing facilities.
*/
#pragma once
#include <chrono>
#include <exot/primitives/fenced_clock.h>
#include <exot/primitives/monotonic_clock.h>
#include <exot/primitives/perf_clock.h>
#include <exot/primitives/tsc.h>
#include <exot/utilities/timing.h>
namespace exot::utilities {
/**
* @brief Enumeration for timing serialisation type
*/
enum class TimingFenceType : unsigned char {
Atomic = 0,
Weak = 1,
Strong = 2,
None = 3,
};
/**
* @brief Enumeration for timing source
*/
enum class TimingSourceType : unsigned char {
SteadyClock = 0, // std::steady_clock
MonotonicCounter = 1, // MonotonicCounter
MonotonicClock = 2, // monotonic_clock
TimeStampCounter = 3, // SimpleTSC
HardwarePerformanceCounter = 4, // perf using PERF_COUNT_HW_CPU_CYCLES
SoftwarePerformanceCounter = 5, // perf using PERF_COUNT_SW_CPU_CYCLES
};
#if !defined(EXOT_TIME_FENCE)
#define EXOT_TIME_FENCE 0 //! Defines the default serialisation type
#endif
#if !defined(EXOT_TIME_SOURCE)
#define EXOT_TIME_SOURCE 0 //! Defines the default timing source
#endif
// clang-format off
#ifndef CONFIGURATION_MESSAGE_PRINTED
#define CONFIGURATION_MESSAGE_PRINTED
#if EXOT_TIME_FENCE == 0
#pragma message "EXOT_TIME_FENCE: Chose TimingFenceType::Atomic"
#elif EXOT_TIME_FENCE == 1
#pragma message "EXOT_TIME_FENCE: Chose TimingFenceType::Weak"
#elif EXOT_TIME_FENCE == 2
#pragma message "EXOT_TIME_FENCE: Chose TimingFenceType::Strong"
#elif EXOT_TIME_FENCE == 3
#pragma message "EXOT_TIME_FENCE: Chose TimingFenceType::None"
#else
#error "EXOT_TIME_FENCE has no or wrong value!"
#endif
#if EXOT_TIME_SOURCE == 0
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::SteadyClock"
#elif EXOT_TIME_SOURCE == 1
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::MonotonicCounter"
#elif EXOT_TIME_SOURCE == 2
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::MonotonicClock"
#elif EXOT_TIME_SOURCE == 3
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::TimeStampCounter"
#elif EXOT_TIME_SOURCE == 4
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::HardwarePerformanceCounter"
#elif EXOT_TIME_SOURCE == 5
#pragma message "EXOT_TIME_SOURCE: Chose TimingSourceType::SoftwarePerformanceCounter"
#else
#error "EXOT_TIME_SOURCE has no or wrong value!"
#endif
#endif
// clang-format on
/**
* @brief The default serialisation type
*/
inline constexpr TimingFenceType EXOT_TIME_FENCE_TYPE =
static_cast<TimingFenceType>(EXOT_TIME_FENCE);
/**
* @brief The default timing source type
*/
inline constexpr TimingSourceType EXOT_TIME_SOURCE_TYPE =
static_cast<TimingSourceType>(EXOT_TIME_SOURCE);
/**
* @brief The serialised time source
*
* @tparam T A clock or counter type
* @tparam Fence The serialisation type
* @tparam <unnamed> Template helper
*/
template <typename T, TimingFenceType Fence, typename = void>
struct serialised_time_source_t;
template <typename Clock>
struct serialised_time_source_t<
Clock, TimingFenceType::Atomic,
std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
: public exot::primitives::fenced_clock<Clock> {};
template <typename Clock>
struct serialised_time_source_t<
Clock, TimingFenceType::Weak,
std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
: public exot::primitives::__fenced_clock<Clock> {};
template <typename Clock>
struct serialised_time_source_t<
Clock, TimingFenceType::Strong,
std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
: public exot::primitives::__strong_fenced_clock<Clock> {};
template <typename Clock>
struct serialised_time_source_t<
Clock, TimingFenceType::None,
std::enable_if_t<exot::utilities::is_clock_v<Clock>>>
: public exot::primitives::plain_clock<Clock> {};
template <typename Counter>
struct serialised_time_source_t<
Counter, TimingFenceType::Atomic,
std::enable_if_t<exot::primitives::is_time_stamp_counter_v<Counter>>>
: public exot::primitives::fenced_tsc<Counter> {};
template <typename Counter>
struct serialised_time_source_t<
Counter, TimingFenceType::Weak,
std::enable_if_t<exot::primitives::is_time_stamp_counter_v<Counter>>>
: public exot::primitives::__fenced_tsc<Counter> {};
template <typename Counter>
struct serialised_time_source_t<
Counter, TimingFenceType::Strong,
std::enable_if_t<exot::primitives::is_time_stamp_counter_v<Counter>>>
: public exot::primitives::__strong_fenced_tsc<Counter> {};
template <typename Counter>
struct serialised_time_source_t<
Counter, TimingFenceType::None,
std::enable_if_t<exot::primitives::is_time_stamp_counter_v<Counter>>>
: public exot::primitives::plain_tsc<Counter> {};
/**
* @brief The time source type, a clock or a counter
*
* @tparam Source The timing source type
*/
template <TimingSourceType Source>
struct time_source_t;
template <>
struct time_source_t<TimingSourceType::SteadyClock>
: public std::chrono::steady_clock {};
template <>
struct time_source_t<TimingSourceType::MonotonicCounter>
: public exot::primitives::MonotonicCounter {};
template <>
struct time_source_t<TimingSourceType::MonotonicClock>
: public exot::primitives::monotonic_clock {};
#if defined(__x86_64__)
template <>
struct time_source_t<TimingSourceType::TimeStampCounter>
: public exot::primitives::SimpleTSC {};
#endif
template <>
struct time_source_t<TimingSourceType::HardwarePerformanceCounter>
: public exot::primitives::perf_clock {};
template <>
struct time_source_t<TimingSourceType::SoftwarePerformanceCounter>
: public exot::primitives::perf_sw_clock {};
/**
* @brief The default time source
*/
using default_time_source = time_source_t<EXOT_TIME_SOURCE_TYPE>;
/**
* @brief The default serialised time source
*/
using default_serialised_time_source =
serialised_time_source_t<default_time_source, EXOT_TIME_FENCE_TYPE>;
/**
* @brief The default timeing facility
* @note Wrapper of the "timeit" utility defined in
* <exot/utilities/timing.h>
*
* @tparam Args The forwarded arguments types
* @param args The forwarded arguments
*
* @return The time measurement output in clock-specific type
*/
template <typename... Args>
inline auto default_timing_facility(Args&&... args) {
if constexpr (exot::primitives::is_time_stamp_counter_v<
typename default_serialised_time_source::
underlying_timing_source>) {
return timeit<default_serialised_time_source>(std::forward<Args>(args)...);
} else {
return timeit<default_serialised_time_source>(std::forward<Args>(args)...)
.count();
}
}
} // namespace exot::utilities<file_sep>/src/meters/frequency_sysfs.cpp
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/frequency_sysfs.cpp
* @author <NAME>
* @brief Implementation of the sysfs frequency metering module.
*/
#include <exot/meters/frequency_sysfs.h>
#include <algorithm> // for sort, unique
#include <numeric> // for iota, set_difference
#include <fmt/format.h> // for formatting strings
#include <fmt/ostream.h> // for ostream support
#include <exot/utilities/configuration.h> // for bootstrap_cores
#include <exot/utilities/filesystem.h> // for grep_directory_r
#include <exot/utilities/formatting.h> // for extract_number
#include <exot/utilities/ostream.h> // for ostream operator overloads
using namespace exot::modules;
frequency_sysfs::frequency_sysfs(settings& conf) : conf_{conf} {
std::string dir{"/sys/devices/system/cpu"}; //! the directory where cpufreq
//! file nodes are found
/* Since sysfs cpufreq nodes are usually placed as symbolic directory links
* (and refer to "/cpufreq/policy*", we only check for the trailing number
* and source specifier, and tell `grep_directory_r` to follow symlinks. */
std::string regex = fmt::format(".*cpufreq/.*\\d+/{}", conf_.source);
/* If no cores were provided, perform an autodiscovery of available frequency
* domains, by searching for cpufreq endpoints. */
filenames_ = exot::utilities::grep_directory_r(
dir, regex, exot::utilities::Symlinks::Follow);
/* If none were found, fall back to the cpu/cpu* directory listing. */
if (filenames_.size() == 0) {
debug_log_->warn(
"[frequency_sysfs] automatic detection of cpufreq endpoints failed, "
"falling back to \"cpu*\" directory discovery");
/* Get /sys/devices/system/cpu/cpu* directories */
auto cpu_dirs =
exot::utilities::grep_directory(dir, std::string{".*/cpu\\d+$"});
std::sort(cpu_dirs.begin(), cpu_dirs.end());
debug_log_->debug("[frequency_sysfs] found {} cpu* directories",
cpu_dirs.size());
/* construct the full file paths */
for (const auto& cpu_dir : cpu_dirs) {
filenames_.push_back(fmt::format("{}/cpufreq/{}", cpu_dir, conf_.source));
}
/* remove paths that are not readable */
auto removed = exot::utilities::remove_unreadable(filenames_);
if (filenames_.empty()) {
debug_log_->critical(
"[frequency_sysfs] no cpufreq endpoints are available/accessible");
throw std::logic_error(
fmt::format("No cpufreq endpoints are available/accessible."));
}
for (const auto& el : removed) {
debug_log_->trace(
"[frequency_sysfs] did not find a cpufreq endpoint for core {}",
exot::utilities::extract_number(el));
}
} else {
debug_log_->debug("[frequency_sysfs] found {} cpufreq endpoints",
filenames_.size());
}
std::sort(filenames_.begin(), filenames_.end());
/* Extract the core numbers from the file paths to obtain the available range
* of cores. */
std::vector<unsigned> available_cores;
for (const auto& filename : filenames_) {
debug_log_->trace("[frequency_sysfs] extracted core {} from {}",
exot::utilities::extract_number(filename), filename);
available_cores.push_back(exot::utilities::extract_number(filename));
}
/*If cores were provided in the settings structure... */
if (!conf_.cores.empty()) {
/* Bootstrap the cores vector and make sure that the provided cores
* do not exceed hardware concurrency. */
exot::utilities::bootstrap_cores(conf_.cores);
/* Compute the set intersection 'available_cores ∩ conf_.cores'.
*
* TODO: The following procedures might be suitable candidates for
* encapsulation. */
std::vector<unsigned> intersection;
std::set_intersection(available_cores.begin(), available_cores.end(),
conf_.cores.begin(), conf_.cores.end(),
std::back_inserter(intersection));
/* If conf_.cores and the intersection are not the same, then some of the
* supplied values are outside of the avaliable range.
*/
if (conf_.cores != intersection) {
/* Compute 'conf_.cores \ available_cores' to get which cores lie outside
* of the accessible range of cpufreq endpoints.
*/
std::vector<unsigned> difference;
std::set_difference(conf_.cores.begin(), conf_.cores.end(),
available_cores.begin(), available_cores.end(),
std::back_inserter(difference));
debug_log_->critical(
"[frequency_sysfs] supplied cores {} are not available", difference);
if (conf_.strict) {
throw std::logic_error(
fmt::format("Supplied cores {} are not available", difference));
}
/* Limit the cores to the accessible range. */
conf_.cores = intersection;
}
/* If the set of cores is a proper subset of the available cores, remove the
* positions which are not necessary. */
if (conf_.cores != available_cores) {
filenames_.erase(
std::remove_if(filenames_.begin(), filenames_.end(),
[&](const auto& el) -> bool {
unsigned core{exot::utilities::extract_number(el)};
return std::find(intersection.begin(),
intersection.end(),
core) == intersection.end();
}),
filenames_.end());
}
} else {
/* ...otherwise set the cores to the available range. */
conf_.cores = available_cores;
}
debug_log_->info("[frequency_sysfs] using source: {}, cores: {}",
conf_.source, conf_.cores);
debug_log_->debug("[frequency_sysfs] using endpoints: {}", filenames_);
readings_.resize(filenames_.size());
/* Make sure that all specified files are readable. */
if (!exot::utilities::all_readable(filenames_)) {
debug_log_->critical(
"[frequency_sysfs] at least one of cpufreq's are not readable.");
throw std::logic_error(
fmt::format("At least one of cpufreq's in not readable."));
}
}
typename frequency_sysfs::return_type frequency_sysfs::measure() {
for (decltype(filenames_.size()) i = 0; i < filenames_.size(); ++i) {
std::ifstream cpufreq(filenames_.at(i));
cpufreq >> readings_.at(i);
cpufreq.close();
}
return readings_;
}
std::vector<std::string> frequency_sysfs::header() {
std::vector<std::string> descriptions;
for (auto core : conf_.cores) {
descriptions.push_back(exot::utilities::generate_header(
conf_.name(), conf_.source, core, DefaultUnits::frequency));
}
return descriptions;
}
<file_sep>/include/exot/meters/frequency_sysfs.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file meters/frequency_sysfs.h
* @author <NAME>
* @brief Frequency meter logging values provided in sysfs' cpufreq
* endpoints.
*/
#pragma once
#if defined(__linux__)
#include <memory> // for std::shared_ptr
#include <string> // for std::string
#include <vector> // for variable-size arrays
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <exot/meters/base.h>
#include <exot/utilities/configuration.h> // for configurable
namespace exot::modules {
struct frequency_sysfs : module {
using return_type = std::vector<unsigned int>;
/**
* @brief Settings supported by the module
*/
struct settings : public exot::utilities::configurable<settings> {
bool strict{true};
std::vector<unsigned> cores; //! vector of cores
std::string source{
"scaling_cur_freq"}; //! use scaling_* or cpuinfo_cur_freq
const char* name() const { return "frequency_sysfs"; }
/* @brief The JSON configuration function */
void configure() {
bind_and_describe_data(
"cores", cores,
"cores to measure frequency of |uint[]|, e.g. [0, 1, 2, 3]");
bind_and_describe_data(
"source", source,
"the sysfs frequency source |str|, \"scaling_cur_freq\" "
"(default) or \"cpuinfo_cur_freq\"");
bind_and_describe_data(
"strict", strict,
"fail if cores are unavailable? |bool|, default: true");
}
};
/**
* @brief Constructs the meter module
*
* @param conf The module settings structure
*/
explicit frequency_sysfs(settings& conf);
/**
* @brief Perform measurement
*
* @return A vector with frequency readings
*/
return_type measure();
/**
* @brief Get descriptions of return values
* @details The descriptions contain variable names and units
*
* @return A vector with descriptions
*/
std::vector<std::string> header();
private:
settings conf_;
std::vector<std::string> filenames_;
return_type readings_;
using logger_pointer = std::shared_ptr<spdlog::logger>;
logger_pointer debug_log_ =
spdlog::get("log") ? spdlog::get("log") : spdlog::stderr_color_mt("log");
};
} // namespace exot::modules
#endif
<file_sep>/include/exot/utilities/cli.h
// Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
//
/**
* @file utilities/cli.h
* @author <NAME>
* @brief Command line parsing facilities.
*/
#pragma once
#include <fstream>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <clipp.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <nlohmann/json.hpp>
#include <exot/utilities/configuration.h>
#include <exot/utilities/filesystem.h>
#include <exot/utilities/formatting.h>
/**
* DEBUG_CLI enables more descriptive printing of parsing errors
*/
#ifndef DEBUG
#define DEBUG_CLI false
#else
#define DEBUG_CLI true
#endif
namespace exot::utilities {
class JsonConfig {
public:
clipp::group get_cli_configuration();
nlohmann::json get() const;
nlohmann::json::reference get_ref();
nlohmann::json::const_reference get_const_ref() const;
std::string get_filename_or_data() const;
void set_with_file(const char* file);
void set_with_file(const std::string& file);
void set_with_file(std::string&& file);
void set_with_string(const char* string);
void set_with_string(const std::string& string);
void set_with_string(std::string&& string);
private:
void ingest(bool using_a_file);
std::string json_file_or_data_;
bool using_a_file_{false};
nlohmann::json root_json_;
};
/* Template specialisations to make the configuration syntax more compact. */
/**
* @brief Sets the JSON file in multiple configurables
*
* @param[in] config The JsonConfig object
* @param[in] ts The configurables
*
* @tparam Ts The types of the configurables
*/
template <typename... Ts>
inline void set_json(const JsonConfig& config, Ts&&... ts) {
(..., ts.set_json(config.get_const_ref()));
}
/**
* @brief Sets the JSON file in multiple configurables and configures them
*
* @param[in] config The JsonConfig object
* @param[in] ts The configurables
*
* @tparam Ts The types of the configurables
*/
template <typename... Ts>
inline void configure(const JsonConfig& config, Ts&&... ts) {
set_json(config.get_const_ref(), ts...);
only_configure(ts...);
}
/**
* @brief Class providing the command line interface
*/
class CLI {
public:
/**
* @brief Adds multiple configurations to the interface
*
* @param[in] config The individual configuration group
*
* @tparam Configs Configuration groups
*/
template <typename... Configs>
void add_configurations(const Configs&... config) {
(..., base_.push_front(config));
}
/**
* @brief Prepends a section to the help message
*
* @param[in] title The title
* @param[in] content The content
*/
void prepend_section(const std::string& title, const std::string& content);
/**
* @brief Appends a section to the help message
*
* @param[in] title The title
* @param[in] content The content
*/
void append_section(const std::string& title, const std::string& content);
/**
* @brief Adds a description section to the help message
*
* @param[in] description The description
*/
void add_description(const std::string& description);
/**
* @brief Adds an example section to the help message
*
* @param[in] example The example
*/
void add_example(const std::string& example);
/**
* @brief Parses the command line arguments
*
* @param[in] argc The argc from main
* @param argv The argv from main
*
* @return True if successful, false if parsing error occurred
*/
bool parse(int argc, char** argv);
template <typename... Ts>
void collect_descriptions(Ts&&... ts) {
auto descriptions = std::string{};
(..., descriptions.append(ts.describe()));
sections_to_append_.emplace_back("CONFIGURATION",
indent(descriptions, 8, false));
}
private:
using section = clipp::man_page::section;
clipp::group base_{}; //! base configuration group
std::vector<section> sections_to_prepend_;
std::vector<section> sections_to_append_;
const bool debug_{DEBUG_CLI};
};
} // namespace exot::utilities
|
ec585299e0ffc34e9f99bcc5be3f485c66c6820d
|
[
"Markdown",
"CMake",
"C++"
] | 98
|
C++
|
ETHZ-TEC/exot_app_lib
|
7330c2db9ea6da33b7532af9c3049f8b673dd117
|
3958b938a2e80ee2e501e7099e57e18833047237
|
refs/heads/master
|
<file_sep><?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Bygma reports
*
* @package report
* @subpackage bygma
*/
require('../../config.php');
require_once($CFG->libdir . '/completionlib.php');
require_once("{$CFG->libdir}/gradelib.php");
require_once("{$CFG->dirroot}/report/bygma/lib/itk_completionlib.php");
define('COMPLETION_REPORT_PAGE', 25);
// Get course
$id = required_param('course',PARAM_INT);
$course = $DB->get_record('course',array('id'=>$id));
if (!$course) {
print_error('invalidcourseid');
}
$context = context_course::instance($course->id);
// Sort (default lastname, optionally firstname)
$sort = optional_param('sort','',PARAM_ALPHA);
$firstnamesort = $sort == 'firstname';
// CSV format
$format = optional_param('format','',PARAM_ALPHA);
$excel = $format == 'excelcsv';
$csv = $format == 'csv' || $excel;
// Paging
$start = optional_param('start', 0, PARAM_INT);
$sifirst = optional_param('sifirst', 'all', PARAM_NOTAGS);
$silast = optional_param('silast', 'all', PARAM_NOTAGS);
$start = optional_param('start', 0, PARAM_INT);
// Whether to show extra user identity information
$extrafields = get_extra_user_fields($context);
$leftcols = 1 + count($extrafields);
function csv_quote($value) {
global $excel;
if ($excel) {
return core_text::convert('"'.str_replace('"',"'",$value).'"','UTF-8','UTF-16LE');
} else {
return '"'.str_replace('"',"'",$value).'"';
}
}
$url = new moodle_url('/report/bygma/index.php', array('course'=>$id));
if ($sort !== '') {
$url->param('sort', $sort);
}
if ($format !== '') {
$url->param('format', $format);
}
if ($start !== 0) {
$url->param('start', $start);
}
$PAGE->set_url($url);
$PAGE->set_pagelayout('report');
require_login($course);
// Check basic permission
require_capability('report/bygma:view',$context);
// Get group mode
$group = groups_get_course_group($course,true); // Supposed to verify group
if ($group===0 && $course->groupmode==SEPARATEGROUPS) {
require_capability('moodle/site:accessallgroups',$context);
}
// Get data on activities and progress of all users, and give error if we've
// nothing to display (no users or no activities)
$reportsurl = $CFG->wwwroot.'/course/report.php?id='.$course->id;
$completion = new itk_completion_lib($course);
$activities = $completion->get_activities();
// Generate where clause
$where = array();
$where_params = array();
if ($sifirst !== 'all') {
$where[] = $DB->sql_like('u.firstname', ':sifirst', false);
$where_params['sifirst'] = $sifirst.'%';
}
if ($silast !== 'all') {
$where[] = $DB->sql_like('u.lastname', ':silast', false);
$where_params['silast'] = $silast.'%';
}
// Get user match count
$total = $completion->get_num_tracked_users(implode(' AND ', $where), $where_params, $group);
// Total user count
$grandtotal = $completion->get_num_tracked_users('', array(), $group);
// Get user data
$progress = array();
if ($total) {
$progress = $completion->get_progress_all(
implode(' AND ', $where),
$where_params,
$group,
$firstnamesort ? 'u.firstname ASC' : 'u.lastname ASC',
$csv ? 0 : COMPLETION_REPORT_PAGE,
$csv ? 0 : $start,
$context
);
}
if ($csv && $grandtotal && count($activities)>0) { // Only show CSV if there are some users/actvs
$shortname = format_string($course->shortname, true, array('context' => $context));
header('Content-Disposition: attachment; filename=progress.'.
preg_replace('/[^a-z0-9-]/','_',core_text::strtolower(strip_tags($shortname))).'.csv');
// Unicode byte-order mark for Excel
if ($excel) {
header('Content-Type: text/csv; charset=UTF-16LE');
print chr(0xFF).chr(0xFE);
$sep="\t".chr(0);
$line="\n".chr(0);
} else {
header('Content-Type: text/csv; charset=UTF-8');
$sep=",";
$line="\n";
}
} else {
// Navigation and header
$strreports = get_string("reports");
$strcompletion = get_string('activitycompletion', 'completion');
$PAGE->set_title($strcompletion);
$PAGE->set_heading($course->fullname);
echo $OUTPUT->header();
$PAGE->requires->js('/report/bygma/textrotate.js');
$PAGE->requires->js_function_call('textrotate_init', null, true);
// Handle groups (if enabled)
groups_print_course_menu($course,$CFG->wwwroot.'/report/bygma/?course='.$course->id);
}
if (count($activities)==0) {
echo $OUTPUT->container(get_string('err_noactivities', 'completion'), 'errorbox errorboxcontent');
echo $OUTPUT->footer();
exit;
}
// If no users in this course what-so-ever
if (!$grandtotal) {
echo $OUTPUT->container(get_string('err_nousers', 'completion'), 'errorbox errorboxcontent');
echo $OUTPUT->footer();
exit;
}
// Build link for paging
$link = $CFG->wwwroot.'/report/bygma/?course='.$course->id;
if (strlen($sort)) {
$link .= '&sort='.$sort;
}
$link .= '&start=';
$pagingbar = '';
// Do we need a paging bar?
if ($total > COMPLETION_REPORT_PAGE) {
// Paging bar
$pagingbar .= '<div class="paging">';
$pagingbar .= get_string('page').': ';
$sistrings = array();
if ($sifirst != 'all') {
$sistrings[] = "sifirst={$sifirst}";
}
if ($silast != 'all') {
$sistrings[] = "silast={$silast}";
}
$sistring = !empty($sistrings) ? '&'.implode('&', $sistrings) : '';
// Display previous link
if ($start > 0) {
$pstart = max($start - COMPLETION_REPORT_PAGE, 0);
$pagingbar .= "(<a class=\"previous\" href=\"{$link}{$pstart}{$sistring}\">".get_string('previous').'</a>) ';
}
// Create page links
$curstart = 0;
$curpage = 0;
while ($curstart < $total) {
$curpage++;
if ($curstart == $start) {
$pagingbar .= ' '.$curpage.' ';
} else {
$pagingbar .= " <a href=\"{$link}{$curstart}{$sistring}\">$curpage</a> ";
}
$curstart += COMPLETION_REPORT_PAGE;
}
// Display next link
$nstart = $start + COMPLETION_REPORT_PAGE;
if ($nstart < $total) {
$pagingbar .= " (<a class=\"next\" href=\"{$link}{$nstart}{$sistring}\">".get_string('next').'</a>)';
}
$pagingbar .= '</div>';
}
// Okay, let's draw the table of progress info,
$total_completed = $DB->get_record_sql('SELECT count(DISTINCT cmc.userid) as count_completed
FROM {course_modules} cm
INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
WHERE cm.course = :courseid AND cmc.completionstate = :completionstate', array('courseid' => $course->id, 'completionstate' => 1));
$average_grade = $DB->get_record_sql("SELECT ROUND(SUM(gg.rawgrade) / SUM(gi.grademax) * 100, 0) as average
FROM {grade_items} gi JOIN {grade_grades} gg ON gg.itemid = gi.id
WHERE courseid = :courseid AND gi.itemtype = :itemtype", array('courseid' => $course->id, 'itemtype' => 'mod'));
print html_writer::start_tag('table', array('class' => 'table-aggregation generaltable flexible boxaligncenter'));
print html_writer::start_tag('tr');
print html_writer::tag('th', get_string('table_aggregation_total_users', 'report_bygma'), array('class' => 'completion-identifyfield'));
print html_writer::tag('td', $grandtotal);
print html_writer::end_tag('tr');
print html_writer::start_tag('tr');
print html_writer::tag('th', get_string('table_aggregation_users_passed', 'report_bygma'), array('class' => 'completion-identifyfield'));
print html_writer::tag('td', $total_completed->count_completed, array('class' => 'completion-progresscell'));
print html_writer::end_tag('tr');
print html_writer::start_tag('tr');
print html_writer::tag('th', get_string('table_aggregation_passed_percentage', 'report_bygma'), array('class' => 'completion-identifyfield'));
print html_writer::tag('td', (round($total_completed->count_completed / $grandtotal * 100)) . '%', array('class' => 'completion-progresscell'));
print html_writer::end_tag('tr');
print html_writer::start_tag('tr');
print html_writer::tag('th', get_string('table_aggregation_average_grade', 'report_bygma'), array('class' => 'completion-identifyfield'));
print html_writer::tag('td', "{$average_grade->average}%", array('class' => 'completion-progresscell'));
print html_writer::end_tag('tr');
print html_writer::end_tag('table');
// Start of table
if (!$csv) {
print '<br class="clearer"/>'; // ugh
print $pagingbar;
if (!$total) {
echo $OUTPUT->heading(get_string('nothingtodisplay'));
echo $OUTPUT->footer();
exit;
}
print '<div id="completion-progress-wrapper" class="no-overflow">';
print '<table id="completion-progress" class="generaltable flexible boxaligncenter" style="text-align:left"><thead><tr style="vertical-align:top">';
//User initials header
print html_writer::tag('th', get_string('table_header_initials', 'report_bygma'), array('class' => 'completion-identifyfield', 'scope' => 'col'));
// User heading / sort option
print '<th scope="col" class="completion-sortchoice">';
$sistring = "&silast={$silast}&sifirst={$sifirst}";
if ($firstnamesort) {
print
get_string('firstname')." / <a href=\"./?course={$course->id}{$sistring}\">".
get_string('lastname').'</a>';
} else {
print "<a href=\"./?course={$course->id}&sort=firstname{$sistring}\">".
get_string('firstname').'</a> / '.
get_string('lastname');
}
print '</th>';
//Department
print html_writer::tag('th', get_string('table_header_department', 'report_bygma'), array('class' => 'completion-identifyfield', 'scope' => 'col'));
} else {
foreach ($extrafields as $field) {
echo $sep . csv_quote(get_user_field_name($field));
}
}
//Passed Header
print html_writer::tag('th', get_string('table_header_passed', 'report_bygma'), array('class' => 'completion-identifyfield', 'scope' => 'col'));
//Grade Header
print html_writer::tag('th', get_string('table_aggregation_passed_percentage', 'report_bygma'), array('class' => 'completion-identifyfield', 'scope' => 'col'));
if ($csv) {
print $line;
} else {
print '</tr></thead><tbody>';
}
$modules_info = array();
foreach($activities as $activity){
$grading_info = grade_get_grades($course->id, 'mod', $activity->modname, $activity->instance, array_keys($progress));
if(!array_key_exists($activity->modname, $modules_info)){
$modules_info[$activity->modname] = array();
}
if(!array_key_exists($activity->instance, $modules_info[$activity->modname])){
$modules_info[$activity->modname][$activity->instance] = $grading_info;
}
}
// Row for each user
foreach($progress as $user) {
print html_writer::start_tag('tr');
//User initials - have to be extracted from the email field since Bygma's ADFS does not hold initials elsewhere
$mail_split = explode('@', $user->email);
print html_writer::tag('td', $mail_split[0], array('class' => 'completion-progresscell'));
// User name
if ($csv) {
print csv_quote(fullname($user));
foreach ($extrafields as $field) {
echo $sep . csv_quote($user->{$field});
}
} else {
print '<th scope="row"><a href="'.$CFG->wwwroot.'/user/view.php?id='.
$user->id.'&course='.$course->id.'">'.fullname($user).'</a></th>';
}
//Department - They prefix every department with 'Bygma' - therefore strip it
$department_split = explode(' ', $user->institution);
print html_writer::tag('td', count($department_split) == 2 ? $department_split[1] : $user->institution, array('class' => 'completion-progresscell'));
$count_completed = 0;
$count_total = count($activities);
// Progress for each activity
foreach($activities as $activity) {
// Get progress information and state
if (array_key_exists($activity->id, $user->progress)) {
$thisprogress = $user->progress[$activity->id];
if ($thisprogress->completionstate == COMPLETION_COMPLETE || $thisprogress->completionstate == COMPLETION_COMPLETE_PASS) {
$count_completed++;
}
}
}
//Passed - whether user passed or not
print html_writer::tag('td', $count_completed == $count_total ? get_string('yes') : get_string('no'), array('completion-progresscell'));
//Score - proportion between incomplete and completed modules
print html_writer::tag('td', (round(($count_completed / $count_total) * 100) . '%'), array('completion-progresscell'));
if ($csv) {
print $line;
} else {
print '</tr>';
}
}
if ($csv) {
exit;
}
print '</tbody></table>';
print '</div>';
print $pagingbar;
echo $OUTPUT->footer();
<file_sep><?php
require_once("{$CFG->libdir}/completionlib.php");
class itk_completion_lib extends completion_info{
public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
$sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
global $DB;
list($enrolledsql, $params) = get_enrolled_sql(
context_course::instance($this->course_id),
'moodle/course:isincompletionreports', $groupid, true);
$allusernames = get_all_user_name_fields(true, 'u');
$sql = 'SELECT u.id, u.idnumber, u.institution, ' . $allusernames;
if ($extracontext) {
$sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
}
$sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
if ($where) {
$sql .= " AND $where";
$params = array_merge($params, $whereparams);
}
if ($sort) {
$sql .= " ORDER BY $sort";
}
return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
}
}
<file_sep><?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains functions used by the progress report
*
* @package report
* @subpackage progress
* @copyright 2009 <NAME>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* This function extends the navigation with the report items
*
* @param navigation_node $navigation The navigation node to extend
* @param stdClass $course The course to object for the report
* @param stdClass $context The context of the course
*/
function report_bygma_extend_navigation_course($navigation, $course, $context) {
global $CFG, $OUTPUT;
require_once($CFG->libdir.'/completionlib.php');
$showonnavigation = has_capability('report/bygma:view', $context);
$group = groups_get_course_group($course,true); // Supposed to verify group
if($group===0 && $course->groupmode==SEPARATEGROUPS) {
$showonnavigation = ($showonnavigation && has_capability('moodle/site:accessallgroups', $context));
}
$completion = new completion_info($course);
$showonnavigation = ($showonnavigation && $completion->is_enabled() && $completion->has_activities());
if ($showonnavigation) {
$url = new moodle_url('/report/bygma/index.php', array('course'=>$course->id));
$navigation->add(get_string('pluginname','report_bygma'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/report', ''));
}
}
/**
* Return a list of page types
* @param string $pagetype current page type
* @param stdClass $parentcontext Block's parent context
* @param stdClass $currentcontext Current context of block
* @return array
*/
function report_bygmapage_type_list($pagetype, $parentcontext, $currentcontext) {
$array = array(
'*' => get_string('page-x', 'pagetype'),
'report-*' => get_string('page-report-x', 'pagetype'),
'report-bygma-*' => get_string('page-report-progress-x', 'report_bygma'),
'report-bygma-index' => get_string('page-report-progress-index', 'report_bygma'),
);
return $array;
}
/**
* Returns percentage of course completion (float)
* @param $activities - all modules with enabled completion tracking for specific course
* @param $general_completion_info - general info about each module completion
* @param $detailed_completion_info - detailed info about module completions - especially quiz since we need to know exact percentage
*/
function resolve_completion_percentage($userid, $activities, $general_completion_info, $detailed_completion_info){
$passed = true;
$complete = 0;
$incomplete = count($activities);
foreach($activities as $activitie){
if(array_key_exists($activitie->modname, $detailed_completion_info) &&
array_key_exists($activitie->instance, $detailed_completion_info[$activitie->modname]) &&
!empty($detailed_completion_info[$activitie->modname][$activitie->instance]['items']) &&
array_key_exists($userid, $detailed_completion_info[$activitie->modname][$activitie->instance]['items'][0])){
$grade_info = $detailed_completion_info[$activitie->modname][$activitie->instance]['items'][0][$userid];
if(!empty($grade_info->grade)){
$passed = $passed && ($grade_info->grade >= $detailed_completion_info[$activitie->modname][$activitie->instance]['items'][0]->gradepass);
if($passed){
$complete++;
}
}
else{
$passed = false;
}
}
else{
// Get progress information and state
if (array_key_exists($activitie->id, $general_completion_info)) {
$thisprogress = $general_completion_info->progress[$activitie->id];
$state = $thisprogress->completionstate;
$date = userdate($thisprogress->timemodified);
} else {
$state = COMPLETION_INCOMPLETE;
$date = '';
}
}
}
}
function calculate_average_grade($modules_info, $user_count){
$grade_count = 0;
$activity_count = 0;
foreach($modules_info as $module_type){
foreach($module_type as $module_instance){
if(!empty($module_instance->items)){
$activity_count++;
$grade_max = floatval($module_instance->items[0]->grademax - $module_instance->items[0]->grademin);
foreach($module_instance->items[0]->grades as $grade_info){
if(!is_null($grade_info->grade)){
$grade_perc = $grade_max / $grade_info->grade * 100;
$grade_count += floatval($grade_perc);
}
}
}
}
}
return ($grade_count / ($user_count * $activity_count));
}
|
18611729d80da22b23597ba14222463bcd2f088b
|
[
"PHP"
] | 3
|
PHP
|
IT-Kartellet/bygma-report
|
a779f42ac547b30c2d1117fb81ff61fc53373a61
|
a2be01ed1813f0763127d89b001645e74749e23f
|
refs/heads/master
|
<repo_name>Hananov/hananov<file_sep>/app/views/orders/show.json.jbuilder
json.extract! @order, :id, :name, :adress, :emailpay_type, :created_at, :updated_at
|
0a37448c7810620575b15da0ce3dbac41478f161
|
[
"Ruby"
] | 1
|
Ruby
|
Hananov/hananov
|
d7ef54a2b67ef89bb2361b87bd0d7384fda23177
|
bd3c5c6fa4784c6a6e0113b58e137bbb17335e8b
|
refs/heads/master
|
<file_sep>//
// ContentView.swift
// Swif-T-Score
//
// Created by <NAME> on 23/04/21.
//
import SwiftUI
import CoreData
struct ContentView: View {
@State var fileContents = ""
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
entity: Tournament.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Tournament.endDate, ascending: true)
],
animation: .default)
private var items: FetchedResults<Tournament>
var body: some View {
HStack {
Text(fileContents)
Button("select File") {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
if panel.runModal() == .OK {
if let url = panel.url?.standardizedFileURL {
if let contents = try? String(contentsOf: url) {
self.fileContents = contents
}
}
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
List {
ForEach(items) { item in
Text("Item at \(item.endDate!, formatter: itemFormatter)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
private func addItem() {
withAnimation {
let newItem = Tournament(context: viewContext)
newItem.endDate = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
|
63c8833d79aec9207463b582fdff7544ba983b55
|
[
"Swift"
] | 1
|
Swift
|
stevenb-nz/Swif-T-Score
|
d22ad1e8a46aa4bf3cd07d11dd4197a31646e1df
|
6a83c247dfe6feb81f9959ca91793bd6331314d0
|
refs/heads/master
|
<file_sep>Version 0.09.x:
- SQL Window size - [ DONE ]
- Application icon and toolbar [ DONE ]
- Add Users list in the Object List [ DONE ]
Version 0.10.x:
- Loading object lists of different types by request [ DONE ]
- Run queries in separate thread [ DONE ]
- SQL Window redesign [ IN PROGRESS ]
- Retrieve first rows in the query [ IN PROGRESS ]
- Possibility to cancel query [ IN PROGRESS ]
- SQL window: make resizable result set part [ IN PROGRESS ]
- Scrolling in MDI area [ DONE ]
Version 0.11.x:
- Command Window
- Posiibility to run script in command window
- Possibility to create/delete connections
Version 0.12.x:
- Possibility to run several quesies in SQL Window - open several result tabs
- representing CLOB and BLOB values
Version 1.01.x:
- SQL export/import objects
- Mark SQL and PL/SQL keywords with different color
Version 1.02.x:
- Undo/Redo functionality
Version 1.03.x:
Version 1.04.x:
Version 1.05.x:
Version 1.06.x:
Version 1.07.x:
Version 1.08.x:
Version 1.09.x:
Version 1.10.x:
Version 1.11.x:
Version 1.12.x:
Not scheduled:
- Refresh Object Tree button and functionality
- Execution Plan Window with short cut (F5)
- Add application settings
- Cut/copy/paste/
<file_sep>#ifndef TREEDBOBJECT_H
#define TREEDBOBJECT_H
#include <QString>
enum treeType { ttType, ttObject };
class TreeDBObject
{
public:
TreeDBObject(QString treeName, treeType type, QString sqlSource, QString sqlNameCol);
QString getTreeName() {
return m_treeName;
}
treeType getType() {
return m_type;
}
QString getSQLSource() {
return m_sql_source;
}
QString getSQLNameColumn() {
return m_sql_name_column;
}
private:
QString m_treeName;
treeType m_type;
QString m_sql_source;
QString m_sql_name_column;
};
#endif // TREEDBOBJECT_H
<file_sep>#ifndef QUERYEXECUTOR_H
#define QUERYEXECUTOR_H
#include <QThread>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QDebug>
class QueryExecutor : public QThread
{
Q_OBJECT
public:
QueryExecutor(QObject *parent = 0);
~QueryExecutor();
void run();
void initializeQuery(QSqlDatabase &db, QString sql);
signals:
void pageLoaded(QList<QSqlRecord>*);
void queryFinished(bool running);
public slots:
void cancel();
private:
QSqlDatabase dbLocal;
QString sqlLocal;
int pageSize;
bool isRunning;
};
#endif // QUERYEXECUTOR_H
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sqlconnectiondialog.h"
#include <QtGui>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
initializeObjectTree();
createActions();
setTitle("Oracle Developer - (not logged in)");
db = QSqlDatabase::addDatabase("QOCI");
}
MainWindow::~MainWindow()
{
db.close();
delete ui;
}
void MainWindow::initializeObjectTree() {
treeModel = new TreeModel("Objects", ":/config/objectbrowser.xml", this);
ui->treeView->setModel(treeModel);
}
void MainWindow::createActions() {
// menu File
connect(ui->actionSQL_Window, SIGNAL(triggered()), this, SLOT(newSqlWindow()));
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(open()));
connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()));
connect(ui->actionSave_As, SIGNAL(triggered()), this, SLOT(saveAs()));
connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->actionClose_All, SIGNAL(triggered()), this, SLOT(closeAll()));
connect(ui->action_Exit, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
// menu edit
// connect(ui->action_Copy, SIGNAL(triggered()), this, SLOT(copy()));
// connect(ui->action_Paste, SIGNAL(triggered()), this, SLOT(paste()));
// connect(ui->actionC_ut, SIGNAL(triggered()), this, SLOT(cut()));
// menu Session
connect(ui->action_Log_on, SIGNAL(triggered()), this, SLOT(login()));
connect(ui->actionLog_off, SIGNAL(triggered()), this, SLOT(logoff()));
connect(ui->action_Execute, SIGNAL(triggered()), this, SLOT(execute()));
connect(ui->action_Commit, SIGNAL(triggered()), this, SLOT(commit()));
connect(ui->action_Rollback, SIGNAL(triggered()), this, SLOT(rollback()));
// menu Help
connect(ui->action_About, SIGNAL(triggered()), this, SLOT(about()));
// others
connect(ui->mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateMenus()));
connect(ui->treeView, SIGNAL(expanded(QModelIndex)), this, SLOT(itemExpanded(QModelIndex)));
}
void MainWindow::newSqlWindow() {
SQLWindow *sqlWindow = createSQLWindow();
sqlWindow->show();
}
void MainWindow::about() {
QMessageBox::about(this, tr("About Oracle Developer"), tr("<b>Oracle Developer</b> version 0.09.28<br><br>created by <NAME> (<a href='<EMAIL>'><EMAIL></a>)<br><br>Application is currently under active development<br><br>"));
}
void MainWindow::open() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Open SQL file"), "", tr("SQL (*.sql)"));
if (!fileName.isEmpty()) {
QMdiSubWindow *existing = findSQLWindow(fileName);
if (existing) {
ui->mdiArea->setActiveSubWindow(existing);
return;
}
SQLWindow *sqlWindow = createSQLWindow();
if (sqlWindow->loadFile(fileName)) {
statusBar()->showMessage(tr("File loaded"), 2000);
sqlWindow->show();
} else {
sqlWindow->close();
}
}
}
void MainWindow::save() {
if (activeSQLWindow() && activeSQLWindow()->save())
statusBar()->showMessage(tr("File saved"), 2000);
}
void MainWindow::saveAs() {
if (activeSQLWindow() && activeSQLWindow()->saveAs())
statusBar()->showMessage(tr("File saved"), 2000);
}
void MainWindow::close() {
ui->mdiArea->closeActiveSubWindow();
}
void MainWindow::closeAll() {
ui->mdiArea->closeAllSubWindows();
}
//void MainWindow::copy() {
// if (activeSQLWindow())
// activeSQLWindow()->copy();
//}
//void MainWindow::cut() {
// if (activeSQLWindow())
// activeSQLWindow()->cut();
//}
//void MainWindow::paste() {
// if (activeSQLWindow())
// activeSQLWindow()->paste();
//}
void MainWindow::login() {
SqlConnectionDialog dialog(this);
if (dialog.exec() != QDialog::Accepted)
return;
statusBar()->showMessage(tr("Connecting to DB..."), 5000);
db.setUserName(dialog.userName());
db.setPassword(dialog.password());
db.setDatabaseName(dialog.databaseName());
if (!db.open()) {
QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while connecting to DB: ") + db.lastError().text());
qDebug() << "Failed to connect to " + dialog.databaseName() + ": " + db.lastError().text();
this->setTitle("Oracle Developer - (not logged in)");
ui->actionLog_off->setEnabled(false);
statusBar()->showMessage(tr("Failed to login"), 2000);
} else {
//QMessageBox::information(this, tr("Success"), tr("Connected to ") + dialog.databaseName());
qDebug() << "Connected to " + dialog.databaseName();
this->setTitle("Oracle Developer - " + dialog.userName() + "@" + dialog.databaseName());
ui->actionLog_off->setEnabled(true);
foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList())
qobject_cast<SQLWindow *>(window->widget())->logon(db);
// add placeholders to TreeView
TreeModel *model = qobject_cast<TreeModel *>(ui->treeView->model());
model->addTreePlaceholders();
ui->treeView->collapseAll();
}
}
void MainWindow::logoff() {
foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList())
qobject_cast<SQLWindow *>(window->widget())->logoff();
this->db.close();
TreeModel *model = qobject_cast<TreeModel *>(ui->treeView->model());
model->clearTree();
ui->treeView->collapseAll();
this->setTitle("Oracle Developer - (not logged in)");
ui->actionLog_off->setEnabled(false);
statusBar()->showMessage(tr("Successfully logged off"), 2000);
}
void MainWindow::commit() {
if (activeSQLWindow())
activeSQLWindow()->commit();
}
void MainWindow::rollback() {
if (activeSQLWindow())
activeSQLWindow()->rollback();
}
void MainWindow::execute() {
if (activeSQLWindow()) {
// QFuture<void> future = QtConcurrent::run(activeSQLWindow(), &SQLWindow::execute);
// future.waitForFinished();
activeSQLWindow()->execute();
}
}
void MainWindow::updateMenus() {
bool hasMdiChild = (activeSQLWindow() != 0);
ui->actionClose->setEnabled(hasMdiChild);
ui->actionClose_All->setEnabled(hasMdiChild);
ui->actionSave->setEnabled(hasMdiChild);
ui->actionSave_As->setEnabled(hasMdiChild);
ui->action_Commit->setEnabled(hasMdiChild);
ui->action_Rollback->setEnabled(hasMdiChild);
ui->action_Execute->setEnabled(hasMdiChild);
}
SQLWindow *MainWindow::activeSQLWindow() {
if(QMdiSubWindow *activeSubWindow = ui->mdiArea->activeSubWindow())
return qobject_cast<SQLWindow *>(activeSubWindow->widget());
return 0;
}
void MainWindow::setTitle(QString newTitle) {
this->setWindowTitle(newTitle);
}
void MainWindow::refreshObjectTree(QModelIndex index, bool reload) {
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
if (db.isOpen()) {
if ((item->childCount() == 1 &&
QString::compare(item->child(0)->data(0).toString(), "NULL") == 0) || reload) {
item->clearChildren();
QString sql = item->getSql();
statusBar()->showMessage(tr("Getting object list"), 5000);
QSqlQuery query(sql, db);
while (query.next()) {
QList<QVariant> columnData;
columnData << query.value(0).toString();
TreeItem *child = new TreeItem(columnData, item);
item->appendChild(child);
}
query.clear();
emit ui->treeView->collapse(index);
emit ui->treeView->expand(index);
}
} else {
QMessageBox::information(this, "Not logged in", "Not logged in");
emit ui->treeView->collapseAll();
}
}
SQLWindow *MainWindow::createSQLWindow() {
SQLWindow *sqlWindow = new SQLWindow(this->db, this);
ui->mdiArea->addSubWindow(sqlWindow);
return sqlWindow;
}
QMdiSubWindow *MainWindow::findSQLWindow(const QString &fileName) {
QString cannonicalFilePath = QFileInfo(fileName).canonicalFilePath();
foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList()) {
SQLWindow *sqlWindow = qobject_cast<SQLWindow *>(window->widget());
if (sqlWindow->currentFile() == cannonicalFilePath)
return window;
}
return 0;
}
void MainWindow::itemExpanded(QModelIndex index) {
refreshObjectTree(index);
}
<file_sep>#include "sqlwindow.h"
#include "ui_sqlwindow.h"
#include <QMessageBox>
#include <QtGui>
int SQLWindow::sequenceNumber = 1;
SQLWindow::SQLWindow(QSqlDatabase &pDB, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SQLWindow)
{
ui->setupUi(this);
ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
windowSeq = sequenceNumber++;
curFile = tr("SQL Window %1").arg(windowSeq);
setWindowTitle(curFile + "[*]");
isUntitled = true;
this->logon(pDB);
this->executor = new QueryExecutor(this);
connect(executor, SIGNAL(pageLoaded(QList<QSqlRecord>*)), this, SLOT(updateUI(QList<QSqlRecord> *)));
connect(executor, SIGNAL(queryFinished(bool)), this, SLOT(queryFinished(bool)));
}
void SQLWindow::createActions()
{
connect(ui->tableWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayContextMenu(QPoint)));
}
void SQLWindow::closeEvent(QCloseEvent *event)
{
maybeSave();
}
SQLWindow::~SQLWindow()
{
db.close();
delete ui;
}
void SQLWindow::commit() {
if (this->db.isOpen())
db.commit();
else
statusBar()->showMessage("Not connected to Oracle");
}
void SQLWindow::rollback() {
if (this->db.isOpen())
db.rollback();
else
statusBar()->showMessage("Not connected to Oracle");
}
void SQLWindow::logoff() {
if (this->db.isOpen())
db.close();
}
void SQLWindow::logon(QSqlDatabase &pDB) {
if (pDB.isOpen()) {
db = QSqlDatabase::cloneDatabase(pDB, QString::number(windowSeq));
if (!db.open())
QMessageBox::information(this, "Info", "Failed to connect to DB");
}
}
void SQLWindow::execute() {
// clean previous results
for (int i = ui->tableWidget->rowCount() - 1; i >= 0; i--) {
ui->tableWidget->removeRow(i);
}
for (int i = ui->tableWidget->columnCount() - 1; i >= 0; i--) {
ui->tableWidget->removeColumn(i);
}
// if Oracle connection is open
if (db.isOpen()) {
statusBar()->showMessage(tr("Executing..."));
timer.restart();
db.transaction();
executor->initializeQuery(db, ui->plainTextEdit->toPlainText().replace(";", "", Qt::CaseInsensitive));
executor->start();
} else { // db.isOpen()
// DB is closed
statusBar()->showMessage("Not connected to Oracle");
}
}
bool SQLWindow::loadFile(const QString &fileName) {
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot read file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream in(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
ui->plainTextEdit->setPlainText(in.readAll());
QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
connect(ui->plainTextEdit->document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));
return true;
}
bool SQLWindow::save() {
if (isUntitled) {
return saveAs();
} else {
return saveFile(this->curFile);
}
}
bool SQLWindow::saveAs() {
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile);
if (fileName.isEmpty()) {
return false;
}
return saveFile(fileName);
}
bool SQLWindow::saveFile(const QString &fileName) {
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot write file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream out(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
out << ui->plainTextEdit->toPlainText();
QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
return true;
}
void SQLWindow::setCurrentFile(const QString &fileName)
{
curFile = QFileInfo(fileName).canonicalFilePath();
isUntitled = false;
ui->plainTextEdit->document()->setModified(false);
setWindowModified(false);
setWindowTitle(userFriendlyCurrentFile() + "[*]");
}
QString SQLWindow::strippedName(const QString &fullFileName)
{
return QFileInfo(fullFileName).fileName();
}
QString SQLWindow::userFriendlyCurrentFile()
{
return strippedName(curFile);
}
void SQLWindow::documentWasModified()
{
setWindowModified(ui->plainTextEdit->document()->isModified());
}
void SQLWindow::displayContextMenu(const QPoint pos)
{
QMenu contextMenu;
QAction *exportAction = new QAction("Export to CSV...", this);
connect (exportAction, SIGNAL(triggered()), this, SLOT(csvExport()));
contextMenu.addAction(exportAction);
contextMenu.exec(ui->tableWidget->viewport()->mapToGlobal(pos));
}
void SQLWindow::updateUI(QList<QSqlRecord> *results)
{
for (int i=0; i<results->size(); i++) {
QList<QStandardItem *> list;
list.append(new QStandardItem(results->at(i).value(0).toString()));
list.append(new QStandardItem(results->at(i).value(1).toString()));
list.append(new QStandardItem(results->at(i).value(2).toString()));
list.append(new QStandardItem("[ SCHEDULED ]"));
// model->appendRow(list);
}
delete results;
qDebug() << "update UI called...";
}
void SQLWindow::queryFinished(bool b)
{
// UI update
if (b) {
statusBar()->showMessage(tr("Executed in %1 seconds").arg(timer.elapsed() / 1000));
}
else
statusBar()->showMessage(tr("User requested cancel of current operation"));
qDebug() << "query finished called...";
}
void SQLWindow::csvExport()
{
if (ui->tableWidget->rowCount() > 0) {
QString fileName = QFileDialog::getSaveFileName(this, tr("Export to"), "", "CSV (*.csv)");
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("CSV Export"), tr("Cannot write file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
} else {
QTextStream out(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
for (int i = 0; i < ui->tableWidget->rowCount(); i++) {
for (int j = 0; j < ui->tableWidget->columnCount(); j++) {
if (j == 0)
out << ui->tableWidget->item(i, j)->text();
else
out << ";" << ui->tableWidget->item(i, j)->text();
}
out << "\n";
}
QApplication::restoreOverrideCursor();
statusBar()->showMessage(QString::number(ui->tableWidget->rowCount()) + " rows exported");
}
} else {
QMessageBox::information(this, "CSV Export", "File name is empty");
}
} else {
QMessageBox::information(this, "CSV Export", "Nothing to export");
}
}
bool SQLWindow::maybeSave()
{
if (ui->plainTextEdit->document()->isModified()) {
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("MDI"),
tr("'%1' has been modified.\n"
"Do you want to save your changes?")
.arg(userFriendlyCurrentFile()),
QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel);
if (ret == QMessageBox::Save)
return save();
else if (ret == QMessageBox::Cancel)
return false;
}
return true;
}
<file_sep>#ifndef SQLCONNECTIONDIALOG_H
#define SQLCONNECTIONDIALOG_H
#include <QDialog>
#include <QSqlRecord>
//#include "querythread.h"
namespace Ui {
class SqlConnectionDialog;
}
class SqlConnectionDialog : public QDialog
{
Q_OBJECT
public:
explicit SqlConnectionDialog(QWidget *parent = 0);
~SqlConnectionDialog();
QString databaseName() const;
QString userName() const;
QString password() const;
private:
Ui::SqlConnectionDialog *ui;
};
#endif // SQLCONNECTIONDIALOG_H
<file_sep>#include "sqlconnectiondialog.h"
#include "ui_sqlconnectiondialog.h"
SqlConnectionDialog::SqlConnectionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SqlConnectionDialog)
{
ui->setupUi(this);
ui->lineEditUsername->setFocus();
}
SqlConnectionDialog::~SqlConnectionDialog()
{
delete ui;
}
QString SqlConnectionDialog::databaseName() const {
return ui->lineEditDatabase->text();
}
QString SqlConnectionDialog::userName() const {
return ui->lineEditUsername->text();
}
QString SqlConnectionDialog::password() const {
return ui->lineEditPassword->text();
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtGui>
#include <QtSql>
#include <QString>
#include <treemodel.h>
#include "sqlconnectiondialog.h"
#include "sqlwindow.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QSqlDatabase db;
QString windowsTitle;
void createActions();
void setTitle(QString newTitle);
void refreshObjectTree(QModelIndex index, bool reload = false);
SQLWindow *activeSQLWindow();
QMdiSubWindow *findSQLWindow(const QString &fileName);
SQLWindow *createSQLWindow();
TreeModel *treeModel;
private slots:
void login();
void logoff();
void commit();
void rollback();
void execute();
void newSqlWindow();
void open();
void save();
void saveAs();
void close();
void closeAll();
void about();
void updateMenus();
void itemExpanded(QModelIndex);
void initializeObjectTree();
// void copy();
// void paste();
// void cut();
};
#endif // MAINWINDOW_H
<file_sep>#include "dbtreeitem.h"
DBTreeItem::DBTreeItem(const QList<QVariant> &data, const QString &sql, TreeItem *parent)
: TreeItem(data, parent)
{
sql = sql;
}
<file_sep>#ifndef TREEMODEL_H
#define TREEMODEL_H
#include <QAbstractItemModel>
#include <QStringList>
#include <QFile>
#include <QXmlStreamReader>
#include "treeitem.h"
#include <QMessageBox>
class TreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
TreeModel(const QString &header, const QString &fileName, QObject *parent = 0);
~TreeModel();
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
QModelIndex parent(const QModelIndex &child) const;
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
void addTreePlaceholders();
void clearTree();
private:
void setupModelData(const QString &fileName, TreeItem *parent);
TreeItem *rootItem;
};
#endif // TREEMODEL_H
<file_sep>OracleDeveloper
===============
Qt Oracle Client<file_sep>#ifndef SQLWINDOW_H
#define SQLWINDOW_H
#include <QMainWindow>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QTextEdit>
#include <QElapsedTimer>
#include "queryexecutor.h"
namespace Ui {
class SQLWindow;
}
class SQLWindow : public QMainWindow
{
Q_OBJECT
public:
explicit SQLWindow(QSqlDatabase &db, QWidget *parent = 0);
~SQLWindow();
bool loadFile(const QString &fileName);
bool save();
bool saveAs();
bool saveFile(const QString &fileName);
void execute();
void rollback();
void commit();
void logon(QSqlDatabase &pDB);
void logoff();
QString currentFile() { return curFile; }
protected:
void closeEvent(QCloseEvent *event);
private slots:
void documentWasModified();
void displayContextMenu(const QPoint pos);
void csvExport();
void updateUI(QList<QSqlRecord> *);
void queryFinished(bool);
private:
Ui::SQLWindow *ui;
QSqlDatabase db;
QString curFile;
bool isUntitled;
void createActions();
void setCurrentFile(const QString &fileName);
QString userFriendlyCurrentFile();
QString strippedName(const QString &fullFileName);
bool maybeSave();
int windowSeq;
QElapsedTimer timer;
QueryExecutor *executor;
static int sequenceNumber;
};
#endif // SQLWINDOW_H
<file_sep>#include "queryexecutor.h"
QueryExecutor::QueryExecutor(QObject *parent) :
QThread(parent)
{
pageSize = 100;
}
QueryExecutor::~QueryExecutor()
{
}
void QueryExecutor::initializeQuery(QSqlDatabase &db, QString sql)
{
dbLocal = db;
sqlLocal = sql;
}
void QueryExecutor::run()
{
QSqlQuery query = QSqlQuery(dbLocal);
int page = 1;
isRunning = true;
query.prepare(QString("select * from (select a.*, rownum r from (%1) a where rownum <= 100 * :p) where r > 100 * (:pp - 1)").arg(sqlLocal));
while (isRunning) {
query.bindValue(":p", page);
query.bindValue(":pp", page);
int count = 0;
query.exec();
QList<QSqlRecord> *results = new QList<QSqlRecord>();
while (query.next()) {
results->append(query.record());
count ++;
}
if (count == 0) {
delete results;
break;
}
qDebug() << "Sent page #" << page << " " << results->size();
emit pageLoaded(results);
page++;
}
emit queryFinished(isRunning);
isRunning = false;
}
void QueryExecutor::cancel()
{
this->isRunning = false;
}
|
49d2442cde2e6a23cd7262395447c55773e9c889
|
[
"Markdown",
"Text",
"C++"
] | 13
|
Text
|
Opel/OracleDeveloper
|
94a1d32571195a2160de0c5d968b27417c2da3d9
|
f5157bbcbda3ab27e07e7728bd64380daf6c1c18
|
refs/heads/main
|
<repo_name>Blue-Dingo/gold_miner<file_sep>/gold_miner.py
#########################################################
# ## import
import pygame
import os
import math
from pygame import Surface, surface
#########################################################
# ## funcs & class
class Claw(pygame.sprite.Sprite):
def __init__(self, image, position) -> None:
super().__init__()
self.image = image
self.rect = image.get_rect(center=position)
self.origin = position # 집게의 원점 좌표 저장
self.image0 = image # 회전되기 전의 이미지 저장
self.offset_x0 = 50
self.offset = pygame.math.Vector2(self.offset_x0, 0)
self.set_init()
def draw(self, screen):
pygame.draw.circle(screen, RED, self.origin, 2)
screen.blit(self.image, self.rect)
def draw_wire(self, screen):
pygame.draw.line(screen, BLACK, self.origin, self.rect.center, 5)
def rotate(self):
self.image = pygame.transform.rotate(self.image0, -self.angle)
def set_init(self):
self.angle = 10
self.direction = CLOCKWISE
self.offset.x = self.offset_x0
self.winding = False
self.to_x = 0
def update(self):
self.offset.x += self.to_x
rotated_offset = self.offset.rotate(self.angle)
self.rect = self.image.get_rect(center=self.origin + rotated_offset)
class GemStone(pygame.sprite.Sprite):
def __init__(self, image, position, speed, score) -> None:
super().__init__()
self.image = image
self.rect = image.get_rect(center=position)
self.speed = speed
self.score = score
def group_add(typeIndex, position):
gemstone_group.add(GemStone(gemstone_images[typeIndex], position, gemstone_speeds[typeIndex], gemstone_score[typeIndex]))
def setup_gemstone():
group_add(1, (300,500))
group_add(1, (800,400))
group_add(0, (200,380))
group_add(0, (500,200))
group_add(0, (600,300))
group_add(2, (700,250))
group_add(3, (900,600))
# gemstone_group.add(GemStone(gemstone_images[0], (200,380), gemstone_speeds[0], gemstone_score[0]))
# gemstone_group.add(GemStone(gemstone_images[1], (300,500), gemstone_speeds[1], gemstone_score[1]))
# gemstone_group.add(GemStone(gemstone_images[2], (300,380), gemstone_speeds[2], gemstone_score[2]))
# gemstone_group.add(GemStone(gemstone_images[3], (900,420), gemstone_speeds[3], gemstone_score[3]))
def check_collide():
global caught_gemstone
for gemstone in gemstone_group:
# if claw.rect.colliderect(gemstone.rect):
if pygame.sprite.collide_mask(claw, gemstone):
caught_gemstone = gemstone
claw.to_x = -gemstone.speed
claw.winding = True
break
def drag_gemstone():
rad = math.radians(claw.angle)
r = caught_gemstone.rect.size[0]/2
x, y = r*math.cos(rad), r*math.sin(rad)
x_claw, y_claw = claw.rect.center[0], claw.rect.center[1]
caught_gemstone.rect = caught_gemstone.image.get_rect(center=(x_claw+x,y_claw+y))
def drop_gemstone():
global caught_gemstone, curr_score
curr_score += caught_gemstone.score
gemstone_group.remove(caught_gemstone)
caught_gemstone = None
#########################################################
# ## pygame 초기화
pygame.init()
screen_w, screen_h = 1280, 720
screen = pygame.display.set_mode((screen_w,screen_h))
pygame.display.set_caption("Gold Miner")
clock = pygame.time.Clock()
#########################################################
# ## 변수들
RED = (255,0,0)
BLACK = (0,0,0)
# 집게 방향
CLOCKWISE = 1
COUNTER_CLOCKWISE = -1
STOP = 0
current_path = os.path.dirname(__file__)
# 점수 시간
game_font = pygame.font.SysFont("arialrounded", 20)
game_font_big = pygame.font.SysFont("arialrounded", 50)
game_font_big.set_bold(True)
start_time = pygame.time.get_ticks()
total_time = 30
goal_score = 1000
curr_score = 0
# 배경
background = pygame.image.load(os.path.join(current_path, "background.png"))
# 보석변수
gemstone_images = [
pygame.image.load(os.path.join(current_path, "small_gold.png")).convert_alpha(),
pygame.image.load(os.path.join(current_path, "big_gold.png")).convert_alpha(),
pygame.image.load(os.path.join(current_path, "stone.png")).convert_alpha(),
pygame.image.load(os.path.join(current_path, "diamond.png")).convert_alpha()]
gemstone_speeds = [5,2,2,7]
gemstone_score = [100,500,10,800]
gemstone_group = pygame.sprite.Group()
setup_gemstone()
caught_gemstone = None
# 집게 변수
claw_image = pygame.image.load(os.path.join(current_path, "claw.png"))
claw = Claw(claw_image, (screen_w/2, 100))
angle_speed = 2.5
launch_speed = 10
return_speed = 20
#########################################################
# ## game loop
running = True
while running:
clock.tick(30)
elapsed = pygame.time.get_ticks() - start_time
time_left = total_time-elapsed//1000
if time_left <=0:
running = False
result = "Game Over"
if curr_score >= goal_score :
running = False
result = "Mission Complete"
goal_score_text = game_font.render(f"Goal Score : {goal_score:,}", True, BLACK)
curr_score_text = game_font.render(f"Current Score : {curr_score:,}", True, BLACK)
timer_text = game_font.render(f"Timer : {time_left}", True, BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
claw.direction = STOP
if claw.direction == CLOCKWISE:
claw.angle += angle_speed
elif claw.direction == COUNTER_CLOCKWISE:
claw.angle -= angle_speed
else:
if not claw.winding:
claw.to_x = launch_speed
# 충돌처리
if not caught_gemstone:
check_collide()
# 경계처리
claw_x = claw.rect.center[0]
claw_y = claw.rect.center[1]
if not(0<claw_x<screen_w) or claw_y>screen_h :
claw.to_x = -return_speed
claw.winding = True
# 되감기중
if claw.winding:
# 끌고오기
if caught_gemstone:
drag_gemstone()
# 원점체크
if claw.offset.x <= claw.offset_x0:
claw.set_init()
# 채광성공
if caught_gemstone:
drop_gemstone()
# 집게 회전
if claw.direction != STOP:
if claw.angle <= 10 :
claw.angle = 10
claw.direction = CLOCKWISE
elif claw.angle >= 170 :
claw.angle = 170
claw.direction = COUNTER_CLOCKWISE
claw.rotate()
claw.update() # claw.rect 업데이트
screen.blit(background, background.get_rect())
gemstone_group.draw(screen)
claw.draw(screen)
claw.draw_wire(screen)
screen.blit(timer_text, timer_text.get_rect(right=screen_w-20,top=20))
screen.blit(goal_score_text, (20,20))
screen.blit(curr_score_text, (20,60))
pygame.display.update()
result_text = game_font_big.render(result, True, BLACK)
screen.blit(result_text, result_text.get_rect(center=screen.get_rect().center))
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
|
87aa804b9a9a321dfbad2ab15b09cd30a4cdf14e
|
[
"Python"
] | 1
|
Python
|
Blue-Dingo/gold_miner
|
6628abbfdfbbcb18cde58b8d62d0b210b4a60c3e
|
f525b2cacff0eedadfc999dc0495c04424cf9417
|
refs/heads/master
|
<repo_name>krunalbapodara/node-ejs-app<file_sep>/routes/routes/users.js
const express = require('express');
const userModal = require('../modals/users');
var router = express.Router();
router.get('/', (req, res) => {
userModal.getAllUsers((err,data)=>{
res.render('layout', { title: 'Users', route: "users", users : data })
});
});
router.get('/:id', (req, res) => {
userModal.getUserByToken(req.params.id,(err,data)=>{
if(err) res.send(err);
res.send(data);
});
});
router.post('/', (req, res) => {
userModal.addUser(req.body,(err,data)=>{
if(err) res.send(err);
res.send(data);
});
});
router.put('/', (req, res) => {
userModal.updateUser(req.body,(err,data)=>{
if(err) res.send(err);
res.send(data);
});
});
router.delete('/', (req, res) => {
userModal.deleteUserByToken(req.body.token,(err,data)=>{
if(err) res.send(err);
res.send(data);
});
});
module.exports = router;<file_sep>/routes/modals/users.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const encryptPsw = (psw, callback) => {
return bcrypt.hash(psw, 13, function (err, hash) {
if (err) throw err;
callback(hash)
});
}
const comparePws = (psw, hash) => {
return bcrypt.compare(psw, hash, function (err, result) {
if (err) return false;
return true;
});
}
const users = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: String,
email: {
type: String,
unique: true
},
contact: Number,
password: {
type: String,
required: true,
select: false
},
token: {
type: String,
default: function () {
return Math.random().toString(36).substr(2);
}
}
})
const userModal = mongoose.model('users', users);
module.exports.getAllUsers = (callback) => {
return userModal.find((err, data) => {
if (err || !data) {
console.log(err);
callback("Records not found", []);
} else {
callback(null, data);
}
})
}
module.exports.getUserByToken = (token, callback) => {
return userModal.findOne({ token: token }, (err, data) => {
if (err || !data) {
console.log(err);
callback("User not found", {});
} else {
callback(null, data);
}
})
}
module.exports.deleteUserByToken = (token, callback) => {
return userModal.deleteOne({ token: token }, (err, data) => {
if (err || !data) {
console.log(err);
callback("Failed to delete user", {});
} else {
callback(null, data);
}
})
}
module.exports.addUser = (user, callback) => {
if (user.password) {
encryptPsw(user.password, (data) => {
user.password = data;
return userModal.create(user, (err, data) => {
if (err || !data) {
console.log(err);
callback("Failed to add user", {});
} else {
callback(null, data);
}
})
});
}
}
module.exports.updateUser = (user, callback) => {
delete user.password;
return userModal.findOne({ token: user.token }, (err, result) => {
if (err || !result) {
console.log(err);
callback("User not found to update", {});
} else {
userModal.updateOne(result, user, (err, data) => {
if (err || !data) {
console.log(err);
callback("Failed to update user", {});
} else {
callback(null, user);
}
})
}
})
}<file_sep>/public/scripts/users.js
$(document).ready( function () {
$('#userTable').addClass( 'nowrap' ).DataTable({
responsive: true,
columnDefs: [
{ targets: [-1], className: 'dt-body-right dt-head-right' }
]
});
$('#userModalButton').click(function() {
$('#userModal').modal('show');
});
});
<file_sep>/README.md
# MVC project in Node.
Template Engine : EJS
Database : MongoDB
=========================================
Step 1: Clone project
Step 2: Run command "npm install" in root directory of project
Step 3: Run command "node app" in root directory of project
Step 4: open "localhost:3000" in browser
<file_sep>/routes/routes/auth.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('layout-full', { title: 'Sign In', route: "signin" })
})
router.get('/signin', (req, res) => {
res.render('layout-full', { title: 'Sign In', route: "signin" })
})
router.get('/forgot', (req, res) => {
res.render('layout-full', { title: 'Forgot Password', route: "forgot" })
})
module.exports = router;
|
885e6ec25d0a8b866a30c442db1ab842faa91e98
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
krunalbapodara/node-ejs-app
|
5cbf42ff312b7d6d85983c77325c657e6e7e7cbc
|
9fe71bc2c61fa627c3e57d93f275b97ef607e3d2
|
refs/heads/master
|
<file_sep>import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GameMain extends JFrame implements KeyListener{
public static void main(String args[]){
System.out.println("70 Miles Per Second");
new GameMain();
}
int width = 800;
int height = 600;
ArrayList attacks = new ArrayList<Attack>();
public GameMain(){
setVisible(true);
setBounds(0,0,width,height);
addKeyListener(this);
createBufferStrategy(2);
while(true){
try{
draw();
update();
Thread.sleep(100);
}
catch(Exception e){
System.out.println(e);
}
}
}
public void draw(){
// Top down
if(prespective == 3){
topDown();
}
else if(prespective == 2){ // 3D
side();
}
}
public void topDown(){
Graphics g = getBufferStrategy().getDrawGraphics();
g.fillRect(0,0,width,height);
g.setColor(Color.red);
g.drawRect((int)c1.x,(int)c1.y,(int)c1.width,(int)c1.height);
g.setColor(Color.green);
g.drawRect((int)c2.x,(int)c2.y,(int)c2.width,(int)c2.height);
g.setColor(Color.blue);
for(int k = 0; k < attacks.size();k++){
Attack a = (Attack) attacks.get(k);
g.drawRect((int)a.x,(int)a.y,(int)a.width,(int)a.height);
}
g.dispose();
getBufferStrategy().show();
}
public void side(){
}
int prespective = 3;
public void p1Draw(){
Graphics g = getBufferStrategy().getDrawGraphics();
g.fillRect(0,0,width,height);
g.setColor(Color.red);
int xOffset = (int) ((width/2)-c1.x);
int yOffset = (int)((height/2)-c1.y);
g.drawRect((int)c1.x+xOffset,(int)c1.y+yOffset,(int)c1.width,(int)c1.height);
g.setColor(Color.green);
g.drawRect((int)c2.x+xOffset,(int)c2.y+yOffset,(int)c2.width,(int)c2.height);
g.setColor(Color.white);
g.drawRect(100+xOffset,100+yOffset,10,10);
g.dispose();
getBufferStrategy().show();
}
public void p2Draw(){
Graphics g = getBufferStrategy().getDrawGraphics();
g.fillRect(0,0,width,height);
g.setColor(Color.red);
int xOffset = (int) ((width/2)-c2.x);
int yOffset = (int)((height/2)-c2.y);
g.drawRect((int)c1.x+xOffset,(int)c1.y+yOffset,(int)c1.width,(int)c1.height);
g.setColor(Color.green);
g.drawRect((int)c2.x+xOffset,(int)c2.y+yOffset,(int)c2.width,(int)c2.height);
g.setColor(Color.white);
g.drawRect(100+xOffset,100+yOffset,10,10);
g.dispose();
getBufferStrategy().show();
}
public void update(){
c1.interact(c2);
c1.update();
c2.update();
for(int k = 0; k < attacks.size(); k++){
Attack a = (Attack) attacks.get(k);
a.interact(c1); // this WILL NOT work the other way around. c1.interact(a)...
a.interact(c2);
a.update();
if(a.hp <= 0){
attacks.remove(k);
k--;
}
}
if(c1.hp <= 0){
c1.x = -1000;
c1.y = -1000;
System.out.println("C1 hp: "+c1.hp);
}
if(c2.hp <= 0){
c2.x = -1000;
c2.y = -1000;
System.out.println("C2 hp: "+c2.hp);
}
}
Car c1 = new Car(200.0,100.0,20,20,10,0,0,0);
Car c2 = new Car(100.0,100.0,20,20,10,0,0,0);
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_1){
prespective = 1;
}
else if(e.getKeyCode() == KeyEvent.VK_2){
prespective = 2;
}
else if(e.getKeyCode() == KeyEvent.VK_3){
prespective = 3;
}
if(e.getKeyCode() == KeyEvent.VK_UP){
c1.up = true;
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
c1.down = true;
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
c1.left = true;
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
c1.right = true;
}
else if(e.getKeyCode() == KeyEvent.VK_W){
c2.up = true;
}
else if(e.getKeyCode() == KeyEvent.VK_S){
c2.down = true;
}
else if(e.getKeyCode() == KeyEvent.VK_A){
c2.left = true;
}
else if(e.getKeyCode() == KeyEvent.VK_D){
c2.right = true;
}
else if(e.getKeyCode() == KeyEvent.VK_SPACE){
attacks.add(new Attack(c1));
}
else if(e.getKeyCode() == KeyEvent.VK_E){
attacks.add(new Attack(c2));
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
c1.up = false;
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
c1.down = false;
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
c1.left = false;
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
c1.right = false;
}
else if(e.getKeyCode() == KeyEvent.VK_W){
c2.up = false;
}
else if(e.getKeyCode() == KeyEvent.VK_S){
c2.down = false;
}
else if(e.getKeyCode() == KeyEvent.VK_A){
c2.left = false;
}
else if(e.getKeyCode() == KeyEvent.VK_D){
c2.right = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
class GameObject{
double x, y, width, height;
double mass;
double vx, vy;
double theta;
boolean collidable = true;
Rectangle rect;
double force = 0.0;
double hp = 10;
public GameObject(double ix, double iy, double iw, double ih, double m, double ivx, double ivy, double t){
x = ix;
y = iy;
width = iw;
height = ih;
mass = m;
vx = ivx;
vy = ivy;
theta = t;
rect = new Rectangle( (int) ix,(int)iy,(int)iw,(int)ih);
}
public void interact(GameObject obj){
if(obj.rect.intersects(rect)){
System.out.println("Collision");
double f1 = getForce();
double t1 = getTheta();
double f2 = obj.getForce();
double t2 = obj.getTheta();
System.out.println("Obj1: F "+f1+" T: "+t1);
System.out.println("Obj1: F "+f2+" T: "+t2);
obj.applyForce(-1*f1,-1*t1);
applyForce(f1,t1);
obj.applyForce(f2,t2);
applyForce(-1*f2,-1*t2);
}
}
public void applyForce(double f, double t){
// TODO: this is just placeholder code. Put in some real math and physics here!!!
force -= f;
theta -= t;
vx = Math.cos(theta) * (force/mass);
vy = Math.sin(theta) * (force/mass);
}
public double getTheta(){
if(vy != 0)
return (theta = Math.atan(vx/vy));
else{
return (theta = 0);
}
}
public double getForce(){
return mass * getVelocity();
}
public double getVelocity() {
return Math.sqrt(Math.pow(vx,2)+Math.pow(vy,2));
}
}
class Car extends GameObject{
boolean up,down,left,right;
public Car(){
super(0,0,10,10,10,0,0,0);
hp = 100;
}
public Car(double ix, double iy, double iw, double ih, double m, double ivx, double ivy, double t){
super(ix,iy,iw,ih,m,ivx,ivy,t);
hp = 100;
}
double topSpeed = 30;
double maxAcc = 5;
// ice has low coef friction
double coefFriction = 0.01;
public void update(){
if(up && vy > -1 * topSpeed){
vy-=maxAcc;
}
if(down && vy < topSpeed){
vy+=maxAcc;
}
if(left && vx > -1 * topSpeed){
vx-=maxAcc;
}
if(right && vx < topSpeed){
vx+=maxAcc;
}
// Friction
vx-=vx/(coefFriction*100)/10;
vy-=vy/(coefFriction*100)/10;
// Actual movement
x+= vx;
y+=vy;
rect.setLocation((int)x,(int)y);
}
}
class Attack extends GameObject{
public Attack(Car c){
super(c.x+c.width+c.vx+10,c.y+c.height/2,3,3,1,1,0,0);
}
public Attack(double ix, double iy, double iw, double ih, double m, double ivx, double ivy, double t){
super(ix,iy,iw,ih,m,ivx,ivy,t);
hp = 1;
mass = 1;
}
public void interact(GameObject obj){
if(obj.rect.intersects(rect)){
System.out.println("Collision");
super.interact(obj);
obj.hp -= hp;
hp = 0;
}
}
public void update(){
x+=vx;
y+=vy;
}
}
|
5be734355b51b55260bdebe2a7159502e84d5bb0
|
[
"Java"
] | 1
|
Java
|
Feni/70MPS
|
6880a864cc5a98c14dc3276af5b14fdc963337a9
|
2ca7f55972f72a46222618072cace8f841da9031
|
refs/heads/master
|
<repo_name>henriquelima92/monomyto_test<file_sep>/Assets/Scripts/Entities/Enemy/States/EnemyShootingState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShootingState : State
{
private ShotSystem shotSystem;
public EnemyShootingState(Entity entity, Transform target) : base(entity)
{
this.target = target;
}
public override void Tick()
{
if (target == null) return;
if (HasPlayerInSight() == true)
{
shotSystem.Tick();
}
else
{
entity.SetState(new EnemyChaseState(entity, target));
}
}
public override void OnStateEnter()
{
shotSystem = entity.GetShotSystem();
}
public override void OnStateExit()
{
shotSystem.ResetSystem();
}
private bool HasPlayerInSight()
{
if (Vector2.Distance(entity.transform.position, target.position) < 2f)
return true;
return false;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
switch (shot.GetShotType())
{
case ShotType.Normal:
case ShotType.Double:
if (entity.GetHealthSystem().GetHealthAmount() <= (entity.GetStartHealth() / 3))
{
entity.SetState(new EnemyAwarenessState(entity, target));
}
break;
case ShotType.Scare:
entity.SetState(new EnemyAwarenessState(entity, target));
break;
case ShotType.Frozen:
entity.SetState(new EnemyFrozenState(entity, target));
break;
}
GameObject.Destroy(shot.gameObject);
}
}
}
<file_sep>/Assets/Scripts/Entities/Player/States/PlayerMovementState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementState : State
{
private Vector3 axisInput;
private float movementSpeed = 0.5f;
private DashMovement dashMovement;
public PlayerMovementState(Entity entity, MonoBehaviour mono) : base(entity)
{
dashMovement = new DashMovement(entity.GetRigidBody());
}
public override void Tick()
{
if(dashMovement.IsDashing() == false)
{
axisInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
if(Input.GetKeyDown(LevelBuilder.builder.GetDashKeyCode()))
{
dashMovement.DoDash();
}
}
public override void TickFixedUpdate()
{
if(dashMovement.IsDashing() == false)
{
Vector3 direction = axisInput.normalized * movementSpeed * Time.deltaTime;
if (LevelBuilder.builder.IsInsideLevelLimits(entity.transform.position + direction) == true)
{
entity.GetRigidBody().MovePosition(entity.transform.position + direction);
}
}
}
public override void OnStateEnter()
{
}
public override void OnStateExit()
{
}
public DashMovement GetDashMovement()
{
return dashMovement;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("EnemyShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
GameObject.Destroy(collision.gameObject);
}
else if(collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
Entity enemyEntity = collision.gameObject.GetComponent<Entity>();
if (GetDashMovement().IsDashing() == true)
{
HealthSystem healthSystem = enemyEntity.GetHealthSystem();
healthSystem.DecreaseHealth(healthSystem.GetHealthAmount());
}
}
}
}
<file_sep>/Assets/Scripts/Utilities.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Utilities
{
public const string ENEMYTAG = "EnemyEntity";
public const string PLAYERTAG = "PlayerEntity";
public const string BOXTAG = "BoxEntity";
public static Vector3 GetMousePositionDirection(Vector3 from)
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = (new Vector3(mousePosition.x, mousePosition.y, 0f) - from).normalized;
return direction;
}
//public static Vector2 GetRandomPointInLevel()
//{
// return new Vector2(
// UnityEngine.Random.Range(MINLEVELWIDTH, MAXLEVELWIDTH),
// UnityEngine.Random.Range(MINLEVELHEIGHT, MAXLEVELHEIGHT));
//}
public static IEnumerator DisableObjectAfterTime(GameObject gameobject, float time)
{
yield return new WaitForSeconds(time);
gameobject.SetActive(false);
}
public static IEnumerator CallMethodWithDelay(Action method, float time)
{
yield return new WaitForSeconds(time);
method();
}
}
<file_sep>/Assets/Scripts/Entities/RechargeBox/States/RechargeElementMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RechargeElementMovement : State
{
private Vector3 direction;
private float movementSpeed = 0.01f;
private ShotType shotTypeToRecharge;
private int shotAmountToRecharge;
public RechargeElementMovement(Entity entity, ShotType shotTypeToRecharge, int shotAmountToRecharge) : base(entity)
{
this.shotTypeToRecharge = shotTypeToRecharge;
this.shotAmountToRecharge = shotAmountToRecharge;
}
public override void Tick()
{
KeepInLevelLimits();
}
public override void TickFixedUpdate()
{
entity.GetRigidBody().MovePosition(entity.transform.position + direction * movementSpeed * Time.deltaTime);
}
public override void OnStateEnter()
{
direction = new Vector3(Random.Range(-100, 100), Random.Range(-100, 100), 0).normalized;
}
public override void OnStateExit() { }
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
HealthSystem healthSystem = entity.GetHealthSystem();
Shot shot = collision.transform.GetComponent<Shot>();
healthSystem.DecreaseHealth(entity.GetStartHealth() / 2);
Recharge(shot.GetEmitterEntity(), healthSystem);
GameObject.Destroy(collision.gameObject);
}
else if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
{
Entity playerEntity = collision.gameObject.GetComponent<Entity>();
PlayerMovementState playerMovementState = (PlayerMovementState)playerEntity.GetState();
if (playerMovementState.GetDashMovement().IsDashing() == true)
{
HealthSystem healthSystem = entity.GetHealthSystem();
healthSystem.DecreaseHealth(healthSystem.GetHealthAmount());
Recharge(playerEntity, healthSystem);
}
}
}
private void Recharge(Entity entity, HealthSystem healthSystem)
{
if(healthSystem.GetHealthAmount() <= 0)
{
PlayerShotSystem playerShotSystem = (PlayerShotSystem)entity.GetShotSystem();
playerShotSystem.Recharge(shotTypeToRecharge, shotAmountToRecharge);
}
}
private void KeepInLevelLimits()
{
Vector2 currentPosition = entity.transform.position;
if (entity.transform.position.x < LevelBuilder.builder.GetWidth().x)
{
entity.transform.position = new Vector2(LevelBuilder.builder.GetWidth().y, currentPosition.y);
}
if(entity.transform.position.x > LevelBuilder.builder.GetWidth().y)
{
entity.transform.position = new Vector2(LevelBuilder.builder.GetWidth().x, currentPosition.y);
}
if (entity.transform.position.y < LevelBuilder.builder.GetHeight().x)
{
entity.transform.position = new Vector2(currentPosition.x, LevelBuilder.builder.GetHeight().y);
}
if (entity.transform.position.y > LevelBuilder.builder.GetHeight().y)
{
entity.transform.position = new Vector2(currentPosition.x, LevelBuilder.builder.GetHeight().x);
}
}
}
<file_sep>/Assets/Scripts/UI/StaticLevelCanvas.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
public class StaticLevelCanvas : MonoBehaviour
{
public static Action OnLevelStart;
public static Action OnLevelEnd;
[SerializeField]
private GameObject edgePanel;
[SerializeField]
private GameObject middlePanel;
[SerializeField]
private Texture2D cursorTexture;
[SerializeField]
private Vector2 hotSpot = Vector2.zero;
private void Awake()
{
OnLevelEnd += LevelEnd;
OnLevelStart += LevelStart;
}
private void OnDestroy()
{
OnLevelEnd -= LevelEnd;
OnLevelStart -= LevelStart;
}
public void PlayAgain()
{
int scene = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(scene, LoadSceneMode.Single);
}
public void QuitButton()
{
Application.Quit();
}
private void LevelStart()
{
edgePanel.SetActive(true);
Cursor.SetCursor(cursorTexture, hotSpot, CursorMode.ForceSoftware);
}
private void LevelEnd()
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
StartCoroutine(Utilities.CallMethodWithDelay(() =>
{
edgePanel.SetActive(false);
middlePanel.SetActive(true);
}, 2));
}
}
<file_sep>/Assets/Scripts/UI/GunsFeedback.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class GunsFeedback : MonoBehaviour
{
public static Action<string, string> OnGunEvent;
[SerializeField]
private TextMeshProUGUI gunFeedback;
private void Awake()
{
OnGunEvent += ChangeGunName;
}
private void OnDestroy()
{
OnGunEvent -= ChangeGunName;
}
private void ChangeGunName(string text, string bullets)
{
string shots = bullets == "0" ? "(no bullets)" : $"(bullets: {bullets})";
gunFeedback.text = $"{text} gun {shots}";
}
}
<file_sep>/Assets/Scripts/UI/StartPanel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class StartPanel : MonoBehaviour
{
[SerializeField]
private TextMeshProUGUI StartingTimer;
[SerializeField]
private float currentTimer;
private void Start()
{
currentTimer = 5f;
}
private void Update()
{
currentTimer -= Time.deltaTime;
if (currentTimer <= 0)
{
LevelBuilder.OnStartTimerEnd?.Invoke();
StaticLevelCanvas.OnLevelStart.Invoke();
gameObject.SetActive(false);
}
else
{
StartingTimer.text = Mathf.RoundToInt(currentTimer).ToString();
}
}
}
<file_sep>/Assets/Scripts/ShotS/Player/NormalShot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NormalShot : Shot
{
private void Update()
{
if (LevelBuilder.builder.IsInsideLevelLimits(transform.position) == false)
{
Destroy(gameObject);
}
}
}
<file_sep>/README.md
# Shooter Monomyto Test
O desafio era criar um jogo no estilo **Diep.io** na Unity, buscando um código limpo e bem estruturado.
## **O que foi desenvolvido:**
- [x] Mecânica de movimentação de personagem;
- [x] Caixas destrutíveis (recarregam uma quantidade de um tipo de munição);
- [x] Mecânica de soco (chamei de Dash, na minha versão, além de destruir as caixas de munição, também pode matar inimigos e também para se movimentar mais rápido);
- [x] 4 tipos de armas, a normal, double (tiro na frente e nas costas), scare (faz com que o inimigo corra de medo) e frozen (inimigo fica congelado por um tempo);
- [x] Bot simples com máquina de estados (movement, shooting, awareness, chase e frozen);
- [x] Sistema de pontuação, quebrando caixas de munição dá 10 pontos e matar inimigo dá 20;
- [x] Gameover com pontuação atingida, tela de vitória (podendo reiniciar e sair do jogo)
- Dentro do projeto, o dev pode criar scriptable objects com dados do nível, podendo setar os limites de movimentação, quantidade inicial de munição, quantidade de inimigos e de caixas recarregáveis.
- Nesse mesmo scriptable object, o dev pode setar o KeyCode referente ao **tiro, troca de arma e Dash**
- Foram utilizadas classes abstratas, polimorfismo, máquina de estados e também Action events.
## **Instruções para jogar:**
- Baixar o conteúdo da branch **release-0.1**
- Executar o arquivo **ShooterMonomytoTest.exe**
- O jogador usa o mouse para mirar.
- As teclas setadas para essa release são :
### **Teclas**
- Movimentação - **WASD ou setas**
- Dash - **botão direito do mouse**
- Tiro - **botão esquerdo do mouse**
- Troca de arma - **clique da roda do mouse**
- Botão de quit - **tecla esc** (o jogador pode sair do jogo em qualquer momento)
## TO DO
- [] Adicionar mais feedbacks;
- [] Adicionar sons;
- [] Criar um menu de seleção de níveis;
- [] Criar um menu inicial;
- [] Desenvolver mais tipos de inimigos, armas e caixas de munição;
- [] Criar um object pooling para melhoria de performance;
- [] Melhorias de código; (sempre tem)
<file_sep>/Assets/Scripts/Effects/ExplosionEffect.cs
using UnityEngine;
public class ExplosionEffect
{
private ParticleSystem particle;
public ExplosionEffect(ParticleSystem particle)
{
this.particle = particle;
}
public void Play()
{
particle.transform.SetParent(null);
particle.gameObject.SetActive(true);
GameObject.Destroy(particle.gameObject, particle.main.duration);
}
}
<file_sep>/Assets/Scripts/Entities/HealthSystem.cs
using System;
using UnityEngine;
[Serializable]
public class HealthSystem
{
public Action<float> OnHealthChange;
private Entity entity;
private float health;
public HealthSystem(Entity entity, float health)
{
this.entity = entity;
this.health = health;
}
public float GetHealthAmount()
{
return health;
}
public void IncreaseHealth(float amount)
{
if(health <= 100)
{
health += amount;
OnHealthChange?.Invoke(health);
}
}
public void DecreaseHealth(float amount)
{
if(health > 0)
{
health -= amount;
OnHealthChange?.Invoke(health);
if(health <= 0)
{
entity.OnEntityDefeat?.Invoke();
}
}
}
}
<file_sep>/Assets/Scripts/UI/PointsFeedback.cs
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System;
public class PointsFeedback : MonoBehaviour
{
public static Action<string, Vector3> OnEventOcurred;
[SerializeField]
private List<TextMeshProUGUI> points;
[SerializeField]
private Vector3 pointOffset;
private void Awake()
{
OnEventOcurred += SetAvailablePoint;
}
private void OnDestroy()
{
OnEventOcurred -= SetAvailablePoint;
}
public void SetAvailablePoint(string text, Vector3 position)
{
for (int i = 0; i < points.Count; i++)
{
if(points[i].gameObject.activeInHierarchy == false)
{
points[i].transform.position = position + pointOffset;
points[i].text = $"+{text} points";
points[i].gameObject.SetActive(true);
float animationLength = points[i].GetComponent<Animator>().runtimeAnimatorController.animationClips[0].length;
StartCoroutine(Utilities.DisableObjectAfterTime(points[i].gameObject, animationLength));
return;
}
}
}
}
<file_sep>/Assets/Scripts/Entities/Enemy/States/EnemyFrozenState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyFrozenState : State
{
private float frozenTime = 3.5f;
public EnemyFrozenState(Entity entity, Transform target) : base(entity)
{
this.target = target;
}
public override void Tick()
{
if (target == null) return;
frozenTime -= Time.deltaTime;
if(frozenTime < 0)
{
entity.SetState(new EnemyMovementState(entity, target));
}
}
public override void OnStateEnter()
{
entity.GetComponent<SpriteRenderer>().color = Color.blue;
}
public override void OnStateExit()
{
entity.GetComponent<SpriteRenderer>().color = Color.white;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
GameObject.Destroy(shot.gameObject);
}
}
}
<file_sep>/Assets/Scripts/LevelBuilder.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelBuilder : MonoBehaviour
{
public static Action OnStartTimerEnd;
public static Action<GameObject> OnEnemyDefeat;
public static LevelBuilder builder;
[SerializeField]
private LevelData levelData;
[SerializeField]
private GameObject enemy;
[SerializeField]
private GameObject normalRecharge;
[SerializeField]
private GameObject doubleRecharge;
[SerializeField]
private GameObject scareRecharge;
[SerializeField]
private GameObject frozenRecharge;
[SerializeField]
private GameObject playerCharacter;
[SerializeField]
private LineRenderer lineRenderer;
private List<GameObject> enemies;
private float minPlayerDistance = -3f;
private float maxPlayerDistance = 3f;
private void Start()
{
enemies = new List<GameObject>();
builder = this;
OnStartTimerEnd += Build;
OnEnemyDefeat += EnemyDefeated;
SetLineRendererLevelLimits();
}
private void OnDestroy()
{
OnStartTimerEnd -= Build;
OnEnemyDefeat -= EnemyDefeated;
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
private void SetLineRendererLevelLimits()
{
lineRenderer.SetPosition(0, new Vector3(levelData.MinWidth, levelData.MaxWidth, levelData.MaxWidth));
lineRenderer.SetPosition(1, new Vector3(levelData.MaxWidth, levelData.MaxWidth, levelData.MaxWidth));
lineRenderer.SetPosition(2, new Vector3(levelData.MaxWidth, levelData.MinHeight, levelData.MaxWidth));
lineRenderer.SetPosition(3, new Vector3(levelData.MinWidth, levelData.MinHeight, levelData.MaxWidth));
//levelData.MaxWidth- levelData.MinWidth
//levelData.MaxHeight - levelData.MinHeight
}
private void Build()
{
Instantiate(playerCharacter, new Vector2(levelData.MinWidth + levelData.MaxWidth , levelData.MinHeight + levelData.MaxHeight), Quaternion.identity);
enemies.AddRange(InstantiateGroupInRandomPosition(enemy, levelData.EnemiesNumber, false));
InstantiateGroupInRandomPosition(normalRecharge, levelData.Normal, true);
InstantiateGroupInRandomPosition(doubleRecharge, levelData.Double, true);
InstantiateGroupInRandomPosition(scareRecharge, levelData.Scare, true);
InstantiateGroupInRandomPosition(frozenRecharge, levelData.Frozen, true);
}
private List<GameObject> InstantiateGroupInRandomPosition(GameObject prefab, int count, bool ignoreMinPosition)
{
List<GameObject> instantiated = new List<GameObject>();
for (int i = 0; i <count; i++)
{
Vector2 position = Vector2.zero;
if (ignoreMinPosition == false)
{
position = new Vector2(
GetRandomPostionWithMinDistance(levelData.MinWidth, levelData.MaxWidth),
GetRandomPostionWithMinDistance(levelData.MinHeight, levelData.MaxHeight));
}
else
{
position = new Vector2(
GetRandomPostion(levelData.MinWidth, levelData.MaxWidth),
GetRandomPostion(levelData.MinHeight, levelData.MaxHeight));
}
GameObject obj = Instantiate(prefab, position, Quaternion.identity);
instantiated.Add(obj);
}
return instantiated;
}
private float GetRandomPostionWithMinDistance(float min, float max)
{
float minValue = UnityEngine.Random.Range(min, minPlayerDistance);
float maxValue = UnityEngine.Random.Range(maxPlayerDistance, max);
float resolution = UnityEngine.Random.Range(0, 100) >= 50 ? maxValue : minValue;
return resolution;
}
private float GetRandomPostion(float min, float max)
{
float position = UnityEngine.Random.Range(min, max);
return position;
}
private void EnemyDefeated(GameObject obj)
{
if(enemies.Contains(obj) == true)
{
enemies.Remove(obj);
}
if(enemies.Count <= 0)
{
StaticLevelCanvas.OnLevelEnd?.Invoke();
PlayerCharacter.OnLevelWin?.Invoke();
}
}
public KeyCode GetDashKeyCode()
{
return levelData.DashMovement;
}
public KeyCode GetShotKeyCode()
{
return levelData.Shot;
}
public KeyCode GetWeaponKeyCode()
{
return levelData.ChangeWeapon;
}
public int GetNormalStartAmmo()
{
return levelData.NormalStartAmmo;
}
public int GetDoubleStartAmmo()
{
return levelData.DoubleStartAmmo;
}
public int GetScareStartAmmo()
{
return levelData.ScareStartAmmo;
}
public int GetFrozenStartAmmo()
{
return levelData.FrozenStartAmmo;
}
public Vector2 GetWidth()
{
return new Vector2(levelData.MinWidth, levelData.MaxWidth);
}
public Vector2 GetHeight()
{
return new Vector2(levelData.MinHeight, levelData.MaxHeight);
}
public bool IsInsideLevelLimits(Vector2 position)
{
if (position.x < levelData.MaxWidth && position.x > levelData.MinWidth
&& position.y < levelData.MaxHeight && position.y > levelData.MinHeight)
{
return true;
}
return false;
}
public Vector2 GetRandomPointInLevel()
{
return new Vector2(
UnityEngine.Random.Range(levelData.MinWidth, levelData.MaxWidth),
UnityEngine.Random.Range(levelData.MinHeight, levelData.MaxHeight));
}
}
<file_sep>/Assets/Scripts/Entities/Entity.cs
using System;
using UnityEngine;
[Serializable]
public abstract class Entity : MonoBehaviour
{
public Action OnEntityDefeat;
[SerializeField]
protected float startHealth = 100f;
[SerializeField]
protected ShotSystem shotSystem;
[SerializeField]
protected int winPoints;
protected Rigidbody2D rb;
protected HealthSystem healthSystem;
protected State currentState;
public abstract void EntityDefeat();
public float GetStartHealth()
{
return startHealth;
}
public HealthSystem GetHealthSystem()
{
return healthSystem != null ? healthSystem : null;
}
public ShotSystem GetShotSystem()
{
return shotSystem != null ? shotSystem : null;
}
public Rigidbody2D GetRigidBody()
{
return rb;
}
public State GetState()
{
return currentState;
}
public void SetState(State newState)
{
if(currentState != null)
{
currentState.OnStateExit();
}
currentState = newState;
if(currentState != null)
{
currentState.OnStateEnter();
}
}
}
<file_sep>/Assets/Scripts/ShotS/Player/PlayerShotSystem.cs
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class PlayerShotSystem : ShotSystem
{
[SerializeField]
private List<int> shotsAmount;
[SerializeField]
private int shotSelected;
public PlayerShotSystem(Entity entity, List<GameObject> shotPrefabs) : base(entity, shotPrefabs)
{
shotSelected = 0;
shotsAmount = new List<int> {
LevelBuilder.builder.GetNormalStartAmmo(),
LevelBuilder.builder.GetDoubleStartAmmo(),
LevelBuilder.builder.GetScareStartAmmo(),
LevelBuilder.builder.GetFrozenStartAmmo()};
GunsFeedback.OnGunEvent?.Invoke(((ShotType)shotSelected).ToString(), shotsAmount[shotSelected].ToString());
}
public override void Tick()
{
if(Input.GetKeyDown(LevelBuilder.builder.GetShotKeyCode()))
{
CreateShot();
}
if (Input.GetKeyDown(LevelBuilder.builder.GetWeaponKeyCode()))
{
ChangeShotType();
}
}
public override void CreateShot()
{
if(shotsAmount[shotSelected] > 0)
{
shotsAmount[shotSelected] -= 1;
GunsFeedback.OnGunEvent?.Invoke(((ShotType)shotSelected).ToString(), shotsAmount[shotSelected].ToString());
Vector3 direction = Utilities.GetMousePositionDirection(entity.transform.position);
GameObject shotObject = GameObject.Instantiate(prefabs[shotSelected], entity.transform.position, Quaternion.identity);
Shot shot = shotObject.GetComponent<Shot>();
shot.Setup(direction, entity);
if (shotSelected == (int)ShotType.Double)
{
GameObject doubleshotObject = GameObject.Instantiate(prefabs[shotSelected], entity.transform.position, Quaternion.identity);
Shot doubleshot = doubleshotObject.GetComponent<Shot>();
doubleshot.Setup(direction * -1, entity);
}
}
}
public void Recharge(ShotType type, int amount)
{
shotsAmount[(int)type] += amount;
GunsFeedback.OnGunEvent?.Invoke(((ShotType)shotSelected).ToString(), shotsAmount[shotSelected].ToString());
}
private void ChangeShotType()
{
shotSelected = (shotSelected < shotsAmount.Count - 1) ? (shotSelected += 1) : 0;
GunsFeedback.OnGunEvent?.Invoke(((ShotType)shotSelected).ToString(), shotsAmount[shotSelected].ToString());
}
}
<file_sep>/Assets/Scripts/ShotS/Shot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ShotType
{
Normal,
Double,
Scare,
Frozen
}
public abstract class Shot : MonoBehaviour
{
[SerializeField]
protected ShotType type;
[SerializeField]
protected Rigidbody2D rb;
[SerializeField]
protected Entity entity;
[SerializeField]
protected float speed;
[SerializeField]
protected Vector3 direction;
[SerializeField]
protected float damage;
public void Setup(Vector3 direction, Entity emitter)
{
this.direction = direction;
entity = emitter;
ShotInDirection(direction);
}
public Entity GetEmitterEntity()
{
return entity;
}
public float GetDamage()
{
return damage;
}
public ShotType GetShotType()
{
return type;
}
private void ShotInDirection(Vector3 direction)
{
rb.AddForce(direction * speed);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("EnemyShot") || collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/Entities/Enemy/States/EnemyMovementState.cs
using System;
using UnityEngine;
[Serializable]
public class EnemyMovementState : State
{
private float movementSpeed = 0.25f;
private Vector2 nextDestination;
public EnemyMovementState(Entity entity, Transform target) : base(entity)
{
this.target = target;
}
public override void TickFixedUpdate()
{
if (target == null) return;
Vector3 direction = (nextDestination - new Vector2(entity.transform.position.x, entity.transform.position.y)).normalized;
entity.GetRigidBody().MovePosition(entity.transform.position + direction * movementSpeed * Time.deltaTime);
}
public override void Tick()
{
if (target == null) return;
if (ReachedDestination() == true)
{
nextDestination = GetRandomDestination();
}
if(HasPlayerInSight() == true)
{
entity.SetState(new EnemyShootingState(entity, target));
}
}
public override void OnStateEnter()
{
nextDestination = GetRandomDestination();
}
private bool HasPlayerInSight()
{
if (Vector2.Distance(entity.transform.position, target.position) < 2f)
return true;
return false;
}
private Vector2 GetRandomDestination()
{
return LevelBuilder.builder.GetRandomPointInLevel();
}
private bool ReachedDestination()
{
return Vector3.Distance(entity.transform.position, nextDestination) < 0.5f;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
switch (shot.GetShotType())
{
case ShotType.Normal:
case ShotType.Double:
if (entity.GetHealthSystem().GetHealthAmount() <= (entity.GetStartHealth()/ 3))
{
entity.SetState(new EnemyAwarenessState(entity, target));
}
else
{
entity.SetState(new EnemyChaseState(entity, target));
}
break;
case ShotType.Scare:
entity.SetState(new EnemyAwarenessState(entity, target));
break;
case ShotType.Frozen:
entity.SetState(new EnemyFrozenState(entity, target));
break;
}
GameObject.Destroy(shot.gameObject);
}
}
}
<file_sep>/Assets/Scripts/ShotS/ShotSystem.cs
using System.Collections.Generic;
using UnityEngine;
public abstract class ShotSystem
{
protected Entity entity;
protected List<GameObject> prefabs;
protected ShotSystem(Entity entity, List<GameObject> prefabs)
{
this.entity = entity;
this.prefabs = prefabs;
}
public abstract void Tick();
public abstract void CreateShot();
public virtual void ResetSystem() {}
}
<file_sep>/Assets/Scripts/ScriptableObjects/LevelData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Data", menuName = "LevelData/Create", order = 1)]
public class LevelData : ScriptableObject
{
[Header("Level Limits")]
[Range(-3, -20)]
public int MinWidth = -3;
[Range(3, 20)]
public int MaxWidth = 3;
[Range(-3, -20)]
public int MinHeight = -3;
[Range(3, 20)]
public int MaxHeight = 3;
[Header("Enemies")]
public int EnemiesNumber;
[Header("Recharge Boxes")]
public int Normal;
public int Double;
public int Scare;
public int Frozen;
[Header("Player")]
public int NormalStartAmmo;
public int DoubleStartAmmo;
public int ScareStartAmmo;
public int FrozenStartAmmo;
[Header("Keyboard/Mouse buttons")]
public KeyCode DashMovement;
public KeyCode Shot;
public KeyCode ChangeWeapon;
}
<file_sep>/Assets/Scripts/Entities/Enemy/EnemyCharacter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCharacter : Entity
{
private Transform target;
[SerializeField]
private List<GameObject> shotPrefabs;
[SerializeField]
private float bulletSpeed;
[SerializeField]
private ParticleSystem deathParticleSystem;
private ExplosionEffect explosionEffect;
public override void EntityDefeat()
{
explosionEffect.Play();
PointsFeedback.OnEventOcurred?.Invoke(winPoints.ToString(), transform.position);
PointsManager.OnPointUpdate?.Invoke(winPoints);
LevelBuilder.OnEnemyDefeat?.Invoke(gameObject);
Destroy(gameObject);
}
private void Awake()
{
target = GameObject.FindWithTag(Utilities.PLAYERTAG).transform;
rb = GetComponent<Rigidbody2D>();
healthSystem = new HealthSystem(this, startHealth);
shotSystem = new EnemyShotSystem(this, shotPrefabs, target);
explosionEffect = new ExplosionEffect(deathParticleSystem);
OnEntityDefeat += EntityDefeat;
}
private void Start()
{
SetState(new EnemyMovementState(this, target));
}
private void Update()
{
currentState.Tick();
}
private void FixedUpdate()
{
currentState.TickFixedUpdate();
}
private void OnDestroy()
{
OnEntityDefeat -= EntityDefeat;
}
private void OnCollisionEnter2D(Collision2D collision)
{
currentState.OnCollisionEvent(collision);
}
}
<file_sep>/Assets/Scripts/Entities/RechargeBox/RechargeElement.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RechargeElement : Entity
{
public Action<PlayerShotSystem> OnRechargeEvent;
[SerializeField]
private ShotType shotTypeToRecharge;
[SerializeField]
private int shotAmountToRecharge = 10;
[SerializeField]
private ParticleSystem deathParticleSystem;
private ExplosionEffect explosionEffect;
public override void EntityDefeat()
{
explosionEffect.Play();
PointsFeedback.OnEventOcurred?.Invoke(winPoints.ToString(), transform.position);
PointsManager.OnPointUpdate?.Invoke(winPoints);
Destroy(gameObject);
}
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
healthSystem = new HealthSystem(this, startHealth);
explosionEffect = new ExplosionEffect(deathParticleSystem);
OnEntityDefeat += EntityDefeat;
}
private void Start()
{
SetState(new RechargeElementMovement(this, shotTypeToRecharge, shotAmountToRecharge));
}
private void Update()
{
currentState.Tick();
}
private void FixedUpdate()
{
currentState.TickFixedUpdate();
}
private void OnDestroy()
{
OnEntityDefeat -= EntityDefeat;
}
private void OnCollisionEnter2D(Collision2D collision)
{
currentState.OnCollisionEvent(collision);
}
}
<file_sep>/Assets/Scripts/Entities/State.cs
using System;
using UnityEngine;
[Serializable]
public abstract class State
{
protected Transform target;
protected Entity entity;
protected State(Entity entity)
{
this.entity = entity;
}
public virtual void Tick() {}
public virtual void OnCollisionEvent(Collision2D collision) { }
public virtual void TickFixedUpdate() {}
public virtual void OnStateEnter() {}
public virtual void OnStateExit() {}
}
<file_sep>/Assets/Scripts/PointsManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PointsManager : MonoBehaviour
{
public static Action<int> OnPointUpdate;
[SerializeField]
private int currentPoints;
[SerializeField]
private TextMeshProUGUI edgeScore;
[SerializeField]
private TextMeshProUGUI middleScore;
private void Awake()
{
currentPoints = 0;
OnPointUpdate += UpdatePoints;
}
private void OnDestroy()
{
OnPointUpdate -= UpdatePoints;
}
private void UpdatePoints(int points)
{
currentPoints += points;
edgeScore.text = currentPoints.ToString();
middleScore.text = currentPoints.ToString();
}
}
<file_sep>/Assets/Scripts/Entities/Enemy/States/EnemyChaseState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyChaseState : State
{
private float movementSpeed = 0.25f;
private float chaseTime = 5f;
private float currentChaseTime = 0f;
public EnemyChaseState(Entity entity, Transform target) : base(entity)
{
this.target = target;
}
public override void TickFixedUpdate()
{
if (target == null) return;
Vector3 direction = (target.transform.position - entity.transform.position).normalized;
entity.GetRigidBody().MovePosition(entity.transform.position + direction * movementSpeed * Time.deltaTime);
}
public override void Tick()
{
if (target == null) return;
if (target.gameObject.activeInHierarchy == false)
{
return;
}
if (HasPlayerInSight() == true)
{
entity.SetState(new EnemyShootingState(entity, target));
}
currentChaseTime += Time.deltaTime;
if (currentChaseTime > chaseTime)
{
entity.SetState(new EnemyMovementState(entity, target));
}
}
private bool HasPlayerInSight()
{
if (Vector2.Distance(entity.transform.position, target.position) < 2f)
return true;
return false;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
switch (shot.GetShotType())
{
case ShotType.Normal:
case ShotType.Double:
if (entity.GetHealthSystem().GetHealthAmount() <= (entity.GetStartHealth() / 3))
{
entity.SetState(new EnemyAwarenessState(entity, target));
}
break;
case ShotType.Scare:
entity.SetState(new EnemyAwarenessState(entity, target));
break;
case ShotType.Frozen:
entity.SetState(new EnemyFrozenState(entity, target));
break;
}
GameObject.Destroy(shot.gameObject);
}
}
}
<file_sep>/Assets/Scripts/ShotS/Enemy/EnemyShotSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShotSystem : ShotSystem
{
private Transform target;
private float reloadTime = 1.5f;
private float shotTime = 0f;
public EnemyShotSystem(Entity entity, List<GameObject> shotPrefabs, Transform target) : base(entity, shotPrefabs)
{
this.target = target;
}
public override void CreateShot()
{
Vector3 direction = (target.position - entity.transform.position).normalized;
GameObject shotObject = GameObject.Instantiate(prefabs[0], entity.transform.position, Quaternion.identity);
Shot shot = shotObject.GetComponent<Shot>();
shot.Setup(direction, entity);
ResetSystem();
}
public override void Tick()
{
shotTime += Time.deltaTime;
if(shotTime > reloadTime)
{
CreateShot();
}
}
public override void ResetSystem()
{
shotTime = 0;
}
}
<file_sep>/Assets/Scripts/Entities/Enemy/States/EnemyAwarenessState.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAwarenessState : State
{
private Vector3 targetDirection;
private float movementSpeed = 0.5f;
public EnemyAwarenessState(Entity entity, Transform target) : base(entity)
{
this.target = target;
}
public override void TickFixedUpdate()
{
if (target == null) return;
entity.GetRigidBody().MovePosition(entity.transform.position + (targetDirection*-1) * movementSpeed * Time.deltaTime);
}
public override void Tick()
{
if (target == null) return;
;
if (HasEscaped() == true)
{
entity.SetState(new EnemyMovementState(entity, target));
}
}
public override void OnStateEnter()
{
entity.GetComponent<SpriteRenderer>().color = Color.red;
targetDirection = (target.transform.position - entity.transform.position).normalized;
}
public override void OnStateExit()
{
entity.GetComponent<SpriteRenderer>().color = Color.white;
}
private bool HasEscaped()
{
if (Vector2.Distance(entity.transform.position, target.position) > 5f)
return true;
return false;
}
public override void OnCollisionEvent(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerShot"))
{
Shot shot = collision.transform.GetComponent<Shot>();
entity.GetHealthSystem().DecreaseHealth(shot.GetDamage());
switch (shot.GetShotType())
{
case ShotType.Frozen:
entity.SetState(new EnemyFrozenState(entity, target));
break;
}
GameObject.Destroy(shot.gameObject);
}
}
}
<file_sep>/Assets/Scripts/UI/HealthBar.cs
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[SerializeField]
private Entity entity;
[SerializeField]
private Image barFillImage;
private float startHealth;
private void Start()
{
if (entity != null)
{
entity.GetHealthSystem().OnHealthChange += ChangeFill;
startHealth = entity.GetHealthSystem().GetHealthAmount();
ChangeFill(startHealth);
}
}
private void OnDestroy()
{
if(entity != null)
{
entity.GetHealthSystem().OnHealthChange -= ChangeFill;
}
}
private void ChangeFill(float health)
{
barFillImage.fillAmount = (health/startHealth);
}
}
<file_sep>/Assets/Scripts/Entities/Player/PlayerCharacter.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCharacter : Entity
{
public static Action OnLevelWin;
[SerializeField]
private List<GameObject> shotPrefabs;
[SerializeField]
private ParticleSystem deathParticleSystem;
private ExplosionEffect explosionEffect;
public override void EntityDefeat()
{
Camera.main.transform.SetParent(null);
explosionEffect.Play();
StaticLevelCanvas.OnLevelEnd?.Invoke();
Destroy(gameObject);
}
private void Awake()
{
OnEntityDefeat += EntityDefeat;
OnLevelWin += LevelWin;
}
private void Start()
{
Camera.main.transform.SetParent(transform);
Camera.main.transform.position = new Vector3(0f, 0f, -10f);
rb = GetComponent<Rigidbody2D>();
healthSystem = new HealthSystem(this, startHealth);
shotSystem = new PlayerShotSystem(this, shotPrefabs);
explosionEffect = new ExplosionEffect(deathParticleSystem);
SetState(new PlayerMovementState(this, this.GetComponent<MonoBehaviour>()));
}
private void Update()
{
currentState.Tick();
shotSystem.Tick();
}
private void FixedUpdate()
{
currentState.TickFixedUpdate();
}
private void OnDestroy()
{
OnEntityDefeat -= EntityDefeat;
OnLevelWin -= LevelWin;
}
private void OnCollisionEnter2D(Collision2D collision)
{
currentState.OnCollisionEvent(collision);
}
private void LevelWin()
{
Camera.main.transform.SetParent(null);
this.enabled = false;
}
}
<file_sep>/Assets/Scripts/Entities/Player/DashMovement.cs
using System.Collections;
using UnityEngine;
public class DashMovement
{
private Rigidbody2D entityRigidBody;
private MonoBehaviour entityMonoBehaviour;
private bool isDashing = false;
private float dashLength;
private float dashSpeed = 2.5f;
public DashMovement(Rigidbody2D entityRigidBody, float dashSpeed = 2.5f, float dashLength = 0.2f)
{
this.entityRigidBody = entityRigidBody;
this.dashSpeed = dashSpeed;
this.dashLength = dashLength;
entityMonoBehaviour = entityRigidBody.gameObject.GetComponent<MonoBehaviour>();
}
public bool IsDashing()
{
return isDashing;
}
public void DoDash()
{
if(isDashing == false)
{
entityMonoBehaviour.StartCoroutine(Dash());
}
}
private IEnumerator Dash()
{
Vector3 direction = Utilities.GetMousePositionDirection(entityRigidBody.transform.position);
float currentDashTime = 0f;
isDashing = true;
while (currentDashTime < dashLength)
{
currentDashTime += Time.deltaTime;
if (LevelBuilder.builder.IsInsideLevelLimits(entityRigidBody.transform.position + direction) == true)
{
entityRigidBody.velocity = direction * dashSpeed;
}
yield return null;
}
entityRigidBody.velocity = Vector3.zero;
isDashing = false;
}
}
|
af1de5b795645b533f52427c54219993f8691bc6
|
[
"Markdown",
"C#"
] | 30
|
C#
|
henriquelima92/monomyto_test
|
a7bb996263d4fbcb6d285b23a905d55bad3c263e
|
de3ba6cac5b09db8195d5cea754f40a035ffe442
|
refs/heads/main
|
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ToolbarComponent } from './components/toolbar/toolbar.component';
import { DrawerComponent } from './components/drawer/drawer.component';
import { FrontendLayoutComponent } from './layouts/frontend-layout/frontend-layout.component';
import { AuthLayoutComponent } from './layouts/auth-layout/auth-layout.component';
import { FullscreenLayoutComponent } from './layouts/fullscreen-layout/fullscreen-layout.component';
import { MaterialModule } from '../material.module';
import { Route, RouterModule } from '@angular/router';
const layoutComponents = { frontend: FrontendLayoutComponent, auth: AuthLayoutComponent, fullscreen: FullscreenLayoutComponent }
export function layout(name: keyof typeof layoutComponents, children: Route[], ...args: any): Route {
return {
path: '',
component: layoutComponents[name],
children,
...args
};
}
@NgModule({
declarations: [ToolbarComponent, DrawerComponent, FrontendLayoutComponent, AuthLayoutComponent, FullscreenLayoutComponent],
imports: [
RouterModule,
CommonModule,
MaterialModule
]
})
export class CoreModule { }
|
95055dc52e8aae76846325f633b61ae52d1d2e8c
|
[
"TypeScript"
] | 1
|
TypeScript
|
wizardnet972/angularup-layouts
|
b1d6ba7c867ee0360f43d4e5aec85689f3748304
|
cb92ead2c180d9c5f6673526c47d1c1628839c1b
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Net;
using System.IO;
namespace HomeDisplay
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DispatcherTimer dispatcherTimer1 = new DispatcherTimer();
private DispatcherTimer dispatcherTimer2 = new DispatcherTimer();
private string currTemp;
private string currCond;
private string currHumid;
private string currWind;
private string location;
private string foreCond;
private string foreHigh;
private string foreLow;
private string imgCode;
private string pubDate;
private BitmapImage sourceImg = new BitmapImage();
public MainWindow()
{
InitializeComponent();
dispatcherTimer1.Tick += dispatcherTimer1_Tick;
dispatcherTimer1.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer1.Start();
label.Content = DateTime.Now.ToLongDateString();
label1.Content = DateTime.Now.ToString("HH:mm:ss");
dispatcherTimer2.Tick += dispatcherTimer2_Tick;
dispatcherTimer2.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer2.Start();
getWeather();
}
public void dispatcherTimer1_Tick(object Sender, EventArgs e)
{
label.Content = DateTime.Now.ToLongDateString();
label1.Content = DateTime.Now.ToString("HH:mm:ss");
}
public void dispatcherTimer2_Tick(object Sender, EventArgs e)
{
getWeather();
}
public void mainPageDisable()
{
label3.Visibility = Visibility.Hidden;
label4.Visibility = Visibility.Hidden;
label6.Visibility = Visibility.Hidden;
label8.Visibility = Visibility.Hidden;
label10.Visibility = Visibility.Hidden;
label11.Visibility = Visibility.Hidden;
}
public void getWeather()
{
string query = String.Format("http://weather.yahooapis.com/forecastrss?w=2972&u=c");
XmlDocument currData = new XmlDocument();
currData.Load(query);
XmlNamespaceManager dataMan = new XmlNamespaceManager(currData.NameTable);
dataMan.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode chan = currData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNodeList nodeList = currData.SelectNodes("/rss/channel/item/yweather:forecast", dataMan);
currTemp = chan.SelectSingleNode("item").SelectSingleNode("yweather:condition", dataMan).Attributes["temp"].Value;
currCond = chan.SelectSingleNode("item").SelectSingleNode("yweather:condition", dataMan).Attributes["text"].Value;
currHumid = chan.SelectSingleNode("yweather:atmosphere", dataMan).Attributes["humidity"].Value;
currWind = chan.SelectSingleNode("yweather:wind", dataMan).Attributes["chill"].Value;
location = chan.SelectSingleNode("yweather:location", dataMan).Attributes["city"].Value;
foreCond = chan.SelectSingleNode("item").SelectSingleNode("yweather:forecast", dataMan).Attributes["text"].Value;
foreHigh = chan.SelectSingleNode("item").SelectSingleNode("yweather:forecast", dataMan).Attributes["high"].Value;
foreLow = chan.SelectSingleNode("item").SelectSingleNode("yweather:forecast", dataMan).Attributes["low"].Value;
imgCode = chan.SelectSingleNode("item").SelectSingleNode("yweather:condition", dataMan).Attributes["code"].Value;
pubDate = chan.SelectSingleNode("item").SelectSingleNode("yweather:condition", dataMan).Attributes["date"].Value;
label3.Content = currTemp + " C";
label4.Content = currCond;
label6.Content = currHumid;
label8.Content = foreHigh + " C";
label10.Content = foreLow + " C";
label11.Content = "Last Updated: " + pubDate;
retrieveWeatherIconFromWeb();
//retrieveWeatherIconFromFolder();
image.Source = sourceImg;
if(sourceImg != null)
{
sourceImg = new BitmapImage();
}
}
private void retrieveWeatherIconFromFolder()
{
if (imgCode.Equals("3200"))
{
sourceImg = new BitmapImage(new Uri(sourceImg.BaseUri, "Images/na.png"));
}
else
{
sourceImg = new BitmapImage(new Uri(sourceImg.BaseUri, "Images/" + imgCode + ".png"));
}
}
private void retrieveWeatherIconFromWeb()
{
int bytesToRead = 100;
WebRequest req = WebRequest.Create(new Uri("http://l.yimg.com/a/i/us/we/52/" + imgCode + ".gif", UriKind.Absolute));
req.Timeout = -1;
WebResponse resp = req.GetResponse();
Stream respStr = resp.GetResponseStream();
BinaryReader reader = new BinaryReader(respStr);
MemoryStream memStr = new MemoryStream();
byte[] bytebuf = new byte[bytesToRead];
int bytesRead = reader.Read(bytebuf, 0, bytesToRead);
while (bytesRead > 0)
{
memStr.Write(bytebuf, 0, bytesRead);
bytesRead = reader.Read(bytebuf, 0, bytesToRead);
}
sourceImg.BeginInit();
memStr.Seek(0, SeekOrigin.Begin);
sourceImg.StreamSource = memStr;
sourceImg.EndInit();
}
}
}
|
8a603c9384a7b93b68942f282a2414654dd874d4
|
[
"C#"
] | 1
|
C#
|
kennyhong/HomeDisplay
|
35d50b69f8a4f01353e5c7a6c33e93ca41a956d1
|
d182921d3f6d329b47e9b7b0f0c9a86af7911c68
|
refs/heads/master
|
<repo_name>CauliFlowor/LearnTower<file_sep>/new.php
<?php
phpinfo();
public function hellp(){
echo 123;
}
public function help(){
echo 123;
}
public fuction test() {
}
public function test1() {
}
public funcion help3() {
}
<file_sep>/README.md
# LearnTower
学习使用Tower
|
fca8841d4e58cd9967f982337ceb4948b3f0d083
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
CauliFlowor/LearnTower
|
0138fb1c8ee7f0d9fbb3b62885c5795155738923
|
e5df3e8279c0dc753ccc0bbc063540b80d1f140e
|
refs/heads/master
|
<file_sep># course_starter
A shell script for quickly setting up all the files and folders required for running a new course.
<file_sep>#!/bin/bash
echo -e "\033[0;34mInitializing a new course! :)\033[0m"
# If you provide a first argument it will use it to make a parent directory
# and then create everything else inside that new directory. If not, it will
# create everything inside the current directory.
if [ $1 ]; then
mkdir $1
cd $1; else
:
fi
echo -e "\033[0;34mCreating subdirectories...\033[0m"
# setup basic directory structure
mkdir -p archive cal_files classlist data grades submissions handouts instructor_resources quizzes readings rubrics student_surveys inspiration student_networks notebooks tutorials
# if there is no lectures directory grab the slide template from github
if [ ! -d lectures/ ]; then
git clone --depth=1 --branch=master https://github.com/mclevey/talks.git && mv talks/ lectures/ && rm -rf lectures/.git; else
:
fi
echo -e "\033[0;34mCreating readme.md for course metadata...\033[0m"
# add a readme to record project metadata, etc.
if [ ! -f readme.md ]; then
echo "creating readme.md";
touch readme.md; else
:
fi
echo -e "\033[0;34mCreating files for the syllabus...\033[0m"
if [ ! -f syllabus.md ]; then
wget "https://raw.githubusercontent.com/mclevey/pandoc_templates/master/syllabus.md"; else
:
fi
echo -e "\033[0;34mAdding a generic course makefile...\033[0m"
if [ ! -f Makefile ]; then
wget "https://raw.githubusercontent.com/mclevey/pandoc_templates/master/make/teaching/Makefile"; else
:
fi
# git
echo -e "\033[0;34mChecking git...\033[0m"
if [ ! .git/ ]; then
echo -e "\033[0;34mInitializing git...\033[0m"
git init
touch .gitignore
echo "archive" >> .gitignore
echo ".Rhistory" >> .gitignore
echo ".Rapp.history" >> .gitignore
echo ".Rproj.user/" >> .gitignore
echo ".httr-oauth" >> .gitignore
echo "/*_cache/" >> .gitignore
echo "/cache/" >> .gitignore
echo "*.utf8.md" >> .gitignore
echo "*.knit.md" >> .gitignore
echo ".ipynb_checkpoints" >> .gitignore; else
:
fi
echo -e "\033[0;34mAll set!\033[0m \033[0;32mNow get to work!\033[0m"
touch todo.taskpaper
|
407afedda117a73e7ccad8369ffab9268b186244
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
mclevey/course_starter
|
8f3cc045bedfa7c6240712b49b6a88ca7dfefc30
|
14b5cf76f8032b8187d81240a3098c50acd7af32
|
refs/heads/master
|
<file_sep>[](https://gitter.im/s-atmech/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [](https://circleci.com/gh/Samsomyajit/s-atmech/tree/master) [](https://badge.fury.io/py/s-atmech)
<p align="center">
<img src="https://github.com/Samsomyajit/s-atmech/blob/master/Misc/logo.png">
</p>
# s-atmech
s-atmech is an independent Open Source, Deep Learning python library which implements attention mechanism as a RNN(Recurrent Neural Network) Layer as Encoder-Decoder system. The papers:[click_here1](https://arxiv.org/pdf/1508.04025.pdf)|[click_here2](https://arxiv.org/pdf/1409.0473.pdf) aimed to improve the sequence-to-sequence model in machine translation by aligning the decoder with the relevant input sentences and implementing Attention. The Flow of calculating Attention weights in Bahdanau Attention is shown below:<br>
<br>
<br>
After obtaining all of our encoder outputs, we can start using the decoder to produce outputs. At each time step of the decoder, we have to calculate the alignment score of each encoder output with respect to the decoder input and hidden state at that time step. The alignment score is the essence of the Attention mechanism, as it quantifies the amount of “Attention” the decoder will place on each of the encoder outputs when producing the next output.
The alignment scores for Bahdanau Attention are calculated using the hidden state produced by the decoder in the previous time step and the encoder outputs with the following equation:<br>
<br>
The decoder hidden state and encoder outputs will be passed through their individual Linear layer and have their own individual trainable weights. Thereafter, they will be added together before being passed through a <i>tanh</i>activation function. The decoder hidden state is added to each encoder output in this case. Lastly, the resultant vector from the previous few steps will undergo matrix multiplication with a trainable vector, obtaining a final alignment score vector which holds a score for each encoder output. After generating the alignment scores vector in the previous step, we can then apply a softmax on this vector to obtain the attention weights. The softmax function will cause the values in the vector to sum up to 1 and each individual value will lie between 0 and 1, therefore representing the weightage each input holds at that time step. After computing the attention weights in the previous step, we can now generate the context vector by doing an element-wise multiplication of the attention weights with the encoder outputs.due to the softmax function in the previous step, if the score of a specific input element is closer to 1 its effect and influence on the decoder output is amplified, whereas if the score is close to 0, its influence is drowned out and nullified. The context vector we produced will then be concatenated with the previous decoder output. It is then fed into the decoder RNN cell to produce a new hidden state and the process repeats itself from step 2. The final output for the time step is obtained by passing the new hidden state through a Linear layer, which acts as a classifier to give the probability scores of the next predicted word. Steps 2 to 4 are repeated until the decoder generates an End Of Sentence token or the output length exceeds a specified maximum length. This above is the entire process how Bhadanau Attention works.
# Next in Line:
This is still in alpha stage so we are planning to add a Luong Attention implementation which will be added by 2020. We are also developing a new attention algorithm for our library.
# Naming:
s-atmech actually is symbolic name for Sam's Attention Mechanism simple yet catchy! \_(^_^)_/
# Installation and Implementation:
To install s-atmech follow the steps:<br>
Install pip:
```
$ python get-pip.py
```
Install s-atmech via pip:
```
$ pip install s-atmech
```
For upgrade:
```
$ pip install --upgrade s-atmech
```
Implementation:
```python
>>> from s-atmech.AttentionLayer import AttentionLayer as atl
>>> from s-atmech import luong_EncoderRNN
>>> from s-atmech import luong_Attn
>>> from s-atmech import luong_DecoderRNN
```
# Developer Info:
Author: <NAME><br>
Author-email: <EMAIL><br>
Team: Bread and Code
# Required Libraries:
'numpy',
'pandas',
'tensorflow',
'matplotlib',
'scikit-learn',
'jupyter',
'pillow',
'nltk',
'pyYAML',
# LISCENSE:
```
MIT License
Copyright (c) 2019 <NAME>
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.
```
<file_sep>from s-atmech import bahdanau
from s-atmech import luong_EncoderRNN
from s-atmech import luong_Attn
from s-atmech import luong_DecoderRNN
<file_sep>"""
This layer module implements the luong decoder as a RNN layer thus concluding the attention mechanism.
by: <NAME>
"""
import torch
import logging
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
class luong_DecoderRNN(nn.Module):
def __init__(self, score_function, hidden_size, input_size, output_size,
n_layers, dropout , word_embedding_matrix, use_cuda):
super(LuongAttnDecoderRNN, self).__init__()
# Keep for reference
self.score_function = score_function
self.hidden_size = hidden_size
self.input_size = input_size
self.output_size = output_size
self.n_layers = n_layers
self.dropout = dropout
self.use_cuda = use_cuda
# Define layers
self.embedding = word_embedding_matrix
self.gru = nn.GRU(self.input_size, self.hidden_size, n_layers, dropout=self.dropout)
self.concat = nn.Linear(self.hidden_size * 2, self.hidden_size)
self.out = nn.Linear(self.hidden_size, self.output_size)
# Choose attention models
if score_function != 'none':
self.attn = Attn(score_function, hidden_size, use_cuda=use_cuda)
def forward(self, input_seq, last_hidden, encoder_outputs):
"""
input_seq : batch_size
hidden : hidden_size, batch_size
encoder_outputs : max input length, batch_size, hidden_size
"""
# Note: we run this one step at a time
# logging.debug(f"input_seq:\n{input_seq}")
# logging.debug(f"last_hidden:\n{last_hidden}")
# logging.debug(f"encoder_outputs:\n{encoder_outputs}")
batch_size = input_seq.size(0)
# (batch size, hidden_size)
embedded = self.embedding(input_seq)
# (1, batch size, input_size) add another dimension so that it works with
# the GRU
embedded = embedded.view(1, batch_size, self.input_size) # S=1 x B x N
logging.debug(f"embedded:\n{embedded}")
# Get current hidden state from input word and last hidden state
rnn_output, hidden = self.gru(embedded, last_hidden)
logging.debug(f"rnn_output:\n{rnn_output}")
logging.debug(f"hidden:\n{hidden}")
# Calculate attention from current RNN state and all encoder outputs;
# apply to encoder outputs to get weighted average
# batch size, max input length
attn_weights = self.attn(rnn_output, encoder_outputs)
logging.debug(f"attn_weights:\n{attn_weights}")
# (batch_size, 1, max input length) @ batch_size, max input length, hidden size
# note that we use this convention here to take advantage of the bmm function
context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x S=1 x N
# Attentional vector using the RNN hidden state and context vector
# concatenated together (Luong eq. 5)
rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N
context = context.squeeze(1) # B x S=1 x N -> B x N
concat_input = torch.cat((rnn_output, context), 1)
concat_output = F.tanh(self.concat(concat_input))
# Finally predict next token (Luong eq. 6, without fftmax)
output = self.out(concat_output)
# Return final output, hidden state, and attention weights (for visualization)
return output, hidden, attn_weights
<file_sep>s-atmech
s-atmech is an independent Open Source, Deep Learning python library which implements attention mechanism as a RNN(Recurrent Neural Network) Layer as Encoder-Decoder system. We are still in development stage so we have just made use of the Bahdanau Attention, commonly referred to as Additive Attention, refer to this paper. The paper aimed to improve the sequence-to-sequence model in machine translation by aligning the decoder with the relevant input sentences and implementing Attention. The Flow of calculating Attention weights in Bahdanau Attention is shown below:
Attention Weights
After obtaining all of our encoder outputs, we can start using the decoder to produce outputs. At each time step of the decoder, we have to calculate the alignment score of each encoder output with respect to the decoder input and hidden state at that time step. The alignment score is the essence of the Attention mechanism, as it quantifies the amount of “Attention” the decoder will place on each of the encoder outputs when producing the next output.
The alignment scores for Bahdanau Attention are calculated using the hidden state produced by the decoder in the previous time step and the encoder outputs with the following equation:
Score Equation
The decoder hidden state and encoder outputs will be passed through their individual Linear layer and have their own individual trainable weights. Thereafter, they will be added together before being passed through a tanhactivation function. The decoder hidden state is added to each encoder output in this case. Lastly, the resultant vector from the previous few steps will undergo matrix multiplication with a trainable vector, obtaining a final alignment score vector which holds a score for each encoder output. After generating the alignment scores vector in the previous step, we can then apply a softmax on this vector to obtain the attention weights. The softmax function will cause the values in the vector to sum up to 1 and each individual value will lie between 0 and 1, therefore representing the weightage each input holds at that time step. After computing the attention weights in the previous step, we can now generate the context vector by doing an element-wise multiplication of the attention weights with the encoder outputs.due to the softmax function in the previous step, if the score of a specific input element is closer to 1 its effect and influence on the decoder output is amplified, whereas if the score is close to 0, its influence is drowned out and nullified. The context vector we produced will then be concatenated with the previous decoder output. It is then fed into the decoder RNN cell to produce a new hidden state and the process repeats itself from step 2. The final output for the time step is obtained by passing the new hidden state through a Linear layer, which acts as a classifier to give the probability scores of the next predicted word. Steps 2 to 4 are repeated until the decoder generates an End Of Sentence token or the output length exceeds a specified maximum length. This above is the entire process how Bhadanau Attention works.
Next in Line:
This is still in alpha stage so we are planning to add a Luong Attention implementation which will be added by 2020. We are also developing a new attention algorithm for our library.
Naming:
s-atmech actually is symbolic name for Sam's Attention Mechanism simple yet catchy! _(^^)/
Installation and Implementation:
To install s-atmech follow the steps:
Install pip:
$ python get-pip.py
Install s-atmech via pip:
$ pip install s-atmech
For upgrade:
$ pip install --upgrade s-atmech
Implementation:
>>> from s-atmech.AttentionLayer import AttentionLayer as atl
Developer Info:
Author: <NAME>
Author-email: <EMAIL>
Team: Bread and Code
Required Libraries:
'numpy', 'pandas', 'tensorflow', 'matplotlib', 'scikit-learn', 'jupyter', 'pillow', 'nltk', 'pyYAML',
LISCENSE:
MIT License
Copyright (c) 2019 <NAME>
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.
<file_sep>numpy>=1.16.4
pandas>=0.22.0
tensorflow
torch
matplotlib>=3.1.2
scikit-learn>=0.22
jupyter>=1.0.0
Pillow>=6.1.0
nltk>=3.4.5
pyYAML>=5.2
scipy>=1.3.0
s-atmech
<file_sep>from s-atmech import AttentionLayer
<file_sep>"""
This module implements the Luong Attention Mechanism.
by: <NAME>
"""
import torch
import logging
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
class luong_Attn(nn.Module):
def __init__(self, method, hidden_size, use_cuda=False):
super().__init__()
self.method = method
self.hidden_size = hidden_size
self.use_cuda = use_cuda
if self.method == 'general':
self.attn = nn.Linear(self.hidden_size, hidden_size)
elif self.method == 'concat':
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))
def forward(self, hidden, encoder_outputs):
"""
hidden : 1, batch_size, hidden_size
encoder_outputs : max input length, batch_size, hidden_size
"""
# max_len = encoder_outputs.size(0)
# this_batch_size = encoder_outputs.size(1)
attn_energies = torch.bmm(self.attn(hidden).transpose(1, 0), encoder_outputs.permute(1, 2, 0))
# Batch size, 1, max input length
return F.softmax(attn_energies)
def score(self, hidden, encoder_output):
if self.method == 'general':
energy = self.attn(encoder_output).view(-1)
energy = hidden.view(-1).dot(energy)
return energy
<file_sep>"""
This is the Encoder RNN layer for implementing the Luong attention courtesy:https://arxiv.org/pdf/1508.04025.pdf
the code is made by team Bread and Code's <NAME> for s-atmech
"""
import torch
import logging
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
class luong_EncoderRNN(nn.Module):
def __init__(self , hidden_size , input_size , n_layers , dropout , word_embedding_matrix , rnn_cell , use_cuda)
super().__init__()
self.hidden_size = hidden_size
self.input_size = input_size
self.n_layers = n_layers
self.dropout = dropout
self.word_embedding_matrix = word_embedding_matrix
self.rnn_cell = rnn_cell
self.use_cuda = use_cuda
if rnn.cell == "GRU"
self.rnn = nn.GRU(input_size, hidden_size, n_layers, dropout=dropout, bidirectional=True)
def forward(self, input_seqs, hidden, input_lengths)
"""
input_seqs : (Max input length, batch_size)
input_lengths: (batch_size)
"""
embedded = self.embedding(input_seqs)
packed = pack_padded_sequence(embedded, input_lengths)
outputs, hidden = self.rnn(packed, hidden)
outputs, output_lengths = pad_packed_sequence(outputs)
# Max input_lenghts, batch_size, hidden_size, we add backward and forward
# hidden states together
outputs = outputs[:, :, :self.hidden_size] + outputs[:, :, self.hidden_size:]
# get the forward and backward hidden states
hidden_layers = []
for i in range(self.n_layers):
hidden_layers.append((hidden[i * 2, :, :] + hidden[(i * 2) + 1, :, :]).unsqueeze(0))
return outputs, torch.cat(hidden_layers, 0)
def init_hidden(self, batch_size):
hidden = Variable(torch.zeros(self.n_layers * 2, batch_size, self.hidden_size))
if self.use_cuda: hidden = hidden.cuda()
return hidden
|
1fadcd05cb577d334e096057a772e4c48e3d6e26
|
[
"Markdown",
"Python",
"Text"
] | 8
|
Markdown
|
Samsomyajit/s-atmech
|
65e937294a498c2e7c46a825d98e8edd015dd7d5
|
75e2b7dc12383a0a25379475828ec741dd8660d0
|
refs/heads/master
|
<repo_name>Tanooj0902/product_catalog<file_sep>/app/javascript/catalog/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ModalModule } from 'ngx-bootstrap';
import { CurrencyPipe } from '@angular/common';
import { InfiniteScrollModule } from 'ngx-infinite-scroll'
import { AppComponent } from './app.component';
import { ProductsComponent } from './products/products.component';
import { ProductService } from './products/shared/product.service';
import { ROUTES } from './app.routes';
import { AddEditProductComponent } from './products/add-edit-product.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToasterModule } from 'angular2-toaster';
@NgModule({
declarations: [
AppComponent,
ProductsComponent,
AddEditProductComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(ROUTES),
ModalModule.forRoot(),
InfiniteScrollModule,
BrowserAnimationsModule,
ToasterModule
],
providers: [ ProductService, CurrencyPipe ],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/spec/requests/products_spec.rb
require 'rails_helper'
RSpec.describe 'Products API', type: :request do
# initialize test data
let!(:product) { create :product }
let(:product_id) { product.id }
# Test suite for GET /api/v1/products
describe 'GET /api/v1/products' do
# make HTTP get request before each example
before { get '/api/v1/products' }
it 'returns products' do
expect(json['products']).not_to be_empty
expect(json['products'].size).to be > 0
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for /api/v1/products?page=2 (pagination)
describe 'GET /api/v1/products?page=2' do
let!(:product) { create_list :product, 20}
before { get '/api/v1/products?page=2' }
it 'returns second page 10 products' do
expect(json['products']).not_to be_empty
expect(json['products'].size).to eq 10
expect(json['meta']['total_records']).to eq 20
expect(json['meta']['total_pages']).to eq 2
expect(json['meta']['current_page']).to eq 2
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for GET /api/v1/product/:id
describe 'GET /api/v1/products/:id' do
before { get "/api/v1/products/#{product_id}" }
context 'when the record exists' do
it 'returns the product' do
expect(json['product']).not_to be_empty
expect(json['product']['id']).to eq(product_id)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when the record does not exist' do
let(:product_id) { "not_exist" }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns a not found message' do
expect(response.body).to match(/Resource not found/)
end
end
end
# Test suite for POST /api/v1/products
describe 'POST /api/v1/products' do
context 'when the request is valid' do
let(:product) { build :product }
let(:valid_attributes) { { product: { name: product.name, description: product.description, price: product.price } } }
before { post '/api/v1/products', valid_attributes }
it 'creates a product' do
expect(Product.find_by(name: product.name)).not_to be_nil
end
it 'return a product' do
expect(json['product']['name']).to eq(product.name)
expect(json['product']['description']).to eq(product.description)
expect(json['product']['price']).to eq(product.price.to_f)
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/api/v1/products', product: { name: 'Product name' } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
parsed_response = JSON.parse(response.body)
expect(parsed_response['errors']['description']).to eq(["can't be blank"])
end
end
end
# Test suite for PUT /api/v1/products/:id
describe 'PUT /api/v1/products/:id' do
context 'when the record exists' do
before { put "/api/v1/products/#{product_id}", product: { name: 'Updated name' } }
it 'updates the record' do
expect(response.body).not_to be_empty
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
it 'should update name' do
expect(Product.find(product_id).name).to eq('Updated name')
end
end
context 'when the record not exists' do
before { put '/api/v1/products/not_exist', product: { name: 'Updated name' } }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
end
end
# Test suite for DELETE /products/:id
describe 'DELETE /api/v1/products/:id' do
context 'when the record exists' do
before { delete "/api/v1/products/#{product_id}" }
it 'delete record' do
expect(Product.find_by(id: product_id)).to be_nil
end
end
context 'when the record not exists' do
before { delete '/api/v1/products/not_exist' }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
end
end
end
<file_sep>/app/services/api/v1/error_service.rb
# frozen_string_literal: true
module Api
module V1
module ErrorService
def self.handle(error)
Api::V1::ErrorService::MessageMapper.send(error.class.name.demodulize.underscore, error)
end
class ApplicationError < StandardError
attr_reader :message, :instance, :klass
def initialize(payload = {})
@message = payload[:message]
@instance = payload[:instance]
@klass = payload[:klass]
end
def instance_errors
return unless instance.present?
instance.errors.messages.each_with_object({}) do |(attribute, messages), result|
result[attribute] = messages.to_sentence
result
end.to_json
end
end
class RecordInvalidError < ApplicationError; end
class RecordNotFoundError < ApplicationError; end
class MessageMapper < ActiveModelSerializers::Model
attr_accessor :code, :message, :status
def self.message_provider(key, interpolation_args = {})
I18n.t "api.errors.#{key}", interpolation_args.delete_if { |_k, v| v.nil? }
end
Api::V1::ErrorService::ApplicationError.descendants.each do |application_error_class|
error_class = application_error_class.name.demodulize.underscore
define_singleton_method error_class do |error|
new code: message_provider("#{error_class}.code"),
message: message_provider("#{error_class}.message",
message: error.message,
instance_errors: error.instance_errors,
klass: error.klass),
status: message_provider("#{error_class}.status")
end
end
def self.params_error(message)
new code: message_provider('params_error.code'),
message: message_provider('params_error.message', message: message),
status: message_provider('params_error.status')
end
def self.not_found
new code: message_provider('not_found_error.code'),
message: message_provider('not_found_error.message'),
status: message_provider('not_found_error.status')
end
end
end
end
end
<file_sep>/app/javascript/catalog/app/products/products.component.ts
import { Component, OnInit } from '@angular/core';
import { ProductService } from './shared/product.service';
import { Product } from './shared/product.model';
import { ToasterService } from 'angular2-toaster';
import productsTemplateString from './products.component.html';
@Component({
selector: 'app-products',
template: productsTemplateString
})
export class ProductsComponent implements OnInit {
products: Product[] = [];
product: Product;
page: number = 1;
total_pages: number;
constructor(private productService: ProductService, private toasterService: ToasterService) {
this.toasterService = toasterService;
}
ngOnInit() {
this.productList();
}
productList() {
this.productService.getProducts(this.page)
.subscribe(response => {
this.products = this.products.concat(response.products);
this.total_pages = response.meta.total_pages;
});
}
showProductDetail(product) {
this.product = product;
}
destroyProduct(product) {
this.productService.deleteProduct(product)
.subscribe(response => {
this.resetList();
this.product = null;
this.popToast('Product deleted successfully');
});
}
onScroll() {
if(this.page < this.total_pages) {
this.page = this.page + 1;
this.productList();
}
}
resetList() {
this.products = [];
this.page = 1;
this.productList();
}
popToast(message) {
this.toasterService.pop('success', '', message);
}
}
<file_sep>/app/javascript/catalog/app/products/shared/product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Product } from './product.model';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class ProductService {
private options;
private productApiUrl = '/api/v1/products';
constructor(private http: Http) {
let headers = new Headers({ 'Content-Type': 'application/json'});
this.options = new RequestOptions({ headers: headers });
}
saveProduct(product: Product): Observable<Product> {
let body = { product: product };
return this.http
.post(this.productApiUrl, JSON.stringify(body), this.options)
.map(response => response.json() as Product)
.catch((error:any) => Observable.throw(error.json().errors || 'Server error'));
}
getProducts(page): Observable<any> {
let url = `${this.productApiUrl}?page=${page}`;
return this.http
.get(url)
.map(response => response.json());
}
updateProduct(product: Product): Observable<Product> {
let url = `${this.productApiUrl}/${product.id}`;
let body = { product: product };
return this.http
.put(url, JSON.stringify(body), this.options)
.map(response => response.json() as Product)
.catch((error:any) => Observable.throw(error.json().errors || 'Server error'));
}
deleteProduct(product: Product): Observable<Product> {
let url = `${this.productApiUrl}/${product.id}`;
return this.http
.delete(url, this.options)
.map(response => response.json());
}
}
<file_sep>/config/routes.rb
Rails.application.routes.draw do
namespace :api, defaults: { format: 'json' } do
namespace :v1 do
resources :products
end
end
root to: 'application#index'
get:'*unmatched_route', to: 'application#index'
end
<file_sep>/app/controllers/api/v1/products_controller.rb
class Api::V1::ProductsController < Api::V1::BaseController
before_action :set_product, only: %i[show update destroy]
def index
@products = Product.all.page(params[:page]).per(10)
render json: @products, status: :ok, meta: meta_hash
end
def show
render json: @product, status: :ok
end
def create
@product = Product.new(product_params)
if @product.save
render json: @product, status: :created
else
render json: { errors: @product.errors }, status: :unprocessable_entity
end
end
def update
if @product.update(product_params)
render json: @product, status: :ok
else
render json: { errors: @product.errors }, status: :unprocessable_entity
end
end
def destroy
@product.destroy!
head :no_content
end
private
def product_params
params.require(:product).permit(:name, :description, :price)
end
def set_product
@product = Product.find(params[:id])
end
def meta_hash
{
total_pages: @products.total_pages,
total_records: @products.total_count,
current_page: @products.current_page
}
end
end
<file_sep>/app/serializers/api/v1/product_serializer.rb
class Api::V1::ProductSerializer < Api::V1::ApplicationSerializer
attributes :id, :name, :description, :price, :price_currency_symbol, :price_currency_code
def price
object.price.to_f
end
def price_currency_symbol
object.price.currency.symbol
end
def price_currency_code
object.price.currency.iso_code
end
end
<file_sep>/app/javascript/catalog/app/products/add-edit-product.component.ts
import { Component, ViewChild, Output, EventEmitter, Input } from '@angular/core';
import { ProductService } from './shared/product.service';
import { Product } from './shared/product.model';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { NgForm } from '@angular/forms';
import { ToasterService } from 'angular2-toaster';
import addEditProductTemplateString from'./add-edit-product.component.html';
@Component({
selector: 'app-add-edit-product',
template: addEditProductTemplateString
})
export class AddEditProductComponent {
@Input() updatedProduct;
product: Product;
errorMessage: Object = {};
pageValues: Object = {};
@ViewChild('newEditProductModal') public newEditProductModal:ModalDirective;
@Output() resetList:EventEmitter<object[]> = new EventEmitter();
@Output() updatedProductChange:EventEmitter<object> = new EventEmitter();
constructor(private productService: ProductService, private toasterService: ToasterService) {
this.product = new Product();
this.toasterService = toasterService;
}
onSubmit(productForm) {
this.product.id ? this.updateProduct(productForm) : this.saveProduct(productForm);
}
saveProduct(productForm: NgForm) {
this.productService.saveProduct(this.product)
.subscribe(response => {
this.refresh(response, productForm);
productForm.reset();
this.popToast('Product added successfully');
},
error => {
this.errorMessage = <any>error;
});
}
updateProduct(productForm: NgForm) {
this.productService.updateProduct(this.product)
.subscribe(response => {
this.refresh(response, productForm);
this.popToast('Product updated successfully');
},
error => {
this.errorMessage = <any>error;
});
}
public showNewProductModal():void {
this.product = new Product();
this.errorMessage = {};
this.pageValues = { title: 'New Product', btnTitle: 'Add Product'};
this.newEditProductModal.show();
}
public hideNewEditProductModal(productForm: NgForm):void {
this.newEditProductModal.hide();
productForm.reset();
}
public showEditProductModal(product):void {
this.pageValues = { title: 'Edit Product', btnTitle: 'Update Product' };
this.errorMessage = {};
this.product = Object.assign({}, product);
this.newEditProductModal.show();
}
refresh(response, productForm) {
this.product = response;
this.updatedProductChange.emit(response.product);
this.resetList.emit(null);
this.hideNewEditProductModal(productForm);
}
popToast(message) {
this.toasterService.pop('success', '', message);
}
}
<file_sep>/app/javascript/catalog/app/app.routes.ts
import { RouterModule, Routes } from '@angular/router';
import { ProductsComponent } from './products/products.component';
import { AddEditProductComponent } from './products/add-edit-product.component';
export const ROUTES: Routes = [
{
path: '',
redirectTo: 'products',
pathMatch: 'full'
},
{
path: 'products',
component: ProductsComponent
},
{
path: 'products/new',
component: AddEditProductComponent,
pathMatch: 'full'
}
];
<file_sep>/app/models/product.rb
class Product < ActiveRecord::Base
monetize :price_cents
validates :name, :description, presence: true
validates :name, uniqueness: true
default_scope { order('created_at DESC')}
end
<file_sep>/spec/factories/product.rb
FactoryGirl.define do
factory :product do
# Adding timestamp so there are no repeated names.
# While this does not guarantee uniq name but works for now.
name { "#{Faker::Lorem.word}_#{Time.now.to_f}" }
description { Faker::Lorem.word }
price { Faker::Number.number(2) }
end
end
<file_sep>/app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < Api::BaseController
rescue_from ActiveRecord::RecordNotFound,
ActionController::RoutingError,
ActiveRecord::RecordInvalid,
with: :respond_with_404
rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception|
message = "#{parameter_missing_exception.param}: parameter is missing or incorrect"
error = Api::V1::ErrorService::MessageMapper.params_error(message)
render json: error, serializer: Api::V1::ErrorSerializer, root: 'errors', status: :unprocessable_entity
end
rescue_from Api::V1::ErrorService::ApplicationError, with: :render_application_error
protected
def render_application_error(exception)
render_error Api::V1::ErrorService.handle(exception)
end
def render_error(error)
render json: error, root: 'errors', serializer: Api::V1::ErrorSerializer, status: error.status
end
def respond_with_404
error = Api::V1::ErrorService::MessageMapper.not_found
render json: error, root: 'errors', serializer: Api::V1::ErrorSerializer, status: :not_found
end
end
<file_sep>/app/serializers/api/v1/error_serializer.rb
# frozen_string_literal: true
class Api::V1::ErrorSerializer < ActiveModel::Serializer
attributes :code, :message
def code
if object.respond_to?(:each)
object.map(&:code).uniq.join(',')
else
object.code
end
end
def message
if object.respond_to?(:each)
object.map(&:message).uniq.join(',')
else
object.message
end
end
end
|
3fda438b89bbd0b88d820a89060134e9de642d81
|
[
"TypeScript",
"Ruby"
] | 14
|
TypeScript
|
Tanooj0902/product_catalog
|
9b17ca54817dc36676ca84fd523a5d1ae46dd40c
|
768906dbfae85c3b570a79d6397d182739d4fc70
|
refs/heads/master
|
<file_sep><?php
namespace Nebelfitz\MathTraining\FusionObjects;
use Nebelfitz\MathTraining\Domain\AdditionTask;
use Nebelfitz\MathTraining\Domain\DivisionTask;
use Nebelfitz\MathTraining\Domain\DivisionWithRemainderTask;
use Nebelfitz\MathTraining\Domain\MultiplicationTask;
use Nebelfitz\MathTraining\Domain\SubstractionTask;
use Neos\Fusion\FusionObjects\AbstractFusionObject;
class ArtithmeticTaskGeneratorImplementation extends AbstractFusionObject
{
public function evaluate()
{
$number = $this->fusionValue('number') ?? 20;
$maximalOperand = $this->fusionValue('maximalOperand') ?? 10;
$elementaryArithmeticTypes = $this->fusionValue('elementaryArithmeticTypes') ?? ['addition'];
$additionalFactors = $this->fusionValue('additionalFactors') ?? [1];
$result = [];
while (count($result) < $number) {
$seed1 = random_int(1, $maximalOperand);
$seed2 = random_int(1, $maximalOperand);
$hash = $seed1 . ':' . $seed2;
if (array_key_exists($hash, $result)) {
continue;
}
$factorPos1 = random_int(0, count($additionalFactors) -1 );
$factor1 = (int)$additionalFactors[$factorPos1];
if ($factor1 <> 1) {
$seed1 *= $factor1;
}
$factorPos2 = random_int(0, count($additionalFactors) -1 );
$factor2 = (int)$additionalFactors[$factorPos2];
if ($factor2 <> 1) {
$seed2 *= $factor2;
}
$typePos = random_int(0, count($elementaryArithmeticTypes) -1 );
$type = $elementaryArithmeticTypes[$typePos];
switch ($type) {
case 'addition':
$task = new AdditionTask($seed1, $seed2);
break;
case 'subtraction':
$task = new SubstractionTask($seed1, $seed2);
break;
case 'multiplication':
$task = new MultiplicationTask($seed1, $seed2);
break;
case 'division':
$task = new DivisionTask($seed1, $seed2);
break;
case 'divisionWithRemainder':
$task = new DivisionWithRemainderTask($seed1, $seed2);
break;
default:
$task = null;
}
$result[$hash] = $task;
}
return $result;
}
}
<file_sep><?php
namespace Nebelfitz\MathTraining\Domain;
use phpDocumentor\Reflection\DocBlockFactoryInterface;
abstract class ElementaryMathematicTask
{
protected $firstOperand;
protected $secondOperand;
/**
* ElementaryMathematicTask constructor.
* @param int $firstOperand
* @param int $secondOperand
*/
public function __construct(int $seed1, int $seed2)
{
$this->firstOperand = $seed1;
$this->secondOperand = $seed2;
}
abstract public function getSymbol(): string;
abstract public function getResult(): float;
public function getFirstOperand(): int
{
return $this->firstOperand;
}
public function getSecondOperand(): int
{
return $this->secondOperand;
}
public function getFormulaWithoutResult():string
{
return $this->formatNumber($this->getFirstOperand()) . ' ' . $this->getSymbol() . ' ' . $this->formatNumber($this->getSecondOperand()) . ' =';
}
public function getFormulaWithResult():string
{
return $this->getFormulaWithoutResult() . ' ' . $this->formatNumber($this->getResult());
}
public function __toString():string
{
return $this->getFormulaWithResult();
}
protected function formatNumber($number): string
{
return number_format($number, 0, ',', '.');
}
}
<file_sep><?php
namespace Nebelfitz\MathTraining\Domain;
class MultiplicationTask extends ElementaryMathematicTask
{
public function getSymbol(): string
{
return '×';
}
public function getResult(): float
{
return $this->getFirstOperand() * $this->getSecondOperand();
}
}
<file_sep># Nebelfitz.MathTraining
just some code to generate math tasks for scool training. Probably useless for anyone except me.
<file_sep><?php
namespace Nebelfitz\MathTraining\Domain;
class DivisionTask extends ElementaryMathematicTask
{
public function __construct(int $seed1, int $seed2)
{
parent::__construct($seed1 * $seed2, $seed1);
}
public function getSymbol(): string
{
return '÷';
}
public function getResult(): float
{
return $this->getFirstOperand() / $this->getSecondOperand();
}
}
<file_sep><?php
namespace Nebelfitz\MathTraining\Domain;
class DivisionWithRemainderTask extends DivisionTask
{
public function __construct(int $seed1, int $seed2)
{
parent::__construct($seed1, $seed1);
$remainder = random_int(0, $seed2 - 1);
$this->firstOperand += $remainder;
}
public function getFormulaWithResult():string
{
$result = $this->getResult();
$integerResult = floor($result);
$remainder = (int)(($result - $integerResult) * $this->getSecondOperand());
if ($remainder) {
return $this->getFormulaWithoutResult() . ' ' . $this->formatNumber($integerResult) . ' R ' . $this->formatNumber($remainder);
} else {
return parent::getFormulaWithResult();
}
}
}
|
6db26fe46d446c0b939aa4f8de3d490e1c86edbc
|
[
"Markdown",
"PHP"
] | 6
|
PHP
|
mficzel/Nebelfitz.MathTraining
|
f42a3fa2c15da83832f8edc709ed8dfea2697e3a
|
d4fafe4c51b7436c8f2dc3289a69a32b2778c57a
|
refs/heads/master
|
<repo_name>imaniah/tugas1-blog<file_sep>/main.php
<h2>Halo. Selamat Datang Author <?php echo $_SESSION['author_name']; ?></h2><file_sep>/inc/config.php
<? php
define('URL', 'http://localhost/tugas1-blog/');
define('ASSET', URL. 'layout/assets/');
require_once "vendor/autoload.php";<file_sep>/photos_tampil.php
<h2 align="center">DAFTAR PHOTOS</h2>
<button><a href="index.php?page=photos_input"style="color: black;">Tambah</a></button>
<?php
require_once "app/Photos.php";
$photos = new App\Photos();
$rows = $photos->tampil();
?>
<table align="center">
<tr align="center" style="background-color: #EEE8AA">
<td>No</td>
<td>Date</td>
<td>Title</td>
<td>Text</td>
<td>Title Post</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr>
<td><?php echo $row['photo_id']; ?></td>
<td><?php echo $row['photo_date']; ?></td>
<td><?php echo $row['photo_title']; ?></td>
<td><?php echo $row['photo_text']; ?></td>
<td><?php echo $row['post_title']; ?></td>
<td><a href="index.php?page=photos_edit&id=<?php echo $row['photo_id']; ?>";>Edit</a></td>
<td><a href="index.php?page=photos_proses&delete-id=<?php echo $row['photo_id']; ?>">Delete</a></td>
</tr>
<?php } ?>
</table>
<br>
<br>
<br>
<br>
|
fcc44b0bd3f2b220361130ff041a5eec51581064
|
[
"PHP"
] | 3
|
PHP
|
imaniah/tugas1-blog
|
24e9b5de6dc5fa613c5a62bc16246c2ab01615c7
|
ce5f2a0ad1aacadb62b9c8c879d387ac7dcb90bc
|
refs/heads/master
|
<repo_name>alexkindel/ak-vec2<file_sep>/__tests__/vec2.test.ts
it('adds 1 + 2 to equal 3 in JavaScript', () => {
const sum = (a: number, b: number): number => a + b;
expect(sum(1, 2)).toBe(3);
});
<file_sep>/package.json
{
"name": "ak-vec2",
"version": "1.0.0",
"description": "A full-featured two-dimensional vector.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/alexkindel/ak-vec2.git"
},
"keywords": [
"2d-vector",
"vector",
"2d",
"geometry"
],
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"bugs": {
"url": "https://github.com/alexkindel/ak-vec2/issues"
},
"homepage": "https://github.com/alexkindel/ak-vec2#readme",
"devDependencies": {
"@types/jest": "^23.3.9",
"jest": "^23.6.0",
"ts-jest": "^23.10.4",
"typescript": "^3.1.6"
},
"jest": {
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfigFile": "tsconfig.json"
}
},
"testMatch": [
"**/__tests__/*.+(ts|tsx|js)"
]
}
}
<file_sep>/README.md
# ak-vec2
A full-featured two-dimensional [vector](https://en.wikipedia.org/wiki/Euclidean_vector).
<file_sep>/lib/index.ts
export { Vec2 } from './vec2';
|
a0d4b8580aaa247867dc50b1619f7d1550e69623
|
[
"Markdown",
"JSON",
"TypeScript"
] | 4
|
TypeScript
|
alexkindel/ak-vec2
|
83810b9bb2e238d7feae51d3333460f1bea383f8
|
b72ad0f78297a7c3f7852acda451a289b6948eb5
|
refs/heads/master
|
<repo_name>mdlmdel/blog-app-api-mongoose<file_sep>/tests/test-blog-posts.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const faker = require('faker');
const mongoose = require('mongoose');
// Specify "should" syntax with chai throughout
const should = chai.should();
const {DATABASE_URL} = require('../config');
const {BlogPost} = require('../models');
const {closeServer, runServer, app} = require('../server');
const {TEST_DATABASE_URL} = require('../config');
chai.use(chaiHttp);
// Use Faker.js library to simplify creating test data.
// It generates placeholder values for different fields that we can put in mongo
function seedBlogPostData() {
console.info('seed the database');
const seedData = [];
for (let i=1; i<=10; i++) {
seedData.push({
author: {
firstName: faker.name.firstName(),
lastName: faker.name.lastName()
},
title: faker.lorem.sentence(),
content: faker.lorem.text()
});
}
// This will return a promise
return BlogPost.insertMany(seedData);
}
// Tear down database and then add "describe" blocks
|
6005ce089262aab14a04ac3858b90a4ed65b9a99
|
[
"JavaScript"
] | 1
|
JavaScript
|
mdlmdel/blog-app-api-mongoose
|
a0f24399a3b781e396f1a327aacc6d9bc005fdf2
|
36f7fb8182362606ab069fee88dc4596496eb7ad
|
refs/heads/main
|
<repo_name>SAV2809/stm32f103c8t6-bluepill<file_sep>/тестовое задание/v1.01/Core/Src/usart.c
/**
******************************************************************************
* @file usart.c
* @brief This file provides code for the configuration
* of the USART instances.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usart.h"
#include "adc.h"
/* USER CODE BEGIN 0 */
/* Private variables ---------------------------------------------------------*/
uint8_t UART_RX_Byte=0;
uint8_t UART_RX_Byte_huart2=0;
TStruct_Uart_State Uart_State;
uint8_t buf_huart2[2];
uint8_t val_adc[2];
/* USER CODE END 0 */
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
/* USART1 init function */
void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/* USART2 init function */
void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspInit 0 */
/* USER CODE END USART1_MspInit 0 */
/* USART1 clock enable */
__HAL_RCC_USART1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART1 GPIO Configuration
PA9 ------> USART1_TX
PA10 ------> USART1_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USART1 interrupt Init */
HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspInit 1 */
/* USER CODE END USART1_MspInit 1 */
}
else if(uartHandle->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspInit 0 */
/* USER CODE END USART2_MspInit 0 */
/* USART2 clock enable */
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USART2 interrupt Init */
HAL_NVIC_SetPriority(USART2_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(USART2_IRQn);
/* USER CODE BEGIN USART2_MspInit 1 */
/* USER CODE END USART2_MspInit 1 */
}
}
void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspDeInit 0 */
/* USER CODE END USART1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART1_CLK_DISABLE();
/**USART1 GPIO Configuration
PA9 ------> USART1_TX
PA10 ------> USART1_RX
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10);
/* USART1 interrupt Deinit */
HAL_NVIC_DisableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspDeInit 1 */
/* USER CODE END USART1_MspDeInit 1 */
}
else if(uartHandle->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspDeInit 0 */
/* USER CODE END USART2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART2_CLK_DISABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3);
/* USART2 interrupt Deinit */
HAL_NVIC_DisableIRQ(USART2_IRQn);
/* USER CODE BEGIN USART2_MspDeInit 1 */
/* USER CODE END USART2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/** ****************************************************************************
* @brief начальная инициализация состояния uart1
* @retval void
*******************************************************************************/
void uart_init_state_settings()
{
Uart_State.Wait_Command=WAIT_NULL_COMMAND;
HAL_UART_Receive_IT(&huart1, &UART_RX_Byte, 1);
Uart_State.Queue_Status_Uart=QUEUE_STATE_EMPTY;
//HAL_UART_Receive_IT(&huart2, &UART_RX_Byte_huart2, 2);
}
/** ****************************************************************************
* @brief callback ф-ия прерывания по приёму
* @retval void
*******************************************************************************/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart1)
{
if (Uart_State.Wait_Command==WAIT_REGULAR_COMMAND) //ждём регулярную команду
{
uart_take_command();
Uart_State.Wait_Command=WAIT_NULL_COMMAND;
}
else if (Uart_State.Wait_Command==WAIT_NULL_COMMAND) //проверка на первый ноль байт
{
if(UART_RX_Byte==0)
{
Uart_State.Wait_Command=WAIT_REGULAR_COMMAND;
Uart_State.Time_Out=100;
}
else {uart_handler_error_first_byte();}
}
HAL_UART_Receive_IT(&huart1, &UART_RX_Byte, 1);
}
if(huart == &huart2)
{
}
}
/** ****************************************************************************
* @brief таймаут на приём регулярной команды
* @retval void
*******************************************************************************/
void uart_timeout()
{
if (Uart_State.Wait_Command==WAIT_REGULAR_COMMAND)
{
if (Uart_State.Time_Out) Uart_State.Time_Out--;
else Uart_State.Wait_Command=WAIT_NULL_COMMAND;
}
}
/** ****************************************************************************
* @brief функция доступа к HAL_UART_Receive_IT
* @retval void
*******************************************************************************/
uint8_t HAL_UART_Receive_IT_user (UART_HandleTypeDef *huart)
{
if(huart == &huart1)
{
HAL_UART_Receive_IT(&huart1, &UART_RX_Byte, 1);
}
return 1;
}
/** ****************************************************************************
* @brief возвращает первую в очереди команду
* @retval TStruct_Uart_Command Uart_State.Queue_Command
*******************************************************************************/
TStruct_Uart_Command uart_get_Command()
{
/*
if (Uart_State.Command_Active_Cnt==0)
{
while(1)
{
//Error
}
}
*/
Uart_State.Command_Active_Cnt--;
if (Uart_State.Command_Active_Cnt==0) Uart_State.Queue_Status_Uart=QUEUE_STATE_EMPTY;
if (Uart_State.Await_To_Reading_Position==QUE_COMMAND_MAX){
Uart_State.Await_To_Reading_Position=0;}
/*
if (Uart_State.Queue_Command[Uart_State.Await_To_Reading_Position].Place==FREE_PLACE)
{
while(1) //ловим ошибку
{
//Error где-то сбой, место должно было быть занято
}
}
*/
Uart_State.Command_Complete++;
Uart_State.Queue_Command[Uart_State.Await_To_Reading_Position].Place=FREE_PLACE;
return Uart_State.Queue_Command[Uart_State.Await_To_Reading_Position++];
}
/** ****************************************************************************
* @brief Процедура возвращает состояние очереди
* @retval Uart_State.Queue_Status_Uart
*******************************************************************************/
TEnum_Queue_State_Uart uart_get_state_queue()
{
return Uart_State.Queue_Status_Uart;
}
/**
* @brief Обработчик ошибки.На будущее
* @retval None
*/
void uart_handler_error_first_byte()
{
//Ошибка, пре-командный байт не равен 0
}
/**
* @brief Подпроцедура получения и сохранения команды по UART1. В конце проверяется состояние очереди (вызывается в прерывании)
* @param argument: Not used
* @retval None
*/
void uart_take_command()
{
if (Uart_State.Command_Active_Cnt==QUE_COMMAND_MAX)
{
handler_queue_not_free_place();
return;
}
if (UART_RX_Byte==0) Uart_State.Queue_Command[Uart_State.Active_Position].Error_Satus_Command=ERROR_NULL_COMMAND;
//сохраняем команду
Uart_State.Queue_Command[Uart_State.Active_Position].Command=UART_RX_Byte;
Uart_State.Queue_Command[Uart_State.Active_Position].NomberCommand=Uart_State.Command_Cnt;
Uart_State.Queue_Command[Uart_State.Active_Position].Place=BUSY_PLACE;
Uart_State.Active_Position++;
if (Uart_State.Active_Position==QUE_COMMAND_MAX)
{
Uart_State.Active_Position=0;
}
Uart_State.Command_Cnt++;
Uart_State.Command_Active_Cnt++;
//HAL_UART_Transmit_IT(&huart1, "OK", 2); //ответ
switch (Uart_State.Command_Active_Cnt)
{
case 1 ... QUE_COMMAND_MAX/2: Uart_State.Queue_Status_Uart=QUEUE_STATE_NORMAL; break;
case (QUE_COMMAND_MAX/2)+1 ... QUE_COMMAND_MAX-1: Uart_State.Queue_Status_Uart=QUEUE_STATE_HALF_WRITTEN; break;
case QUE_COMMAND_MAX : Uart_State.Queue_Status_Uart=QUEUE_STATE_NOT_FREE_PLACE; break;
}
}
/**
* @brief Обработчик ошибки.На будущее
* @retval None
*/
void handler_queue_not_free_place()
{
}
/**
* @brief Подпроцедура рандомно генерирует 1 из 4 возможных команд и посылает по UART2 (примет UART1). В конце проверяется состояние очереди
* @param argument: Not used
* @retval None
*/
void uart2_send_random(uint32_t task_500ms_Cnt)
{
uint8_t t_command[2]={0,0};
t_command[1]=((uint8_t)rand()%4)+1;
HAL_UART_Transmit_IT(&huart2, t_command, 2);
HAL_Delay(100);
t_command[1]++;
HAL_UART_Transmit_IT(&huart2, t_command, 2);
/*
if (task_500ms_Cnt==10)
{
t_command[1]=(1<<3)|4;
HAL_UART_Transmit_IT(&huart2, t_command, 2);
}
if (task_500ms_Cnt==20)
{
t_command[1]=(2<<3)|4;
HAL_UART_Transmit_IT(&huart2, t_command, 2);
HAL_Delay(100);
}
*/
}
/**
* @brief Подпроцедура отправляет по uart1 среднее значение ADC двумя байтами
* @param argument: Not used
* @retval None
*/
void uart_send_val_adc()
{
val_adc[0]=(uint8_t)adc_get_adc_mean_val()<<4;
val_adc[1]=(uint8_t)adc_get_adc_mean_val();
HAL_UART_Transmit_IT(&huart1, val_adc, 2);
//sprintf(
}
/**
* @brief Подпроцедура разрешает получить заданное количество байт
* @param argument: uint8_t num (количество байт)
* @retval None
*/
void uart_allow_to_receive(uint8_t num)
{
HAL_UART_Receive_IT(&huart2, buf_huart2, num);
}
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/тестовое задание/v1.01 — копия/Core/Inc/usart.h
/**
******************************************************************************
* @file usart.h
* @brief This file contains all the function prototypes for
* the usart.c file
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USART_H__
#define __USART_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart2;
/* USER CODE BEGIN Private defines */
#define QUE_COMMAND_MAX 10
#define UART_COMMAND_LED_ON 1
#define UART_COMMAND_LED_OFF 2
#define UART_COMMAND_GET_ADC_AVG_VOLTAGE 3
#define UART_COMMAND_SET_ADC_SAMPLE_RATE 4
/* Exported types ------------------------------------------------------------*/
typedef enum _TEnum_Place
{
FREE_PLACE = 01,
BUSY_PLACE = 02,
}TEnum_Place;
typedef enum _TEnum_Wait_Command
{
WAIT_NULL_COMMAND = 01,
WAIT_REGULAR_COMMAND = 02,
}TEnum_Wait_Command;
typedef enum _TEnum_Error_Status_Command //Error_Satus_Value
{
ERROR_NULL_COMMAND = 01,
ERROR_INCORRECT_COMMAND = 02,
}TEnum_Error_Status_Command;
typedef enum _TEnum_Queue_State_Uart //Error_Satus_Value
{
QUEUE_STATE_EMPTY = 00,
QUEUE_STATE_NORMAL = 01,
QUEUE_STATE_HALF_WRITTEN = 02,
QUEUE_STATE_NOT_FREE_PLACE = 03,
}TEnum_Queue_State_Uart;
typedef struct _TStruct_Uart_Command
{
uint32_t NomberCommand :32; //порядковый номер команды от начала работы программы
uint8_t Command :8; //сама команда
//uint8_t Param :8 //частота
TEnum_Place Place :2; //свободно ли место FREE_PLACE или BUSY_PLACE
TEnum_Error_Status_Command Error_Satus_Command :2;
}TStruct_Uart_Command;
typedef struct _TStruct_Uart_State
{
uint8_t Time_Out; // таймаут
uint32_t Command_Cnt; //сколько всего было команд за всё время
uint32_t Command_Active_Cnt; //количество активных команд (ждущих обработки)
uint32_t Active_Position; //указатель на текущее пустое место для новой записи
uint32_t Await_To_Reading_Position; //кто первый в очереди на считывание
TEnum_Wait_Command Wait_Command;
uint32_t Command_Complete; //счётчик отданых на обработку команд
TStruct_Uart_Command Queue_Command[QUE_COMMAND_MAX]; //очередь
TEnum_Queue_State_Uart Queue_Status_Uart;
}TStruct_Uart_State;
/* USER CODE END Private defines */
void MX_USART1_UART_Init(void);
void MX_USART2_UART_Init(void);
/* USER CODE BEGIN Prototypes */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) ;
uint8_t HAL_UART_Receive_IT_user (UART_HandleTypeDef* huart);
TStruct_Uart_Command uart_get_Command();
void UART_decrement_Index(void);
void uart_handler_error_first_byte();
void uart_init_state_settings();
void uart_take_command();
void handler_queue_not_free_place();
TEnum_Queue_State_Uart uart_get_state_queue();
void uart2_send_random(uint32_t);
void uart_allow_to_receive(uint8_t);
void uart_send_val_adc();
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __USART_H__ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/тестовое задание/v1.01/Core/Inc/commander.h
/**
******************************************************************************
* @file
* @brief
******************************************************************************
* @attention
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef _commander_H_
#define _commander_H_
/* Includes ------------------------------------------------------------------*/
#include "types.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
void commander_work();
void work_uart_command_queue();
void commander_do_command();
void get_and_execute_command();
#endif /* _commander_H_ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/тестовое задание/v1.01/Core/Src/freertos.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* File Name : freertos.c
* Description : Code for freertos applications
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usart.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
uint32_t task_1ms_Cnt=0;
uint32_t task_10ms_Cnt=0;
uint32_t task_500ms_Cnt=0;
/* USER CODE END Variables */
/* Definitions for Task_1ms */
osThreadId_t Task_1msHandle;
const osThreadAttr_t Task_1ms_attributes = {
.name = "Task_1ms",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for Task_10ms */
osThreadId_t Task_10msHandle;
const osThreadAttr_t Task_10ms_attributes = {
.name = "Task_10ms",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityLow,
};
/* Definitions for Task_500_ms */
osThreadId_t Task_500_msHandle;
const osThreadAttr_t Task_500_ms_attributes = {
.name = "Task_500_ms",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityLow,
};
/* Definitions for Task_Command */
osThreadId_t Task_CommandHandle;
const osThreadAttr_t Task_Command_attributes = {
.name = "Task_Command",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityLow,
};
/* Definitions for Task_Uart_TimeO */
osThreadId_t Task_Uart_TimeOHandle;
const osThreadAttr_t Task_Uart_TimeO_attributes = {
.name = "Task_Uart_TimeO",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityLow,
};
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
/* USER CODE END FunctionPrototypes */
void Task_1ms_Handler(void *argument);
void Task_10ms_Handler(void *argument);
void Task_500_ms_Handler(void *argument);
void Task_Command_Handler(void *argument);
void Task_Uart_TimeOut_Handler(void *argument);
void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */
/**
* @brief FreeRTOS initialization
* @param None
* @retval None
*/
void MX_FREERTOS_Init(void) {
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* USER CODE BEGIN RTOS_MUTEX */
/* add mutexes, ... */
/* USER CODE END RTOS_MUTEX */
/* USER CODE BEGIN RTOS_SEMAPHORES */
/* add semaphores, ... */
/* USER CODE END RTOS_SEMAPHORES */
/* USER CODE BEGIN RTOS_TIMERS */
/* start timers, add new ones, ... */
/* USER CODE END RTOS_TIMERS */
/* USER CODE BEGIN RTOS_QUEUES */
/* add queues, ... */
/* USER CODE END RTOS_QUEUES */
/* Create the thread(s) */
/* creation of Task_1ms */
Task_1msHandle = osThreadNew(Task_1ms_Handler, NULL, &Task_1ms_attributes);
/* creation of Task_10ms */
Task_10msHandle = osThreadNew(Task_10ms_Handler, NULL, &Task_10ms_attributes);
/* creation of Task_500_ms */
Task_500_msHandle = osThreadNew(Task_500_ms_Handler, NULL, &Task_500_ms_attributes);
/* creation of Task_Command */
Task_CommandHandle = osThreadNew(Task_Command_Handler, NULL, &Task_Command_attributes);
/* creation of Task_Uart_TimeO */
Task_Uart_TimeOHandle = osThreadNew(Task_Uart_TimeOut_Handler, NULL, &Task_Uart_TimeO_attributes);
/* USER CODE BEGIN RTOS_THREADS */
/* add threads, ... */
/* USER CODE END RTOS_THREADS */
/* USER CODE BEGIN RTOS_EVENTS */
/* add events, ... */
/* USER CODE END RTOS_EVENTS */
}
/* USER CODE BEGIN Header_Task_1ms_Handler */
/**
* @brief Function implementing the Task_1ms thread. В этой задаче происходит оцифровка сигнала АЦП (ЦАП на моей макетке нет)
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Task_1ms_Handler */
void Task_1ms_Handler(void *argument)
{
/* USER CODE BEGIN Task_1ms_Handler */
TickType_t xLastWakeTime;
const TickType_t xFrequency = 1 / portTICK_PERIOD_MS;
xLastWakeTime = xTaskGetTickCount();
/* Infinite loop */
for(;;)
{
adc_start1();
task_1ms_Cnt++;
vTaskDelayUntil(&xLastWakeTime, xFrequency);
osDelay(1);
}
/* USER CODE END Task_1ms_Handler */
}
/* USER CODE BEGIN Header_Task_10ms_Handler */
/**
* @brief Function implementing the Task_10ms thread. Задача проверяет не закончилось ли время ожидания регулярной команды
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Task_10ms_Handler */
void Task_10ms_Handler(void *argument)
{
/* USER CODE BEGIN Task_10ms_Handler */
TickType_t xLastWakeTime;
const TickType_t xFrequency = 10 / portTICK_PERIOD_MS;
xLastWakeTime = xTaskGetTickCount();
/* Infinite loop */
for(;;)
{
HAL_NVIC_DisableIRQ(USART1_IRQn);
uart_timeout();
HAL_NVIC_EnableIRQ(USART1_IRQn);
vTaskDelayUntil(&xLastWakeTime, xFrequency);
osDelay(1);
}
/* USER CODE END Task_10ms_Handler */
}
/* USER CODE BEGIN Header_Task_500_ms_Handler */
/**
* @brief Function implementing the Task_500_ms thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Task_500_ms_Handler */
void Task_500_ms_Handler(void *argument)
{
/* USER CODE BEGIN Task_500_ms_Handler */
TickType_t xLastWakeTime;
const TickType_t xFrequency = 500 / portTICK_PERIOD_MS;
xLastWakeTime = xTaskGetTickCount();
/* Infinite loop */
for(;;)
{
uart2_send_random(task_500ms_Cnt);
task_500ms_Cnt++;
vTaskDelayUntil(&xLastWakeTime, xFrequency);
osDelay(1);
}
/* USER CODE END Task_500_ms_Handler */
}
/* USER CODE BEGIN Header_Task_Command_Handler */
/**
* @brief Function implementing the Task_Command thread. Работа командного модуля
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Task_Command_Handler */
void Task_Command_Handler(void *argument)
{
/* USER CODE BEGIN Task_Command_Handler */
TickType_t xLastWakeTime;
const TickType_t xFrequency = 3000 / portTICK_PERIOD_MS;
xLastWakeTime = xTaskGetTickCount();
/* Infinite loop */
for(;;)
{
if (task_500ms_Cnt>5)
{
HAL_NVIC_DisableIRQ(USART1_IRQn);
commander_work();
HAL_NVIC_EnableIRQ(USART1_IRQn);
}
vTaskDelayUntil(&xLastWakeTime, xFrequency);
osDelay(1);
}
/* USER CODE END Task_Command_Handler */
}
/* USER CODE BEGIN Header_Task_Uart_TimeOut_Handler */
/**
* @brief Function implementing the Task_Uart_TimeO thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_Task_Uart_TimeOut_Handler */
void Task_Uart_TimeOut_Handler(void *argument)
{
/* USER CODE BEGIN Task_Uart_TimeOut_Handler */
/* Infinite loop */
for(;;)
{
osDelay(1);
}
/* USER CODE END Task_Uart_TimeOut_Handler */
}
/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */
/* USER CODE END Application */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/тестовое задание/v1.01 — копия/Core/Src/commander.c
/**
******************************************************************************
* @file commander.c
* @brief модуль обработки команд и их выполнения
******************************************************************************
* @attention
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "commander.h"
#include "usart.h"
#include "adc.h"
uint32_t commander_operation_cnt=0;
/* Private function ----------------------------------------------------------*/
void commander_work()
{
work_uart_command_queue();
}
/**
* @brief Работа с очередью. проверяется состояние очереди, если всё плохо, то обрабатывается сразу несколько команд
* @param None
* @retval None
*/
void work_uart_command_queue()
{
TEnum_Queue_State_Uart Uart_Queue_State=uart_get_state_queue();
switch (Uart_Queue_State)
{
case QUEUE_STATE_EMPTY:
//todo ничего не делать
break;
case QUEUE_STATE_NORMAL:
get_and_execute_command();
break;
case QUEUE_STATE_HALF_WRITTEN:
get_and_execute_command();
get_and_execute_command();
break;
case QUEUE_STATE_NOT_FREE_PLACE:
get_and_execute_command();
get_and_execute_command();
get_and_execute_command();
get_and_execute_command();
break;
}
}
/**
* @brief достаёт актуальную команду из очереди, проверяет и выполняет
* @param None
* @retval None
* @attention Принимается команда Command_now (достаётся из очереди)
Если порядковый номер не совпадает, вызывается исключение
Команда UART_COMMAND_SET_ADC_SAMPLE_RATE включает в себя
идентификатор команды Command_now (младшие 3 бита)
и параметр Param_Freq(старшие 5 бит) для конфигурирования частоты
дискретизации ADC
*/
void get_and_execute_command()
{
TStruct_Uart_Command UART_Command;
UART_Command=uart_get_Command();
if(commander_operation_cnt!=UART_Command.NomberCommand)
{
while(1) {}//Исключение. что-то пошло не так
}
uint8_t Command_now=UART_Command.Command&0x07; //только 3 младших бита
uint8_t Param_Freq=UART_Command.Command&0xf8; //5 старших бит
Param_Freq=Param_Freq>>3;
switch (Command_now)
{
case UART_COMMAND_LED_ON:
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);
break;
case UART_COMMAND_LED_OFF:
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
break;
case UART_COMMAND_GET_ADC_AVG_VOLTAGE:
uart_allow_to_receive(2); //разрешить huart2 получить 2 байта
uart_send_val_adc(); //отправить adc_val (2 байта) для huart2
break;
case UART_COMMAND_SET_ADC_SAMPLE_RATE:
adc_new_freq_samp(Param_Freq);
break;
}
commander_operation_cnt++;
}
/***************************************************************END OF FILE****/
|
fb22188f076f96d19b8158c4e1ca010d2d18931c
|
[
"C"
] | 5
|
C
|
SAV2809/stm32f103c8t6-bluepill
|
2dce24ad7da65f50cb293e3b7071a1ef1611ac48
|
1cfac2b75c0f817b1b4ed51de2a6d694f38fde8e
|
refs/heads/master
|
<file_sep>const logItems = function(array) {
console.log(array);
let index;
for (index = 0; index < array.length; index++) {
console.log(`${array.indexOf(array[index]) + 1} - ${array[index]}`);
}
};
/*
* Вызовы функции для проверки работоспособности реализации.
*/
//logItems(["Mango", "Poly", "Ajax", "Lux", "Jay", "Kong"]);
logItems([5, 10, 15, 20, 25, 30, 35, 40, 45, 50]);
<file_sep>let input = +prompt("Enter a number", "");
const numbers = [];
let total = 0;
while (input) {
numbers.push(input);
input = +prompt("Insert a number", "");
}
for (let value of numbers) {
total += value;
}
console.log(`Общая сумма чисел равна ${total}`);
|
dec6e6c68114470b3458a739416b40dd136428c5
|
[
"JavaScript"
] | 2
|
JavaScript
|
Victor-page/js-02
|
c997d8e78d1e674c35e6cefaf262446b82eef600
|
fba799bbbcee01f055ab44db928b533aad5e939c
|
refs/heads/main
|
<file_sep>#pragma once
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundConstantExpression : public BoundExpression
{
private:
shared_ptr<BoundConstant> mValue;
public:
BoundConstantExpression(shared_ptr<BoundConstant> val)
: BoundExpression(make_shared<Syntax::ExpressionSyntax>(Syntax::Token::Default)), mValue(val) {}
virtual Kind GetKind() override
{ return ConstantExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return Symbol::TypeSymbol::LongType; }
virtual shared_ptr<BoundConstant> ConstantValue() override
{ return mValue; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); ConstantValue()->Print(os, newIndent, true, "Constant = ");
}
};
}<file_sep>#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Symbol
{
shared_ptr<TypeSymbol> TypeSymbol::ErrorType = make_shared<TypeSymbol>(Error, "error-type", -1);
shared_ptr<TypeSymbol> TypeSymbol::VoidType = make_shared<TypeSymbol>(Void, "void", 0);
shared_ptr<TypeSymbol> TypeSymbol::ByteType = make_shared<TypeSymbol>(Byte, "byte", 1);
shared_ptr<TypeSymbol> TypeSymbol::ShortType = make_shared<TypeSymbol>(Short, "short", 2);
shared_ptr<TypeSymbol> TypeSymbol::IntType = make_shared<TypeSymbol>(Int, "int", 4);
shared_ptr<TypeSymbol> TypeSymbol::LongType = make_shared<TypeSymbol>(Long, "long", 8);
shared_ptr<TypeSymbol> TypeSymbol::BoolType = make_shared<TypeSymbol>(Bool, "bool", 2);
shared_ptr<TypeSymbol> TypeSymbol::CharType = make_shared<TypeSymbol>(Char, "char", 4);
shared_ptr<TypeSymbol> TypeSymbol::WCharType = make_shared<TypeSymbol>(WChar, "wchar", 8);
shared_ptr<TypeSymbol> TypeSymbol::FloatType = make_shared<TypeSymbol>(Float, "float", 8, true);
shared_ptr<TypeSymbol> TypeSymbol::DoubleType = make_shared<TypeSymbol>(Double, "double", 8, true);
shared_ptr<TypeSymbol> TypeSymbol::TripleType = make_shared<TypeSymbol>(Triple, "triple", 16, true);
shared_ptr<TypeSymbol> TypeSymbol::VoidPointerType = make_shared<TypeSymbol>(Void, "void", 4, false, 1);
shared_ptr<TypeSymbol> TypeSymbol::BytePointerType = make_shared<TypeSymbol>(Byte, "byte", 4, false, 1);
shared_ptr<TypeSymbol> TypeSymbol::CharPointerType = make_shared<TypeSymbol>(Char, "char", 4, false, 1);
TypeSymbol::TypeSymbol(TypeKind kind, std::string_view name, unsigned sz, bool isFloat, unsigned pointerCount, std::vector<char> mods)
: mTypeKind(kind), mName(name), mSize(sz), mFloat(isFloat), mPointerCount(pointerCount), mModifiers(mods)
{}
bool TypeSymbol::Equals(shared_ptr<TypeSymbol> other)
{
return GetPointerCount() == other->GetPointerCount() && Is(other->GetTypeKind());
}
bool TypeSymbol::Is(TypeKind kind)
{ return mTypeKind == kind; }
void TypeSymbol::Print(std::ostream &os, std::string_view indent, bool last, std::string_view label)
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '";
PrintShort(os);
os << '\'';
}
void TypeSymbol::PrintShort(std::ostream &os)
{
os << GetName();
for (unsigned p = 0; p < GetPointerCount(); p++)
os << '*';
}
Symbol::Kind TypeSymbol::GetKind()
{ return Type; }
TypeSymbol::TypeKind TypeSymbol::GetTypeKind()
{ return mTypeKind; }
std::string_view TypeSymbol::GetName()
{ return mName; }
unsigned TypeSymbol::GetSize()
{ return GetPointerCount() ? 4 : mSize; }
bool TypeSymbol::IsFloat()
{ return mFloat; }
unsigned TypeSymbol::GetPointerCount()
{ return mPointerCount; }
std::vector<char> &TypeSymbol::GetModifiers()
{ return mModifiers; }
}<file_sep>#pragma once
#include <cstdio>
#include <string>
namespace Symple::Util
{
FILE* OpenFile(char* path, char* perms);
FILE* OpenTempFile();
extern int (*CloseFile)(FILE*);
void DumpFile(FILE* from, FILE* to = stdout);
std::string ReadFile(FILE*, unsigned max = -1);
}<file_sep>#pragma once
#include "SympleCode/Syntax/NameExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Symbol/VariableSymbol.h"
namespace Symple::Binding
{
class BoundVariableExpression : public BoundExpression
{
private:
shared_ptr<Symbol::VariableSymbol> mSymbol;
public:
BoundVariableExpression(shared_ptr<Syntax::NameExpressionSyntax> syntax, shared_ptr<Symbol::VariableSymbol> var)
: BoundExpression(syntax), mSymbol(var)
{}
virtual Kind GetKind() override
{ return VariableExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return mSymbol->GetType(); }
virtual bool IsMutable() override
{ return true; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetSymbol()->Print(os, newIndent, true, "Symbol = ");
}
shared_ptr<Symbol::VariableSymbol> GetSymbol()
{ return mSymbol; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
namespace Symple::Syntax
{
class NativeStatementSyntax : public StatementSyntax
{
private:
shared_ptr<Token> mAssembly;
public:
NativeStatementSyntax(shared_ptr<Token> key, shared_ptr<Token> code)
: StatementSyntax(key), mAssembly(code) {}
virtual Kind GetKind() override
{ return NativeStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetAssembly()->Print(os, newIndent, true, "Assembly = ");
}
shared_ptr<Token> GetKeyword()
{ return GetToken(); }
shared_ptr<Token> GetAssembly()
{ return mAssembly; }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/Symbol.h"
namespace Symple::Symbol
{
class LabelSymbol : public Symbol
{
private:
std::string mLabel;
public:
LabelSymbol(std::string_view label)
: mLabel(label)
{}
virtual Kind GetKind() override
{ return Label; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '" << GetLabel() << '\'';
}
void PrintShort(std::ostream& os = std::cout)
{ os << GetLabel(); }
std::string_view GetLabel()
{ return mLabel; }
};
typedef std::vector<shared_ptr<LabelSymbol>> LabelList;
}<file_sep>#pragma once
#include "SympleCode/Syntax/MemberSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
namespace Symple::Syntax
{
class GlobalStatementSyntax : public MemberSyntax
{
private:
shared_ptr<StatementSyntax> mStatement;
public:
GlobalStatementSyntax(shared_ptr<StatementSyntax> stmt)
: MemberSyntax(stmt->GetToken()), mStatement(stmt) {}
virtual Kind GetKind() override
{ return GlobalStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetStatement()->Print(os, newIndent, true, "Value = ");
}
shared_ptr<StatementSyntax> GetStatement()
{ return mStatement; }
};
}<file_sep>#pragma once
#include <iostream>
#include "SympleCode/Binding/Node.h"
namespace Symple::Binding
{
class BoundConstant
{
public: enum Kind : unsigned;
private:
Kind mKind;
char mValue[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
public:
BoundConstant(Kind kind, void* data)
: mKind(kind)
{
errno_t err = memcpy_s(mValue, sizeof(mValue), data, 16);
if (err)
{
char msg[16];
if (strerror_s(msg, err))
spdlog::critical("Error copying data");
else
spdlog::critical("Error copying data: {}", msg);
}
}
void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
Node::PrintIndent(os, indent, last, label);
os << "BoundConstant: ";
switch (GetKind())
{
case Integer:
os << GetValue<int>();
break;
case Float:
os << GetValue<float>();
break;
}
}
void PrintShort(std::ostream& os = std::cout)
{
os << "(Constant) ";
switch (GetKind())
{
case Integer:
os << GetValue<int>();
break;
case Float:
os << GetValue<float>();
break;
}
}
void SetKind(Kind kind)
{ mKind = kind; }
Kind GetKind()
{ return mKind; }
template <typename T = int>
T& GetValue()
{
__SY_ASSERT(sizeof(T) <= 16, "BoundConstant buffer to large");
return *(T*)mValue;
}
public:
enum Kind : unsigned
{
Integer,
Float,
};
};
}<file_sep>#include "SympleCode/Syntax/Parser.h"
#include <sstream>
#include <spdlog/spdlog.h>
#include "SympleCode/Syntax/Facts.h"
#include "SympleCode/Syntax/GlobalStatementSyntax.h"
namespace Symple::Syntax
{
Parser::Parser(shared_ptr<Lexer> lexer)
{
do
mTokens.push_back(lexer->Lex());
while (!mTokens.back()->Is(Token::EndOfFile));
}
Parser::Parser(shared_ptr<Lexer> lexer, TokenList tokens)
: mTokens(tokens)
{
if (!tokens.empty() && tokens.back()->Is(Token::EndOfFile))
return;
do
mTokens.push_back(lexer->Lex());
while (!mTokens.back()->Is(Token::EndOfFile));
}
Parser::Parser(TokenList tokens)
: mTokens(tokens)
{}
shared_ptr<TranslationUnitSyntax> Parser::Parse()
{
std::vector<shared_ptr<MemberSyntax>> members;
while (!Peek()->Is(Token::EndOfFile))
{
unsigned start = mPosition;
members.push_back(ParseMember());
if (start == mPosition)
Next();
}
shared_ptr<Token> eof = Match(Token::EndOfFile);
return make_shared<TranslationUnitSyntax>(members, eof);
}
shared_ptr<MemberSyntax> Parser::ParseMember()
{
if (IsType())
return ParseFunctionDeclaration();
else
switch (Peek()->GetKind())
{
case Token::ExternKeyword:
return ParseExternFunction();
case Token::StructKeyword:
return ParseStructDeclaration();
case Token::ImportKeyword:
return ParseImportStatement();
default:
return make_shared<GlobalStatementSyntax>(ParseStatement());
}
}
shared_ptr<ExternFunctionSyntax> Parser::ParseExternFunction()
{
shared_ptr<Token> keyword = Match(Token::ExternKeyword);
auto type = ParseType();
shared_ptr<Token> name = Match(Token::Identifier);
shared_ptr<Token> openParen = Match(Token::OpenParenthesis);
auto params = ParseFunctionParameters();
shared_ptr<Token> closeParen = Match(Token::CloseParenthesis);
TokenList modifiers = ParseFunctionModifiers();
Match(Token::Semicolon);
return make_shared<ExternFunctionSyntax>(keyword, type, name, openParen, params, closeParen, modifiers);
}
shared_ptr<FunctionDeclarationSyntax> Parser::ParseFunctionDeclaration()
{
auto type = ParseType();
shared_ptr<Token> name = Match(Token::Identifier);
shared_ptr<Token> openParen = Match(Token::OpenParenthesis);
auto params = ParseFunctionParameters();
shared_ptr<Token> closeParen = Match(Token::CloseParenthesis);
TokenList modifiers = ParseFunctionModifiers();
if (Peek()->Is(Token::EqualArrow))
Next();
shared_ptr<StatementSyntax> statement = ParseStatement();
return make_shared<FunctionDeclarationSyntax>(type, name, openParen, params, closeParen, modifiers, statement);
}
VariableDeclarationList Parser::ParseFunctionParameters()
{
VariableDeclarationList list;
bool first = true;
shared_ptr<TypeSyntax> pty;
while (!Peek()->Is(Token::CloseParenthesis))
{
if (Peek()->Is(Token::EndOfFile))
{
mDiagnosticBag->ReportUnexpectedEndOfFile(Peek());
break;
}
if (first)
first = false;
else
Match(Token::Comma);
if (!Peek()->Is(Token::CloseParenthesis))
{
list.push_back(ParseVariableDeclaration(pty));
pty = list.back()->GetType();
}
}
return list;
}
TokenList Parser::ParseFunctionModifiers()
{
TokenList list;
while (Peek()->Is(Token::CDeclKeyword, Token::StdCallKeyword, // Naming Conventions
Token::DllExportKeyword, Token::DllImportKeyword, // Dll Stuff
Token::StaticKeyword, Token::LocalKeyword, Token::GlobalKeyword, // Visibility Modifiers
Token::Comma)) // Commas
{
if (Peek()->Is(Token::Comma))
Next();
else
list.push_back(Next());
}
return list;
}
shared_ptr<StructDeclarationSyntax> Parser::ParseStructDeclaration()
{
shared_ptr<Token> keyword = Match(Token::StructKeyword);
shared_ptr<Token> name = Match(Token::Identifier);
shared_ptr<Token> open = Match(Token::OpenBrace);
auto members = ParseStructMembers();
shared_ptr<Token> close = Match(Token::CloseBrace);
mStructNames.push_back(std::string(name->GetText()));
return make_shared<StructDeclarationSyntax>(keyword, name, open, members, close);
}
VariableDeclarationList Parser::ParseStructMembers()
{
VariableDeclarationList list;
bool first = true;
shared_ptr<TypeSyntax> pty;
while (!Peek()->Is(Token::CloseBrace))
{
if (Peek()->Is(Token::EndOfFile))
{
mDiagnosticBag->ReportUnexpectedEndOfFile(Peek());
break;
}
if (first)
first = false;
else
Match(Token::Comma);
if (!Peek()->Is(Token::CloseBrace))
{
list.push_back(ParseVariableDeclaration(pty));
pty = list.back()->GetType();
}
}
return list;
}
shared_ptr<ImportStatementSyntax> Parser::ParseImportStatement()
{
shared_ptr<Token> tok = Match(Token::ImportKeyword);
shared_ptr<Token> import = Match(Token::String);
Match(Token::Semicolon);
return make_shared<ImportStatementSyntax>(tok, import);
}
shared_ptr<StatementSyntax> Parser::ParseStatement(bool matchSemi)
{
shared_ptr<StatementSyntax> statement;
if (IsType())
statement = ParseVariableDeclaration();
else
switch (Peek()->GetKind())
{
case Token::IfKeyword:
statement = ParseIfStatement();
matchSemi = false;
break;
case Token::GotoKeyword:
statement = ParseGotoStatement();
break;
case Token::NativeKeyword:
statement = ParseNativeStatement();
break;
case Token::OpenBrace:
statement = ParseBlockStatement();
matchSemi = false;
break;
case Token::ReturnKeyword:
statement = ParseReturnStatement();
break;
case Token::Identifier:
if (Peek(1)->Is(Token::Colon))
{
statement = ParseLabel();
matchSemi = false;
break;
}
default:
statement = ParseExpressionStatement();
break;
}
if (matchSemi)
Match(Token::Semicolon);
return statement;
}
shared_ptr<LabelSyntax> Parser::ParseLabel()
{
shared_ptr<Token> label = Match(Token::Identifier);
shared_ptr<Token> colon = Match(Token::Colon);
return make_shared<LabelSyntax>(label, colon);
}
shared_ptr<IfStatementSyntax> Parser::ParseIfStatement()
{
shared_ptr<Token> ifKey = Match(Token::IfKeyword);
shared_ptr<ParenthesizedExpressionSyntax> cond = ParseParenthesizedExpression();
shared_ptr<StatementSyntax> then = ParseStatement();
shared_ptr<Token> elseKey;
shared_ptr<StatementSyntax> elze;
if (Peek()->Is(Token::ElseKeyword))
{
elseKey = Next();
elze = ParseStatement();
}
return make_shared<IfStatementSyntax>(ifKey, cond, then, elseKey, elze);
}
shared_ptr<GotoStatementSyntax> Parser::ParseGotoStatement()
{
shared_ptr<Token> keyword = Match(Token::GotoKeyword);
shared_ptr<Token> label = Match(Token::Identifier);
return make_shared<GotoStatementSyntax>(keyword, label);
}
shared_ptr<NativeStatementSyntax> Parser::ParseNativeStatement()
{
shared_ptr<Token> tok = Match(Token::NativeKeyword);
shared_ptr<Token> code = Match(Token::String);
return make_shared<NativeStatementSyntax>(tok, code);
}
shared_ptr<BlockStatementSyntax> Parser::ParseBlockStatement()
{
shared_ptr<Token> open = Match(Token::OpenBrace);
std::vector<shared_ptr<StatementSyntax>> statements;
while (!Peek()->Is(Token::CloseBrace))
{
if (Peek()->Is(Token::EndOfFile))
{
mDiagnosticBag->ReportUnexpectedEndOfFile(Peek());
return make_shared<BlockStatementSyntax>(open, statements, Peek());
}
unsigned start = mPosition;
shared_ptr<StatementSyntax> statement = ParseStatement();
statements.push_back(statement);
if (mPosition == start)
Next();
}
shared_ptr<Token> close = Match(Token::CloseBrace);
return make_shared<BlockStatementSyntax>(open, statements, close);
}
shared_ptr<ReturnStatementSyntax> Parser::ParseReturnStatement()
{
shared_ptr<Token> tok = Match(Token::ReturnKeyword);
shared_ptr<ExpressionSyntax> val = ParseExpression();
return make_shared<ReturnStatementSyntax>(tok, val);
}
shared_ptr<ExpressionStatementSyntax> Parser::ParseExpressionStatement()
{
shared_ptr<ExpressionSyntax> expr = ParseExpression();
return make_shared<ExpressionStatementSyntax>(expr);
}
shared_ptr<VariableDeclarationSyntax> Parser::ParseVariableDeclaration(shared_ptr<TypeSyntax> ty)
{
if (!ty || IsType())
ty = ParseType();
shared_ptr<Token> name = Token::Default;
if (Peek()->Is(Token::Identifier))
name = Next();
shared_ptr<Token> equals = Token::Default;
shared_ptr<ExpressionSyntax> initializer;
if (Peek()->Is(Token::Equal))
{
equals = Next();
initializer = ParseExpression();
}
return make_shared<VariableDeclarationSyntax>(ty, name, equals, initializer);
}
shared_ptr<TypeSyntax> Parser::ParseType(shared_ptr<TypeSyntax> base)
{
shared_ptr<Token> tyqename = Next();
base = make_shared<TypeReferenceSyntax>(tyqename, base);
if (IsType())
return ParseType(base);
else
return base;
}
shared_ptr<ExpressionSyntax> Parser::ParseExpression()
{ return ParseBinaryExpression(); }
ExpressionList Parser::ParseExpressionList()
{
ExpressionList list;
bool first = true;
while (!Peek()->Is(Token::CloseParenthesis, Token::CloseBrace))
{
if (Peek()->Is(Token::EndOfFile))
{
mDiagnosticBag->ReportUnexpectedEndOfFile(Peek());
break;
}
if (first)
first = false;
else
Match(Token::Comma);
list.push_back(ParseExpression());
}
return list;
}
shared_ptr<ExpressionSyntax> Parser::ParseUnaryExpression(unsigned parentPrecedence)
{
unsigned precedence = Facts::GetUnaryOperatorPrecedence(Peek()->GetKind());
if (precedence && precedence <= parentPrecedence)
{
shared_ptr<Token> oqerator = Next();
shared_ptr<ExpressionSyntax> operand = ParseBinaryExpression(precedence);
return make_shared<UnaryExpressionSyntax>(oqerator, operand);
}
else
return ParsePrimaryExpression();
}
shared_ptr<ExpressionSyntax> Parser::ParseBinaryExpression(unsigned parentPrecedence)
{
shared_ptr<ExpressionSyntax> left = ParseUnaryExpression(parentPrecedence);
while (true)
{
unsigned precedence = Facts::GetBinaryOperatorPrecedence(Peek()->GetKind());
if (!precedence || parentPrecedence && precedence >= parentPrecedence)
return left;
shared_ptr<Token> oqerator = Next();
shared_ptr<ExpressionSyntax> right = ParseUnaryExpression(precedence);
left = make_shared<BinaryExpressionSyntax>(oqerator, left, right);
}
}
shared_ptr<ExpressionSyntax> Parser::ParsePrimaryExpression()
{
switch (Peek()->GetKind())
{
case Token::Identifier:
if (Peek(1)->Is(Token::OpenParenthesis))
return ParseCallExpression();
else
return ParseNameExpression();
case Token::Number:
case Token::Float:
case Token::Integer:
case Token::String:
case Token::DefaultKeyword:
return ParseLiteralExpression();
case Token::OpenParenthesis:
return ParseParenthesizedExpression();
default:
return make_shared<ExpressionSyntax>(Next());
}
}
shared_ptr<NameExpressionSyntax> Parser::ParseNameExpression()
{ return make_shared<NameExpressionSyntax>(Match(Token::Identifier)); }
shared_ptr<CallExpressionSyntax> Parser::ParseCallExpression()
{
shared_ptr<Token> name = Match(Token::Identifier);
shared_ptr<Token> open = Match(Token::OpenParenthesis);
ExpressionList args = ParseExpressionList();
shared_ptr<Token> close = Match(Token::CloseParenthesis);
return make_shared<CallExpressionSyntax>(name, open, args, close);
}
shared_ptr<LiteralExpressionSyntax> Parser::ParseLiteralExpression()
{ return make_shared<LiteralExpressionSyntax>(Next()); }
shared_ptr<ParenthesizedExpressionSyntax> Parser::ParseParenthesizedExpression()
{
shared_ptr<Token> open = Match(Token::OpenParenthesis);
shared_ptr<ExpressionSyntax> expression = ParseExpression();
shared_ptr<Token> close = Match(Token::CloseParenthesis);
return make_shared<ParenthesizedExpressionSyntax>(open, expression, close);
}
shared_ptr<DiagnosticBag> Parser::GetDiagnosticBag()
{ return mDiagnosticBag; }
shared_ptr<Token> Parser::Peek(unsigned off)
{
unsigned pos = mPosition + off;
if (pos >= mTokens.size())
return mTokens.back();
return mTokens[pos];
}
shared_ptr<Token> Parser::Next()
{
auto current = Peek();
mPosition++;
return current;
}
shared_ptr<Token> Parser::Match(Token::Kind kind)
{
if (Peek()->Is(kind))
return Next();
mDiagnosticBag->ReportUnexpectedToken(Peek(), kind);
return Peek();
}
bool Parser::IsType()
{
switch (Peek()->GetKind())
{
case Token::VoidKeyword:
case Token::ByteKeyword:
case Token::ShortKeyword:
case Token::IntKeyword:
case Token::LongKeyword:
case Token::BoolKeyword:
case Token::CharKeyword:
case Token::WCharKeyword:
case Token::FloatKeyword:
case Token::DoubleKeyword:
case Token::TripleKeyword:
case Token::Asterisk:
return true;
case Token::Identifier:
for (auto name : mStructNames)
if (Peek()->GetText() == name)
return true;
default:
return false;
}
}
}<file_sep>#include "SympleCode/Binding/Casting.h"
namespace Symple::Binding
{
bool CastTable::CanImplicitelyCast(shared_ptr<Symbol::TypeSymbol> from, shared_ptr<Symbol::TypeSymbol> to)
{ return true; }
bool CastTable::CanExplicitelyCast(shared_ptr<Symbol::TypeSymbol> from, shared_ptr<Symbol::TypeSymbol> to)
{ return CanImplicitelyCast(from, to) || true; }
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/MemberSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/VariableDeclarationSyntax.h"
#include "SympleCode/Syntax/TypeSyntax.h"
namespace Symple::Syntax
{
class StructDeclarationSyntax: public MemberSyntax
{
private:
shared_ptr<Token> mKeyword;
shared_ptr<Token> mOpenBrace;
VariableDeclarationList mMembers;
shared_ptr<Token> mCloseBrace;
public:
StructDeclarationSyntax(shared_ptr<Token> keyword, shared_ptr<Token> name, shared_ptr<Token> openBrace,
VariableDeclarationList members, shared_ptr<Token> closeBrace)
: MemberSyntax(name), mKeyword(keyword), mOpenBrace(openBrace), mMembers(members), mCloseBrace(closeBrace)
{}
virtual Kind GetKind() override
{ return StructDeclaration; }
virtual void Print(std::ostream &os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '" << GetName()->GetText() << "'";
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto member : GetMembers())
{ os.put('\n'); member->Print(os, newIndent, member == GetMembers().back(), "[Member] "); }
}
shared_ptr<Token> GetKeyword()
{ return mKeyword; }
shared_ptr<Token> GetName()
{ return GetToken(); }
shared_ptr<Token> GetOpenBrace()
{ return mOpenBrace; }
VariableDeclarationList GetMembers()
{ return mMembers; }
shared_ptr<Token> GetCloseBrace()
{ return mCloseBrace; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class CallExpressionSyntax : public ExpressionSyntax
{
private:
shared_ptr<Token> mOpenParenthesis;
ExpressionList mArguments;
shared_ptr<Token> mCloseParenthesis;
public:
CallExpressionSyntax(shared_ptr<Token> name, shared_ptr<Token> openParen, ExpressionList args, shared_ptr<Token> closeParen)
: ExpressionSyntax(name), mOpenParenthesis(openParen), mArguments(args), mCloseParenthesis(closeParen) {}
virtual Kind GetKind() override
{ return CallExpression; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '" << GetName()->GetText() << " (" << GetArguments().size() << ")'";
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto arg : GetArguments())
{ os.put('\n'); arg->Print(os, newIndent, arg == GetArguments().back()); }
}
shared_ptr<Token> GetName()
{ return GetToken(); }
shared_ptr<Token> GetOpenParenthesis()
{ return mOpenParenthesis; }
ExpressionList GetArguments()
{ return mArguments; }
shared_ptr<Token> GetCloseParenthesis()
{ return mCloseParenthesis; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/NameExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Symbol/FunctionSymbol.h"
namespace Symple::Binding
{
class BoundFunctionPointer : public BoundExpression
{
private:
shared_ptr<Symbol::FunctionSymbol> mSymbol;
public:
BoundFunctionPointer(shared_ptr<Syntax::NameExpressionSyntax> syntax, shared_ptr<Symbol::FunctionSymbol> fn)
: BoundExpression(syntax), mSymbol(fn)
{}
virtual Kind GetKind() override
{ return FunctionPointer; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return Symbol::TypeSymbol::VoidPointerType; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetSymbol()->Print(os, newIndent, true, "Symbol = ");
}
shared_ptr<Symbol::FunctionSymbol> GetSymbol()
{ return mSymbol; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class LiteralExpressionSyntax : public ExpressionSyntax
{
public:
LiteralExpressionSyntax(shared_ptr<Token> tok)
: ExpressionSyntax(tok) {}
virtual Kind GetKind() override
{ return LiteralExpression; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
GetLiteral()->Print(os, indent, last, label);
os << " (";
PrintName(os);
os.put(')');
}
shared_ptr<Token> GetLiteral()
{ return GetToken(); }
};
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Diagnostic.h"
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/Syntax/CallExpressionSyntax.h"
#include "SympleCode/Syntax/LiteralExpressionSyntax.h"
#include "SympleCode/Symbol/TypeSymbol.h"
#define __SY_ALLOW_UNIMPLIMENTED __SY_DEBUG
namespace Symple
{
class DiagnosticBag
{
private:
std::vector<shared_ptr<Diagnostic>> mDiagnostics;
unsigned mMessageCount, mWarningCount, mErrorCount;
public:
void ReportMessage(shared_ptr<Syntax::Token>, std::string_view msg);
void ReportWarning(shared_ptr<Syntax::Token>, std::string_view msg);
void ReportError(shared_ptr<Syntax::Token>, std::string_view msg);
unsigned GetMessageCount();
unsigned GetWarningCount();
unsigned GetErrorCount();
std::vector<shared_ptr<Diagnostic>>& GetDiagnostics();
#if __SY_ALLOW_UNIMPLIMENTED
void ReportUnimplimentedMessage(shared_ptr<Syntax::Token>);
void ReportUnimplimentedWarning(shared_ptr<Syntax::Token>);
void ReportUnimplimentedError(shared_ptr<Syntax::Token>);
#endif
void ReportBindError(shared_ptr<Syntax::Node>);
void ReportExpressionMustHaveValue(shared_ptr<Syntax::ExpressionSyntax>);
void ReportNoDefaultArgument(shared_ptr<Syntax::CallExpressionSyntax>, unsigned paramIndex);
void ReportTooFewArguments(shared_ptr<Syntax::CallExpressionSyntax>);
void ReportTooManyArguments(shared_ptr<Syntax::CallExpressionSyntax>, unsigned paramIndex);
void ReportNoSuchFunction(shared_ptr<Syntax::CallExpressionSyntax>);
void ReportUndeclaredLabel(shared_ptr<Syntax::Token>);
void ReportUndeclaredIdentifier(shared_ptr<Syntax::Token>);
void ReportUnexpectedDllImportBody(shared_ptr<Syntax::Token>);
void ReportUnexpectedEndOfFile(shared_ptr<Syntax::Token>);
void ReportUnexpectedToken(shared_ptr<Syntax::Token>, Syntax::Token::Kind expectedKind);
void ReportUnknownToken(shared_ptr<Syntax::Token>);
void ReportInvalidOperation(shared_ptr<Syntax::Token>, shared_ptr<Symbol::TypeSymbol> left, shared_ptr<Symbol::TypeSymbol> right);
void ReportInvalidOperation(shared_ptr<Syntax::Token>, shared_ptr<Symbol::TypeSymbol>);
void ReportExpectedUnqualifiedID(shared_ptr<Syntax::Token>);
void ReportExpectedLValue(shared_ptr<Syntax::Token>);
void ReportInvalidLiteral(shared_ptr<Syntax::LiteralExpressionSyntax>);
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/BlockStatementSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
namespace Symple::Binding
{
class BoundBlockStatement : public BoundStatement
{
private:
std::vector<shared_ptr<BoundStatement>> mStatements;
public:
BoundBlockStatement(shared_ptr<Syntax::BlockStatementSyntax> syntax, std::vector<shared_ptr<BoundStatement>> statements)
: BoundStatement(syntax), mStatements(statements) {}
virtual Kind GetKind() override
{ return BlockStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto statement : GetStatements())
{ os.put('\n'); statement->Print(os, newIndent, statement == GetStatements().back()); }
}
std::vector<shared_ptr<BoundStatement>> GetStatements()
{ return mStatements; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/LabelSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Symbol/LabelSymbol.h"
namespace Symple::Binding
{
class BoundLabel : public BoundStatement
{
private:
shared_ptr<Symbol::LabelSymbol> mSymbol;
public:
BoundLabel(shared_ptr<Syntax::LabelSyntax> syntax, shared_ptr<Symbol::LabelSymbol> symbol)
: BoundStatement(syntax), mSymbol(symbol)
{}
virtual Kind GetKind() override
{ return Label; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " \'" << GetLabel() << '\'';
}
shared_ptr<Symbol::LabelSymbol> GetSymbol()
{ return mSymbol; }
std::string_view GetLabel()
{ return GetSymbol()->GetLabel(); }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/ParenthesizedExpressionSyntax.h"
namespace Symple::Syntax
{
class IfStatementSyntax : public StatementSyntax
{
private:
shared_ptr<ParenthesizedExpressionSyntax> mCondition;
shared_ptr<StatementSyntax> mThen;
shared_ptr<Token> mElseKeyword;
shared_ptr<StatementSyntax> mElse;
public:
IfStatementSyntax(shared_ptr<Token> ifKey, shared_ptr<ParenthesizedExpressionSyntax> cond, shared_ptr<StatementSyntax> then, shared_ptr<Token> elseKey, shared_ptr<StatementSyntax> elze)
: StatementSyntax(ifKey), mCondition(cond), mThen(then), mElseKeyword(elseKey), mElse(elze) {}
virtual Kind GetKind() override
{ return IfStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetCondition()->Print(os, newIndent, false, "Condition = ");
os.put('\n'); GetThen()->Print(os, newIndent, !GetElse(), "Then = ");
if (GetElse())
{ os.put('\n'); GetElse()->Print(os, newIndent, true, "Else = "); }
}
shared_ptr<Token> GetIfKeyword()
{ return GetToken(); }
shared_ptr<ParenthesizedExpressionSyntax> GetCondition()
{ return mCondition; }
shared_ptr<StatementSyntax> GetThen()
{ return mThen; }
shared_ptr<Token> GetElseKeyword()
{ return mElseKeyword; }
shared_ptr<StatementSyntax> GetElse()
{ return mElse; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
class TypeSyntax : public Node
{
public:
TypeSyntax(shared_ptr<Token> name)
: Node(name) {}
virtual Kind GetKind() override
{ return Type; }
virtual void PrintShort(std::ostream& os = std::cout)
{ os << GetName()->GetText(); }
shared_ptr<Token> GetName()
{ return GetToken(); }
};
}<file_sep>#include "SympleCode/Syntax/Token.h"
#include <spdlog/spdlog.h>
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
__SYC_API shared_ptr<Token> Token::Error = make_shared<Token>();
__SYC_API shared_ptr<Token> Token::Default = make_shared<Token>();
Token::Token(Kind kind, shared_ptr<Trivia> trivia, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(), mTrivia(trivia), mLine(ln), mColumn(col), mFile(file)
{}
Token::Token(Kind kind, std::string_view text, shared_ptr<Trivia> trivia, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(text), mTrivia(trivia), mLine(ln), mColumn(col), mFile(file)
{}
Token::Token(Kind kind, char* beg, unsigned len, shared_ptr<Trivia> trivia, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(beg, len), mTrivia(trivia), mLine(ln), mColumn(col), mFile(file)
{}
Token::Token(Kind kind, char* beg, char* end, shared_ptr<Trivia> trivia, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(beg, std::distance(beg, end)), mTrivia(trivia), mLine(ln), mColumn(col), mFile(file)
{}
bool Token::IsKeyword()
{ return mKind >= FirstKeyword; }
bool Token::Is(Kind kind)
{ return mKind == kind; }
void Token::Print(std::ostream& os, std::string_view indent, bool last, std::string_view label)
{
Node::PrintIndent(os, indent, last, label);
os << KindMap[GetKind()] << "Token '" << GetText() << "' ";
GetTrivia()->PrintShort(os);
os << " <" << GetLine() << ':' << GetColumn() << ">";
}
void Token::PrintShort(std::ostream& os)
{ os << '(' << KindMap[mKind] << ") " << mText; }
Token::Kind Token::GetKind()
{ return mKind; }
std::string_view Token::GetText()
{ return mText; }
shared_ptr<Trivia> Token::GetTrivia()
{ return mTrivia; }
char* Token::GetFile()
{ return mFile; }
unsigned Token::GetLine()
{ return mLine; }
unsigned Token::GetColumn()
{ return mColumn; }
}<file_sep>#pragma once
#include "SympleCode/Symbol/Symbol.h"
#include "SympleCode/Symbol/VariableSymbol.h"
namespace Symple::Binding
{
class BoundScope
{
private:
shared_ptr<BoundScope> mBase;
Symbol::VariableList mVariables;
public:
BoundScope(shared_ptr<BoundScope> base = nullptr)
: mBase(base) {}
void DeclareVariable(shared_ptr<Symbol::VariableSymbol> var)
{ mVariables.push_back(var); }
shared_ptr<BoundScope> GetBase()
{ return mBase; }
Symbol::VariableList GetDeclaredVariables()
{ return mVariables; }
shared_ptr<Symbol::VariableSymbol> GetVariableSymbol(std::string_view name)
{
for (auto var : GetDeclaredVariables())
if (var->GetName() == name)
return var;
if (GetBase())
return GetBase()->GetVariableSymbol(name);
else
return nullptr;
}
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/TypeSyntax.h"
namespace Symple::Syntax
{
class TypeReferenceSyntax : public TypeSyntax
{
private:
shared_ptr<TypeSyntax> mBase;
public:
TypeReferenceSyntax(shared_ptr<Token> name, shared_ptr<TypeSyntax> base)
: TypeSyntax(name), mBase(base) {}
virtual Kind GetKind() override
{ return TypeReference; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
PrintIndent(os, indent, last, label);
PrintName(os);
if (GetBase())
{
std::string newIndent(indent);
newIndent += GetAddIndent(last);
GetBase()->Print(os, newIndent, true, "Base = ");
}
}
virtual void PrintShort(std::ostream& os = std::cout) override
{
if (GetBase())
GetBase()->PrintShort(os);
TypeSyntax::PrintShort(os);
}
shared_ptr<TypeSyntax> GetBase()
{ return mBase; }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/Symbol.h"
#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Symbol
{
class VariableSymbol : public Symbol
{
private:
shared_ptr<TypeSymbol> mType;
std::string mName;
public:
VariableSymbol(shared_ptr<TypeSymbol> ty, std::string_view name)
: mType(ty), mName(name)
{}
virtual Kind GetKind() override
{ return Variable; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os); os << ' ' << GetName() << '\'';
}
void PrintShort(std::ostream& os = std::cout)
{ GetType()->PrintShort(os); os << ' ' << GetName(); }
shared_ptr<TypeSymbol> GetType()
{ return mType; }
std::string_view GetName()
{ return mName; }
};
typedef std::vector<shared_ptr<VariableSymbol>> VariableList;
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/Node.h"
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Binding
{
class BoundBinaryOperator
{
public: enum Kind : unsigned;
private:
Syntax::Token::Kind mTokenKind;
Kind mKind;
shared_ptr<Symbol::TypeSymbol> mLeftType, mRightType, mType;
bool mMutable;
BoundBinaryOperator(Syntax::Token::Kind, Kind, shared_ptr<Symbol::TypeSymbol> leftType, shared_ptr<Symbol::TypeSymbol> rightType, shared_ptr<Symbol::TypeSymbol> type, bool isMutable = false);
static std::vector<shared_ptr<BoundBinaryOperator>> sOperators;
public:
void Print(std::ostream& = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "");
void PrintShort(std::ostream& os = std::cout);
static shared_ptr<BoundBinaryOperator> Bind(Syntax::Token::Kind, shared_ptr<Symbol::TypeSymbol> leftType, shared_ptr<Symbol::TypeSymbol> rightType);
static shared_ptr<BoundBinaryOperator> ErrorOperator;
bool IsMutable();
Syntax::Token::Kind GetTokenKind();
Kind GetKind();
shared_ptr<Symbol::TypeSymbol> GetLeftType();
shared_ptr<Symbol::TypeSymbol> GetRightType();
shared_ptr<Symbol::TypeSymbol> GetType();
public:
enum Kind : unsigned
{
Unknown,
Addition,
Subtraction,
Multiplication,
Division,
Modulo,
Assign,
Last = Assign,
};
static constexpr char* KindMap[Last + 1] = {
"Unknown",
"Addition",
"Subtraction",
"Multiplication",
"Division",
"Modulo",
"Assign",
};
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/Symbol.h"
#include "SympleCode/Symbol/VariableSymbol.h"
namespace Symple::Emit
{
class Scope
{
private:
shared_ptr<Scope> mBase;
unsigned mDepth;
Symbol::VariableList mVariables;
public:
Scope(shared_ptr<Scope> base = nullptr)
: mBase(base), mDepth(base ? base->mDepth : 0) {}
void DeclareVariable(shared_ptr<Symbol::VariableSymbol> var)
{ mVariables.push_back(var); }
shared_ptr<Scope> GetBase()
{ return mBase; }
unsigned GetDepth()
{ return mDepth; }
Symbol::VariableList GetDeclaredVariables()
{ return mVariables; }
shared_ptr<Symbol::VariableSymbol> GetVariableSymbol(std::string_view name)
{
for (auto var : GetDeclaredVariables())
if (var->GetName() == name)
return var;
if (GetBase())
return GetBase()->GetVariableSymbol(name);
else
return nullptr;
}
unsigned GetVariableDepth(std::string_view name)
{
for (auto var : GetDeclaredVariables())
if (var->GetName() == name)
return GetDepth();
if (GetBase())
return GetBase()->GetVariableDepth(name);
else
return -1;
}
};
}<file_sep>project "SympleEditor"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
defines {
"SY_32",
"null=0"
}
files {
"inc/**.h",
"inc/**.hpp",
"src/**.c",
"src/**.cpp",
"sy/**.sy",
"vendor/glfw/include/GLFW/glfw3.h",
"vendor/glfw/include/GLFW/glfw3native.h",
"vendor/glfw/src/glfw_config.h",
"vendor/glfw/src/context.c",
"vendor/glfw/src/init.c",
"vendor/glfw/src/input.c",
"vendor/glfw/src/monitor.c",
"vendor/glfw/src/vulkan.c",
"vendor/glfw/src/window.c"
}
includedirs {
"inc",
"vendor/glfw/include"
}
filter "system:windows"
filter "configurations:Debug"
defines "__SY_DEBUG"
symbols "On"
filter "configurations:Release"
defines "__SY_RELEASE"
optimize "On"<file_sep>#pragma once
#include "SympleCode/Syntax/Token.h"
namespace Symple
{
class Diagnostic
{
public: enum Level : unsigned;
private:
Level mLevel;
shared_ptr<Syntax::Token> mToken;
std::string mMessage;
public:
Diagnostic(Level lvl, shared_ptr<Syntax::Token> tok, std::string_view msg)
: mLevel(lvl), mToken(tok), mMessage(msg) {}
Level GetLevel()
{ return mLevel; }
auto GetToken()
{ return mToken; }
std::string_view GetMessage()
{ return mMessage; }
public:
enum Level : unsigned
{
Message,
Warning,
Error,
};
};
}<file_sep>#include "SympleCode/Binding/BoundUnaryOperator.h"
namespace Symple::Binding
{
// Explicit Declaration instead of using 'make_shared' because this is a private constructor
std::vector<shared_ptr<BoundUnaryOperator>> BoundUnaryOperator::sOperators;
shared_ptr<BoundUnaryOperator> BoundUnaryOperator::ErrorOperator = shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Unknown, Negative, Symbol::TypeSymbol::ErrorType, Symbol::TypeSymbol::ErrorType));;
BoundUnaryOperator::BoundUnaryOperator(Syntax::Token::Kind tokenKind, Kind kind, shared_ptr<Symbol::TypeSymbol> operandType, shared_ptr<Symbol::TypeSymbol> type)
: mTokenKind(tokenKind), mKind(kind), mOperandType(operandType), mType(type)
{}
void BoundUnaryOperator::Print(std::ostream& os, std::string_view indent, bool last, std::string_view label)
{
Syntax::Node::PrintIndent(os, indent, last, label);
os << "BoundUnary" << KindMap[GetKind()] << " (" << Syntax::Token::KindMap[GetTokenKind()] << ')';
}
void BoundUnaryOperator::PrintShort(std::ostream& os)
{
os << '(' << KindMap[GetKind()] << ')';
}
shared_ptr<BoundUnaryOperator> BoundUnaryOperator::Bind(Syntax::Token::Kind tokenKind, shared_ptr<Symbol::TypeSymbol> operandType)
{
if (sOperators.empty())
sOperators = {
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Plus, Positive, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Plus, Positive, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Plus, Positive, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Plus, Positive, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Plus, Positive, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Dash, Negative, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Dash, Negative, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Dash, Negative, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Dash, Negative, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Dash, Negative, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Exclamation, Not, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::BoolType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Exclamation, Not, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::BoolType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Exclamation, Not, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::BoolType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Exclamation, Not, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::BoolType)),
shared_ptr<BoundUnaryOperator>(new BoundUnaryOperator(Syntax::Token::Exclamation, Not, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::BoolType)),
};
for (auto op : sOperators)
if (op->GetTokenKind() == tokenKind && op->GetOperandType()->Equals(operandType))
return op;
return ErrorOperator;
}
Syntax::Token::Kind BoundUnaryOperator::GetTokenKind()
{ return mTokenKind; }
BoundUnaryOperator::Kind BoundUnaryOperator::GetKind()
{ return mKind; }
shared_ptr<Symbol::TypeSymbol> BoundUnaryOperator::GetOperandType()
{ return mOperandType; }
shared_ptr<Symbol::TypeSymbol> BoundUnaryOperator::GetType()
{ return mType; }
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
namespace Symple::Syntax
{
class GotoStatementSyntax : public StatementSyntax
{
private:
shared_ptr<Token> mKeyword;
public:
GotoStatementSyntax(shared_ptr<Token> key, shared_ptr<Token> label)
: StatementSyntax(label), mKeyword(key) {}
virtual Kind GetKind() override
{ return GotoStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetLabel()->Print(os, newIndent, true, "Label = ");
}
shared_ptr<Token> GetKeyword()
{ return mKeyword; }
shared_ptr<Token> GetLabel()
{ return GetToken(); }
};
}<file_sep>#pragma once
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundImplicitCastExpression : public BoundExpression
{
private:
shared_ptr<Symbol::TypeSymbol> mType;
shared_ptr<BoundExpression> mCastee;
public:
BoundImplicitCastExpression(shared_ptr<Syntax::ExpressionSyntax> syntax, shared_ptr<Symbol::TypeSymbol> type, shared_ptr<BoundExpression> castee)
: BoundExpression(syntax), mType(type), mCastee(castee) {}
virtual Kind GetKind() override
{ return ImplicitCastExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return mType; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, false, "Type = ");
os.put('\n'); GetCastee()->Print(os, newIndent, true, "Castee = ");
}
shared_ptr<BoundExpression> GetCastee()
{ return mCastee; }
shared_ptr<Symbol::TypeSymbol> GetCasteeType()
{ return GetCastee()->GetType(); }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/Symbol.h"
#include "SympleCode/Symbol/TypeSymbol.h"
#include "SympleCode/Symbol/ParameterSymbol.h"
namespace Symple::Symbol
{
class FunctionSymbol : public Symbol
{
public: enum CallingConvention : unsigned;
private:
shared_ptr<TypeSymbol> mType;
std::string mName;
ParameterList mParameters;
CallingConvention mCallingConvention;
bool mDllImport : 1, mDllExport : 1, mGlobal : 1;
public:
FunctionSymbol(shared_ptr<TypeSymbol> ty, std::string_view name, ParameterList& params, CallingConvention conv, bool dllin, bool dllout, bool isGlobal)
: mType(ty), mName(name), mParameters(params), mCallingConvention(conv), mDllImport(dllin), mDllExport(dllout), mGlobal(isGlobal)
{}
virtual Kind GetKind() override
{ return Function; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '" << GetName() << '\'';
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, GetParameters().empty(), "Return Type = ");
for (auto param : GetParameters())
{ os.put('\n'); param->Print(os, newIndent, param == GetParameters().back(), "[Param] "); }
}
void PrintShort(std::ostream& os = std::cout)
{
GetType()->PrintShort(os); os << ' ' << GetName() << '(';
for (auto param : GetParameters())
{
param->PrintShort(os);
if (param != GetParameters().back())
os << ", ";
}
os.put(')');
}
void PrintSignature(std::ostream& os = std::cout)
{
GetType()->PrintShort(os); os << ' ' << GetName() << '(';
for (auto param : GetParameters())
{
param->GetType()->PrintShort(os);
if (param != GetParameters().back())
os << ", ";
}
os.put(')');
}
shared_ptr<TypeSymbol> GetType()
{ return mType; }
std::string_view GetName()
{ return mName; }
ParameterList GetParameters()
{ return mParameters; }
CallingConvention GetCallingConvention()
{ return mCallingConvention; }
bool IsDllImport()
{ return mDllImport; }
bool IsDllExport()
{ return mDllExport; }
bool IsGlobal()
{ return mGlobal; }
public:
enum CallingConvention : unsigned
{
CDecl,
StdCall,
};
};
}<file_sep>#include "SympleCode/Binding/Binder.h"
#include <string>
#include "SympleCode/Syntax/TypeReferenceSyntax.h"
#include "SympleCode/Syntax/ParenthesizedExpressionSyntax.h"
#include "SympleCode/Symbol/TypeSymbol.h"
#include "SympleCode/Binding/BoundDefaultExpression.h"
#include "SympleCode/Binding/BoundConstantExpression.h"
#include "SympleCode/Binding/BoundImplicitCastExpression.h"
#include "SympleCode/Binding/BoundFunctionPointer.h"
#include "SympleCode/Compiler.h"
namespace Symple::Binding
{
void Binder::BeginScope()
{ mScope = make_shared<BoundScope>(mScope); }
void Binder::EndScope()
{ mScope = mScope->GetBase(); }
std::unordered_map<std::string, shared_ptr<BoundCompilationUnit>> Binder::sImportedSymbols;
shared_ptr<BoundCompilationUnit> Binder::BindImport(shared_ptr<Syntax::ImportStatementSyntax> syntax)
{
std::string path = syntax->GetImport()->GetFile();
path = path.substr(0, path.find_last_of('/') + 1);
path += syntax->GetImport()->GetText();
for (auto symbol : sImportedSymbols)
if (path == symbol.first)
{
auto unit = symbol.second;
for (auto s : unit->GetStructures())
mStructures.push_back(s);
for (auto fn : unit->GetFunctions())
mFunctions.push_back({ fn.first, nullptr });
return unit;
}
for (auto symbol : Compiler::sLibraries)
if (path == symbol)
return make_shared<BoundCompilationUnit>(syntax, StructMap(), FunctionMap());
if (_access(path.c_str(), 0) != -1)
{
Util::ConsoleColor col = Util::GetConsoleColor();
Util::SetConsoleColor(Util::Cyan);
spdlog::info("Import '{}'", path);
Util::SetConsoleColor(col);
unique_ptr<Symple::Compiler> compiler = make_unique<Symple::Compiler>((char*)path.c_str());
compiler->Lex();
compiler->Parse();
compiler->Bind();
compiler->Emit();
compiler->Compile();
col = Util::GetConsoleColor();
Util::SetConsoleColor(Util::Cyan);
spdlog::info("Imported '{}'", path);
Util::SetConsoleColor(col);
auto unit = compiler->mTree;
Symple::Compiler::sUnits.push_back(compiler->mAsmPath);
sImportedSymbols.insert({ path, unit });
for (auto s : unit->GetStructures())
mStructures.push_back(s);
for (auto fn : unit->GetFunctions())
mFunctions.push_back({ fn.first, nullptr });
return unit;
}
else
{
Compiler::sLibraries.push_back(std::string(syntax->GetImport()->GetText()));
return make_shared<BoundCompilationUnit>(syntax, StructMap(), FunctionMap());
}
}
shared_ptr<BoundCompilationUnit> Binder::BindSymbols(shared_ptr<Syntax::TranslationUnitSyntax> unit)
{
mCompilationUnit = unit;
mStructures.clear();
mFunctions.clear();
mScope.reset();
BeginScope();
for (auto member : mCompilationUnit->GetMembers())
BindMemberSymbol(member);
EndScope();
return make_shared<BoundCompilationUnit>(unit, mStructures, mFunctions);
}
shared_ptr<BoundCompilationUnit> Binder::Bind(shared_ptr<Syntax::TranslationUnitSyntax> unit)
{
mCompilationUnit = unit;
mStructures.clear();
mFunctions.clear();
mScope.reset();
BeginScope();
for (auto member : mCompilationUnit->GetMembers())
BindMember(member);
EndScope();
CheckMemberPromises();
CheckFunctionPromises();
return make_shared<BoundCompilationUnit>(unit, mStructures, mFunctions);
}
void Binder::CheckGotoPromises()
{
for (auto promise : mGotoPromises)
{
for (auto label : mLabels)
if (label->GetLabel() == promise->GetPrompt()->GetLabel()->GetText())
{
promise->Complete(label);
break;
}
if (promise->IsBroken())
mDiagnosticBag->ReportUndeclaredLabel(promise->GetPrompt()->GetLabel());
}
}
void Binder::CheckMemberPromises()
{
for (auto promise : mMemPromises)
{
auto ztruct = dynamic_pointer_cast<Symbol::StructTypeSymbol>(promise->GetPrompt().first->GetType());
if (ztruct)
for (auto member : ztruct->GetMembers())
if (promise->GetPrompt().second->GetRight()->GetToken()->GetText() == member->GetName())
{
promise->Complete(member);
break;
}
if (promise->IsBroken())
mDiagnosticBag->ReportBindError(promise->GetPrompt().second);
}
}
void Binder::CheckFunctionPromises()
{
for (auto promise : mFuncPromises)
{
auto syntax = promise->GetPrompt();
shared_ptr<Symbol::FunctionSymbol> funcSymbol = FindFunction(mFunctions, syntax->GetName()->GetText());
ExpressionList args;
if (funcSymbol)
{
if (syntax->GetArguments().size() > funcSymbol->GetParameters().size())
mDiagnosticBag->ReportTooManyArguments(syntax, funcSymbol->GetParameters().size());
else
for (unsigned i = 0; i < funcSymbol->GetParameters().size(); i++)
{
shared_ptr<BoundExpression> arg = make_shared<BoundConstantExpression>(funcSymbol->GetParameters()[i]->GetInitializer());
if (i < syntax->GetArguments().size())
{
auto boundArg = BindExpression(syntax->GetArguments()[i]);
if (boundArg->GetKind() == Node::DefaultExpression)
{
if (!arg->ConstantValue())
{
mDiagnosticBag->ReportNoDefaultArgument(syntax, i);
break;
}
}
else
arg = boundArg;
}
else if (!arg->ConstantValue())
{
mDiagnosticBag->ReportTooFewArguments(syntax);
break;
}
args.push_back(arg);
}
auto pair = std::pair(funcSymbol, args);
promise->Complete(pair);
}
else
mDiagnosticBag->ReportNoSuchFunction(syntax);
}
}
#pragma region Symbols
#define TYPE_CONT(name) \
case Syntax::Token::##name##Keyword: \
return make_shared<Symbol::TypeSymbol>(Symbol::TypeSymbol::##name##Type->GetTypeKind(), Symbol::TypeSymbol::##name##Type->GetName(), Symbol::TypeSymbol::##name##Type->GetSize(), Symbol::TypeSymbol::##name##Type->IsFloat(), pointerCount)
#define TYPE_CASE(name) \
case Syntax::Token::##name##Keyword: \
return Symbol::TypeSymbol::##name##Type
shared_ptr<Symbol::TypeSymbol> Binder::BindType(shared_ptr<Syntax::TypeSyntax> syntax)
{
if (dynamic_pointer_cast<Syntax::TypeReferenceSyntax>(syntax) && dynamic_pointer_cast<Syntax::TypeReferenceSyntax>(syntax)->GetBase())
{
unsigned pointerCount = 0;
shared_ptr<Syntax::TypeSyntax> sy = syntax;
while (sy = dynamic_pointer_cast<Syntax::TypeReferenceSyntax>(sy) ? dynamic_pointer_cast<Syntax::TypeReferenceSyntax>(sy)->GetBase() : nullptr)
{
if (!sy->GetName()->Is(Syntax::Token::Asterisk))
mDiagnosticBag->ReportUnimplimentedError(sy->GetName());
pointerCount++;
}
switch (syntax->GetName()->GetKind())
{
TYPE_CONT(Void);
TYPE_CONT(Byte);
TYPE_CONT(Short);
TYPE_CONT(Int);
TYPE_CONT(Long);
TYPE_CONT(Bool);
TYPE_CONT(Char);
TYPE_CONT(WChar);
TYPE_CONT(Float);
TYPE_CONT(Double);
TYPE_CONT(Triple);
// Special
case Syntax::Token::Asterisk:
return Symbol::TypeSymbol::VoidPointerType;
default:
for (auto s : mStructures)
if (syntax->GetName()->GetText() == s->GetName())
return make_shared<Symbol::TypeSymbol>(s->GetTypeKind(), s->GetName(), s->GetSize(), s->IsFloat(), pointerCount);
return Symbol::TypeSymbol::ErrorType;
}
}
else
{
switch (syntax->GetName()->GetKind())
{
TYPE_CASE(Void);
TYPE_CASE(Byte);
TYPE_CASE(Short);
TYPE_CASE(Int);
TYPE_CASE(Long);
TYPE_CASE(Bool);
TYPE_CASE(Char);
TYPE_CASE(WChar);
TYPE_CASE(Float);
TYPE_CASE(Double);
TYPE_CASE(Triple);
// Special
case Syntax::Token::Asterisk:
return Symbol::TypeSymbol::VoidPointerType;
default:
for (auto s : mStructures)
if (syntax->GetName()->GetText() == s->GetName())
return s;
return Symbol::TypeSymbol::ErrorType;
}
}
}
shared_ptr<Symbol::LabelSymbol> Binder::BindLabelSymbol(shared_ptr<Syntax::LabelSyntax> syntax)
{
shared_ptr<Symbol::LabelSymbol> label = make_shared<Symbol::LabelSymbol>(syntax->GetLabel()->GetText());
mLabels.push_back(label);
return label;
}
shared_ptr<Symbol::FunctionSymbol> Binder::BindFunction(shared_ptr<Syntax::FunctionDeclarationSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty = BindType(syntax->GetType());
std::string_view name = syntax->GetName()->GetText();
Symbol::ParameterList params;
for (auto param : syntax->GetParameters())
params.push_back(BindParameter(param));
Symbol::FunctionSymbol::CallingConvention conv = Symbol::FunctionSymbol::CDecl;
bool dll = false, isGlobal = true;
for (auto mod : syntax->GetModifiers())
switch (mod->GetKind())
{
case Syntax::Token::CDeclKeyword:
conv = Symbol::FunctionSymbol::CDecl;
break;
case Syntax::Token::StdCallKeyword:
conv = Symbol::FunctionSymbol::StdCall;
break;
case Syntax::Token::DllExportKeyword:
dll = true;
break;
case Syntax::Token::DllImportKeyword:
mDiagnosticBag->ReportUnexpectedDllImportBody(mod);
break;
case Syntax::Token::LocalKeyword:
isGlobal = false;
break;
case Syntax::Token::GlobalKeyword:
isGlobal = true;
break;
}
shared_ptr<Symbol::FunctionSymbol> symbol = make_shared<Symbol::FunctionSymbol>(ty, name, params, conv, false, dll, isGlobal);
BeginScope();
for (auto param : symbol->GetParameters())
mScope->DeclareVariable(param);
shared_ptr<BoundStatement> body = BindStatement(syntax->GetBody());
EndScope();
CheckGotoPromises();
mFunctions.push_back({ symbol, body });
return symbol;
}
shared_ptr<Symbol::FunctionSymbol> Binder::BindExternFunction(shared_ptr<Syntax::ExternFunctionSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty = BindType(syntax->GetType());
std::string_view name = syntax->GetName()->GetText();
Symbol::ParameterList params;
for (auto param : syntax->GetParameters())
params.push_back(BindParameter(param));
Symbol::FunctionSymbol::CallingConvention conv = Symbol::FunctionSymbol::CDecl;
bool dll = false, isGlobal = true;
for (auto mod : syntax->GetModifiers())
switch (mod->GetKind())
{
case Syntax::Token::CDeclKeyword:
conv = Symbol::FunctionSymbol::CDecl;
break;
case Syntax::Token::StdCallKeyword:
conv = Symbol::FunctionSymbol::StdCall;
break;
case Syntax::Token::DllImportKeyword:
dll = true;
break;
case Syntax::Token::LocalKeyword:
isGlobal = false;
break;
case Syntax::Token::GlobalKeyword:
isGlobal = true;
break;
}
shared_ptr<Symbol::FunctionSymbol> symbol = make_shared<Symbol::FunctionSymbol>(ty, name, params, conv, dll, false, isGlobal);
mFunctions.push_back({ symbol, nullptr });
return symbol;
}
shared_ptr<Symbol::ParameterSymbol> Binder::BindParameter(shared_ptr<Syntax::VariableDeclarationSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty = BindType(syntax->GetType());
std::string_view name = syntax->GetName()->GetText();
shared_ptr<BoundConstant> init;
if (syntax->GetInitializer())
init = BindExpression(syntax->GetInitializer())->ConstantValue();
return make_shared<Symbol::ParameterSymbol>(ty, name, init);
}
shared_ptr<Symbol::MemberSymbol> Binder::BindMember(shared_ptr<Syntax::VariableDeclarationSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty = BindType(syntax->GetType());
std::string_view name = syntax->GetName()->GetText();
shared_ptr<BoundConstant> init;
if (syntax->GetInitializer())
init = BindExpression(syntax->GetInitializer())->ConstantValue();
return make_shared<Symbol::MemberSymbol>(ty, name, init);
}
shared_ptr<Symbol::StructTypeSymbol> Binder::BindStructType(shared_ptr<Syntax::StructDeclarationSyntax> syntax)
{
unsigned sz = 0;
Symbol::MemberList members;
for (auto member : syntax->GetMembers())
{
auto memberSymbol = BindMember(member);
sz += memberSymbol->GetType()->GetSize();
members.push_back(memberSymbol);
}
shared_ptr<Symbol::StructTypeSymbol> symbol = make_shared<Symbol::StructTypeSymbol>(syntax->GetName()->GetText(), sz, members);
mStructures.push_back(symbol);
return symbol;
}
#pragma endregion
#pragma region Members
shared_ptr<Symbol::Symbol> Binder::BindMemberSymbol(shared_ptr<Syntax::MemberSyntax> syntax)
{
switch (syntax->GetKind())
{
case Syntax::Node::StructDeclaration:
return BindStructType(dynamic_pointer_cast<Syntax::StructDeclarationSyntax>(syntax));
case Syntax::Node::ExternFunction:
return BindExternFunction(dynamic_pointer_cast<Syntax::ExternFunctionSyntax>(syntax));
case Syntax::Node::FunctionDeclaration:
return BindFunction(dynamic_pointer_cast<Syntax::FunctionDeclarationSyntax>(syntax));
case Syntax::Node::ImportStatement:
BindImport(dynamic_pointer_cast<Syntax::ImportStatementSyntax>(syntax));
return make_shared<Symbol::Symbol>();
}
}
shared_ptr<Node> Binder::BindMember(shared_ptr<Syntax::MemberSyntax> syntax)
{
shared_ptr<Node> result = BindMemberInternal(syntax);
mGotoPromises.clear();
mLabels.clear();
if (!result /* Should not be null, but just in case */)
{
mDiagnosticBag->ReportBindError(syntax);
return make_shared<Node>(syntax);
}
else
return result;
}
shared_ptr<Node> Binder::BindMemberInternal(shared_ptr<Syntax::MemberSyntax> syntax)
{
switch (syntax->GetKind())
{
case Syntax::Node::GlobalStatement:
return BindGlobalStatement(dynamic_pointer_cast<Syntax::GlobalStatementSyntax>(syntax));
case Syntax::Node::StructDeclaration:
BindStructType(dynamic_pointer_cast<Syntax::StructDeclarationSyntax>(syntax));
goto Return;
case Syntax::Node::ExternFunction:
BindExternFunction(dynamic_pointer_cast<Syntax::ExternFunctionSyntax>(syntax));
goto Return;
case Syntax::Node::FunctionDeclaration:
BindFunction(dynamic_pointer_cast<Syntax::FunctionDeclarationSyntax>(syntax));
goto Return;
case Syntax::Node::ImportStatement:
BindImport(dynamic_pointer_cast<Syntax::ImportStatementSyntax>(syntax));
goto Return;
default:
Return:
return make_shared<Node>(syntax);
}
}
shared_ptr<BoundStatement> Binder::BindGlobalStatement(shared_ptr<Syntax::GlobalStatementSyntax> syntax)
{ return BindStatement(syntax->GetStatement()); }
#pragma endregion
#pragma region Statement
shared_ptr<BoundStatement> Binder::BindStatement(shared_ptr<Syntax::StatementSyntax> syntax)
{
shared_ptr<BoundStatement> result = BindStatementInternal(syntax);
if (!result /* Should not be null, but just in case */)
{
mDiagnosticBag->ReportBindError(syntax);
return make_shared<BoundStatement>(syntax);
}
else
return result;
}
shared_ptr<BoundStatement> Binder::BindStatementInternal(shared_ptr<Syntax::StatementSyntax> syntax)
{
switch (syntax->GetKind())
{
case Syntax::Node::Label:
return BindLabel(dynamic_pointer_cast<Syntax::LabelSyntax>(syntax));
case Syntax::Node::NativeStatement:
return BindNativeCode(dynamic_pointer_cast<Syntax::NativeStatementSyntax>(syntax));
case Syntax::Node::IfStatement:
return BindIfStatement(dynamic_pointer_cast<Syntax::IfStatementSyntax>(syntax));
case Syntax::Node::GotoStatement:
return BindGotoStatement(dynamic_pointer_cast<Syntax::GotoStatementSyntax>(syntax));
case Syntax::Node::BlockStatement:
return BindBlockStatement(dynamic_pointer_cast<Syntax::BlockStatementSyntax>(syntax));
case Syntax::Node::ReturnStatement:
return BindReturnStatement(dynamic_pointer_cast<Syntax::ReturnStatementSyntax>(syntax));
case Syntax::Node::ExpressionStatement:
return BindExpressionStatement(dynamic_pointer_cast<Syntax::ExpressionStatementSyntax>(syntax));
case Syntax::Node::VariableDeclaration:
return BindVariableDeclaration(dynamic_pointer_cast<Syntax::VariableDeclarationSyntax>(syntax));
default:
return make_shared<BoundStatement>(syntax);
}
}
shared_ptr<BoundLabel> Binder::BindLabel(shared_ptr<Syntax::LabelSyntax> syntax)
{ return make_shared<BoundLabel>(syntax, BindLabelSymbol(syntax)); }
shared_ptr<BoundNativeCode> Binder::BindNativeCode(shared_ptr<Syntax::NativeStatementSyntax> syntax)
{ return make_shared<BoundNativeCode>(syntax); }
shared_ptr<BoundIfStatement> Binder::BindIfStatement(shared_ptr<Syntax::IfStatementSyntax> syntax)
{
shared_ptr<BoundExpression> cond = BindExpression(syntax->GetCondition());
shared_ptr<BoundStatement> then = BindStatement(syntax->GetThen());
shared_ptr<BoundStatement> elze = BindStatement(syntax->GetElse());
return make_shared<BoundIfStatement>(syntax, cond, then, elze);
}
shared_ptr<BoundGotoStatement> Binder::BindGotoStatement(shared_ptr<Syntax::GotoStatementSyntax> syntax)
{
shared_ptr<GotoPromise> promise = make_shared<GotoPromise>(syntax);
mGotoPromises.push_back(promise);
return make_shared<BoundGotoStatement>(syntax, promise);
}
shared_ptr<BoundBlockStatement> Binder::BindBlockStatement(shared_ptr<Syntax::BlockStatementSyntax> syntax)
{
std::vector<shared_ptr<BoundStatement>> statements;
BeginScope();
for (auto statement : syntax->GetStatements())
statements.push_back(BindStatement(statement));
EndScope();
return make_shared<BoundBlockStatement>(syntax, statements);
}
shared_ptr<BoundReturnStatement> Binder::BindReturnStatement(shared_ptr<Syntax::ReturnStatementSyntax> syntax)
{ return make_shared<BoundReturnStatement>(syntax, BindExpression(syntax->GetValue())); }
shared_ptr<BoundExpressionStatement> Binder::BindExpressionStatement(shared_ptr<Syntax::ExpressionStatementSyntax> syntax)
{ return make_shared<BoundExpressionStatement>(syntax, BindExpression(syntax->GetExpression())); }
shared_ptr<BoundVariableDeclaration> Binder::BindVariableDeclaration(shared_ptr<Syntax::VariableDeclarationSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty = BindType(syntax->GetType());
std::string_view name = syntax->GetName()->GetText();
shared_ptr<BoundExpression> init;
if (syntax->GetInitializer())
init = BindExpression(syntax->GetInitializer());
shared_ptr<Symbol::VariableSymbol> symbol = make_shared<Symbol::VariableSymbol>(ty, name);
mScope->DeclareVariable(symbol);
return make_shared<BoundVariableDeclaration>(syntax, symbol, init);
}
#pragma endregion
#pragma region Expression
shared_ptr<BoundExpression> Binder::BindExpression(shared_ptr<Syntax::ExpressionSyntax> syntax)
{
shared_ptr<BoundExpression> result = BindExpressionInternal(syntax);
if (!result /* Should not be null, but just in case */ || result->GetType()->Is(Symbol::TypeSymbol::Error))
{
mDiagnosticBag->ReportExpressionMustHaveValue(syntax);
return make_shared<BoundErrorExpression>(syntax);
}
else
return result;
}
shared_ptr<BoundExpression> Binder::BindExpressionInternal(shared_ptr<Syntax::ExpressionSyntax> syntax)
{
switch (syntax->GetKind())
{
case Syntax::Node::CallExpression:
return BindCallExpression(dynamic_pointer_cast<Syntax::CallExpressionSyntax>(syntax));
case Syntax::Node::UnaryExpression:
return BindUnaryExpression(dynamic_pointer_cast<Syntax::UnaryExpressionSyntax>(syntax));
case Syntax::Node::BinaryExpression:
return BindBinaryExpression(dynamic_pointer_cast<Syntax::BinaryExpressionSyntax>(syntax));
case Syntax::Node::LiteralExpression:
return BindLiteralExpression(dynamic_pointer_cast<Syntax::LiteralExpressionSyntax>(syntax));
case Syntax::Node::NameExpression:
return BindNameExpression(dynamic_pointer_cast<Syntax::NameExpressionSyntax>(syntax));
case Syntax::Node::ParenthesizedExpression:
return BindExpressionInternal(dynamic_pointer_cast<Syntax::ParenthesizedExpressionSyntax>(syntax)->GetExpression());
default:
return make_shared<BoundErrorExpression>(syntax);
}
}
shared_ptr<BoundExpression> Binder::BindCallExpression(shared_ptr<Syntax::CallExpressionSyntax> syntax)
{
shared_ptr<FunctionPromise> promise = make_shared<FunctionPromise>(syntax);
mFuncPromises.push_back(promise);
return make_shared<BoundCallExpression>(syntax, promise);
}
shared_ptr<BoundUnaryExpression> Binder::BindUnaryExpression(shared_ptr<Syntax::UnaryExpressionSyntax> syntax)
{
shared_ptr<BoundExpression> operand = BindExpression(syntax->GetOperand());
shared_ptr<BoundUnaryOperator> op = BoundUnaryOperator::Bind(syntax->GetOperator()->GetKind(), operand->GetType());
if (op == BoundUnaryOperator::ErrorOperator)
mDiagnosticBag->ReportInvalidOperation(syntax->GetOperator(), operand->GetType());
return make_shared<BoundUnaryExpression>(syntax, op, operand);
}
shared_ptr<BoundExpression> Binder::BindBinaryExpression(shared_ptr<Syntax::BinaryExpressionSyntax> syntax)
{
shared_ptr<BoundExpression> left = BindExpression(syntax->GetLeft());
if (syntax->GetOperator()->Is(Syntax::Token::Period))
{
shared_ptr<MemberPromise> promise = make_shared<MemberPromise>(std::pair(left, syntax));
mMemPromises.push_back(promise);
return make_shared<BoundFieldExpression>(syntax, promise);
}
shared_ptr<BoundExpression> right = BindExpression(syntax->GetRight());
shared_ptr<BoundBinaryOperator> op = BoundBinaryOperator::Bind(syntax->GetOperator()->GetKind(), left->GetType(), right->GetType());
if (op == BoundBinaryOperator::ErrorOperator)
{
mDiagnosticBag->ReportInvalidOperation(syntax->GetOperator(), left->GetType(), right->GetType());
return make_shared<BoundErrorExpression>(syntax);
}
else if (op->IsMutable() && !left->IsMutable())
{
mDiagnosticBag->ReportExpectedLValue(left->GetSyntax()->GetToken());
return make_shared<BoundErrorExpression>(syntax);
}
return make_shared<BoundBinaryExpression>(syntax, op, left, right);
}
shared_ptr<BoundExpression> Binder::BindLiteralExpression(shared_ptr<Syntax::LiteralExpressionSyntax> syntax)
{
shared_ptr<Symbol::TypeSymbol> ty;
shared_ptr<BoundConstant> constant;
switch (syntax->GetLiteral()->GetKind())
{
case Syntax::Token::Integer:
{
if (std::stoll(std::string(syntax->GetLiteral()->GetText())) & 0xFFFFFFFF00000000)
ty = Symbol::TypeSymbol::LongType;
else
ty = Symbol::TypeSymbol::IntType;
long long val = std::stoll(std::string(syntax->GetLiteral()->GetText()));
constant = make_shared<BoundConstant>(BoundConstant::Integer, &val);
break;
}
case Syntax::Token::Number:
{
ty = Symbol::TypeSymbol::DoubleType;
double val = std::stod(std::string(syntax->GetLiteral()->GetText()));
constant = make_shared<BoundConstant>(BoundConstant::Float, &val);
break;
}
case Syntax::Token::Float:
{
ty = Symbol::TypeSymbol::FloatType;
float val = std::stof(std::string(syntax->GetLiteral()->GetText()));
constant = make_shared<BoundConstant>(BoundConstant::Float, &val);
break;
}
case Syntax::Token::String:
{
ty = Symbol::TypeSymbol::CharPointerType;
break;
}
case Syntax::Token::DefaultKeyword:
{
return make_shared<BoundDefaultExpression>(syntax);
}
default:
ty = Symbol::TypeSymbol::ErrorType;
break;
}
return make_shared<BoundLiteralExpression>(syntax, ty, constant);
}
shared_ptr<BoundExpression> Binder::BindNameExpression(shared_ptr<Syntax::NameExpressionSyntax> syntax)
{
shared_ptr<Symbol::VariableSymbol> varSymbol = mScope->GetVariableSymbol(syntax->GetToken()->GetText());
if (varSymbol)
return make_shared<BoundVariableExpression>(syntax, varSymbol);
else
{
shared_ptr<Symbol::FunctionSymbol> fnSymbol = FindFunction(mFunctions, syntax->GetToken()->GetText());
if (fnSymbol)
return make_shared<BoundFunctionPointer>(syntax, fnSymbol);
else
{
mDiagnosticBag->ReportUndeclaredIdentifier(syntax->GetToken());
return make_shared<BoundErrorExpression>(syntax);
}
}
}
#pragma endregion
shared_ptr<DiagnosticBag> Binder::GetDiagnosticBag()
{ return mDiagnosticBag; }
}<file_sep>#pragma once
#include <iostream>
#include "SympleCode/Util/ConsoleColor.h"
#include "SympleCode/Syntax/Token.h"
namespace Symple::Syntax
{
class Node
{
public: enum Kind : unsigned;
protected:
shared_ptr<Token> mToken;
void PrintName(std::ostream& os = std::cout)
{ os << KindMap[GetKind()] << "Syntax"; }
public:
Node(shared_ptr<Token> tok)
: mToken(tok) {}
bool Is(Kind kind)
{ return GetKind() == kind; }
template <typename... Args>
bool Is(Kind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
virtual Kind GetKind()
{ return Unknown; }
shared_ptr<Token> GetToken()
{ return mToken; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
PrintIndent(os, indent, last, label);
PrintName(os);
os.put('\n'); GetToken()->Print(os, std::string(indent) + GetAddIndent(last), true, "Token = ");
}
virtual void PrintShort(std::ostream& os)
{ PrintName(os); os << ": "; GetToken()->PrintShort(os); }
static void PrintIndent(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
Util::SetConsoleColor(Util::ConsoleColor::DarkGrey);
os << indent;
if (last)
os << "L--";
else
os << "|--";
Util::SetConsoleColor(Util::ConsoleColor::Cyan);
os << label;
Util::SetConsoleColor(Util::ConsoleColor::Green);
}
static char* GetAddIndent(bool last = true)
{
if (last)
return " ";
else
return "| ";
}
public:
enum Kind : unsigned
{
Unknown,
TranslationUnit,
Member,
ExternFunction,
GlobalStatement,
FunctionDeclaration,
StructDeclaration,
Statement,
Type,
TypeReference,
ImportStatement,
NativeStatement,
Label,
IfStatement,
GotoStatement,
BlockStatement,
ReturnStatement,
ExpressionStatement,
VariableDeclaration,
Expression,
UnaryExpression,
BinaryExpression,
LiteralExpression,
ParenthesizedExpression,
NameExpression,
CallExpression,
Last = CallExpression,
};
static constexpr char* KindMap[Last + 1] = {
"Unknown",
"TranslationUnit",
"Member",
"ExternFunction",
"GlobalStatement",
"FunctionDeclaration",
"StructDeclaration",
"Statement",
"Type",
"TypeReference",
"ImportStatement",
"NativeStatement",
"Label",
"IfStatement",
"GotoStatement",
"BlockStatement",
"ReturnStatement",
"ExpressionStatement",
"VariableDeclaration",
"Expression",
"UnaryExpression",
"BinaryExpression",
"LiteralExpression",
"ParenthesizedExpression",
"NameExpression",
"CallExpression",
};
};
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/TranslationUnitSyntax.h"
#include "SympleCode/Binding/Node.h"
#include "SympleCode/Binding/BoundBlockStatement.h"
#include "SympleCode/Symbol/FunctionSymbol.h"
#include "SympleCode/Symbol/StructTypeSymbol.h"
namespace Symple::Binding
{
typedef std::vector<shared_ptr<Symbol::StructTypeSymbol>> StructMap;
typedef std::vector<std::pair<shared_ptr<Symbol::FunctionSymbol>, shared_ptr<BoundStatement>>> FunctionMap;
inline shared_ptr<Symbol::StructTypeSymbol> FindStruct(StructMap structs, std::string_view name)
{
for (auto s : structs)
if (s->GetName() == name)
return s;
return nullptr;
}
inline shared_ptr<Symbol::FunctionSymbol> FindFunction(FunctionMap funcs, std::string_view name)
{
for (auto fn : funcs)
if (fn.first->GetName() == name)
return fn.first;
return nullptr;
}
class BoundCompilationUnit : public Node
{
private:
StructMap mStructures;
FunctionMap mFunctions;
public:
BoundCompilationUnit(shared_ptr<Syntax::Node> syntax, StructMap structs, FunctionMap funcs)
: Node(syntax), mStructures(structs), mFunctions(funcs) {}
virtual Kind GetKind() override
{ return CompilationUnit; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto &s : GetStructures())
{ os << '\n'; s->Print(os, newIndent, true, "[Struct] "); }
for (auto &func : GetFunctions())
{
os.put('\n'); func.first->Print(os, newIndent, !func.second && func == GetFunctions().back(), "[Function] ");
if (func.second)
{ os.put('\n'); func.second->Print(os, newIndent, func == GetFunctions().back(), "Body = "); }
}
}
StructMap GetStructures()
{ return mStructures; }
FunctionMap GetFunctions()
{ return mFunctions; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class ParenthesizedExpressionSyntax : public ExpressionSyntax
{
private:
shared_ptr<ExpressionSyntax> mExpression;
shared_ptr<Token> mClose;
public:
ParenthesizedExpressionSyntax(shared_ptr<Token> open, shared_ptr<ExpressionSyntax> expression, shared_ptr<Token> close)
: ExpressionSyntax(open), mExpression(expression), mClose(close) {}
virtual Kind GetKind() override
{ return ParenthesizedExpression; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetExpression()->Print(os, newIndent, true, "Expression = ");
}
shared_ptr<Token> GetOpen()
{ return GetToken(); }
shared_ptr<ExpressionSyntax> GetExpression()
{ return mExpression; }
shared_ptr<Token> GetClose()
{ return mClose; }
};
}<file_sep>#pragma once
#include <memory>
#include <spdlog/spdlog.h>
#if __SY_DEBUG
#define __SY_ASSERT(cond, msg, ...) if (!(cond)) { spdlog::critical("(Assertion Failed) '{}'@{}: " #msg, __FILE__, __LINE__, ##__VA_ARGS__); __debugbreak(); }
#else
#define __SY_ASSERT(cond, msg, ...)
#endif
#if __SY_BUILD_DLL
#define __SYC_API __declspec(dllexport)
#elif __SY_BUILD_STATIC
#define __SYC_API
#else
#define __SYC_API
#endif
namespace Symple
{
using std::shared_ptr;
using std::make_shared;
using std::unique_ptr;
using std::make_unique;
using std::dynamic_pointer_cast;
}
#undef GetObject<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/MemberSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/VariableDeclarationSyntax.h"
#include "SympleCode/Syntax/TypeSyntax.h"
namespace Symple::Syntax
{
class ExternFunctionSyntax : public MemberSyntax
{
private:
shared_ptr<Token> mKeyword;
shared_ptr<TypeSyntax> mType;
shared_ptr<Token> mOpenParenthesis;
VariableDeclarationList mParameters;
shared_ptr<Token> mCloseParenthesis;
TokenList mModifiers;
public:
ExternFunctionSyntax(shared_ptr<Token> keyword, shared_ptr<TypeSyntax> type, shared_ptr<Token> name,
shared_ptr<Token> openParen, VariableDeclarationList& params, shared_ptr<Token> closeParen,
TokenList mods)
: MemberSyntax(name), mKeyword(keyword), mType(type), mOpenParenthesis(openParen), mParameters(params), mCloseParenthesis(closeParen), mModifiers(mods) {}
virtual Kind GetKind() override
{ return ExternFunction; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os); os << ' ' << GetName()->GetText(); os.put('(');
for (auto param : GetParameters())
{
param->GetType()->PrintShort(os);
if (param != GetParameters().back())
os << ", ";
}
os.put(')');
if (!GetModifiers().empty())
os.put(' ');
for (auto mod : GetModifiers())
{
mod->PrintShort(os);
if (mod != GetModifiers().back())
os << ", ";
}
os.put('\'');
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto param : GetParameters())
{ os.put('\n'); param->Print(os, newIndent, param == GetParameters().back(), "[Param] "); }
}
shared_ptr<Token> GetKeyword()
{ return mKeyword; }
shared_ptr<TypeSyntax> GetType()
{ return mType; }
shared_ptr<Token> GetName()
{ return GetToken(); }
shared_ptr<Token> GetOpenParenthesis()
{ return mOpenParenthesis; }
VariableDeclarationList GetParameters()
{ return mParameters; }
shared_ptr<Token> GetCloseParenthesis()
{ return mCloseParenthesis; }
TokenList& GetModifiers()
{ return mModifiers; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
namespace Symple::Syntax
{
class LabelSyntax : public StatementSyntax
{
private:
shared_ptr<Token> mColon;
public:
LabelSyntax(shared_ptr<Token> label, shared_ptr<Token> colon)
: StatementSyntax(label), mColon(colon) {}
virtual Kind GetKind() override
{ return Label; }
shared_ptr<Token> GetLabel()
{ return GetToken(); }
shared_ptr<Token> GetColon()
{ return mColon; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/GotoStatementSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Symbol/Promise.h"
#include "SympleCode/Symbol/LabelSymbol.h"
namespace Symple::Binding
{
typedef Promise<shared_ptr<Symbol::LabelSymbol>, shared_ptr<Syntax::GotoStatementSyntax>> GotoPromise;
class BoundGotoStatement : public BoundStatement
{
private:
shared_ptr<GotoPromise> mLabel;
public:
BoundGotoStatement(shared_ptr<Syntax::GotoStatementSyntax> syntax, shared_ptr<GotoPromise> symbol)
: BoundStatement(syntax), mLabel(symbol)
{}
virtual Kind GetKind() override
{ return GotoStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " \'" << GetLabel() << '\'';
}
auto GetLabelSymbol()
{ return mLabel; }
std::string_view GetLabel()
{ return mLabel->GetPrompt()->GetToken()->GetText(); }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class ExpressionStatementSyntax : public StatementSyntax
{
private:
shared_ptr<ExpressionSyntax> mExpression;
public:
ExpressionStatementSyntax(shared_ptr<ExpressionSyntax> expr)
: StatementSyntax(expr->GetToken()), mExpression(expr) {}
virtual Kind GetKind() override
{ return ExpressionStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetExpression()->Print(os, newIndent, true, "Expression = ");
}
shared_ptr<ExpressionSyntax> GetExpression()
{ return mExpression; }
};
}<file_sep>#pragma once
#include <iostream>
#include <string_view>
#include "SympleCode/Memory.h"
namespace Symple::Syntax
{
class __SYC_API Trivia
{
public: typedef unsigned Kind;
private:
Kind mKind;
std::string mText;
char* mFile;
unsigned mLine, mColumn;
public:
Trivia(Kind = Unknown, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Trivia(Kind, std::string_view text, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Trivia(Kind, char* beg, unsigned len = 1, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Trivia(Kind, char* beg, char* end, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
bool Is(Kind kind);
template <typename... Args>
bool Is(Kind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
void Print(std::ostream& = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "");
void PrintShort(std::ostream& = std::cout);
Kind GetKind();
std::string_view GetText();
char* GetFile();
unsigned GetLine();
unsigned GetColumn();
static shared_ptr<Trivia> Error;
static shared_ptr<Trivia> Default;
public:
enum _Kind : unsigned
{
Unknown = 0 << 0,
StartOfLine = 1 << 0,
LeadingSpace = 1 << 1,
Length = 3,
};
static constexpr Kind KindArray[Length] = {
Unknown,
StartOfLine,
LeadingSpace,
};
static constexpr char* KindMap[Length] = {
"Unknown",
"StartOfLine",
"LeadingSpace",
};
};
}<file_sep>#include "SympleCode/Compiler.h"
#include <sstream>
#include <spdlog/spdlog.h>
#include "SympleCode/Syntax/Lexer.h"
#include "SympleCode/Syntax/Parser.h"
#include "SympleCode/Binding/Binder.h"
#include "SympleCode/Emit/AsmEmitter.h"
#include "SympleCode/Util/ConsoleColor.h"
namespace Symple
{
std::vector<std::string> Compiler::sLibraries;
std::vector<std::string> Compiler::sUnits;
Compiler::Compiler(char *path)
: mPath(path)
{
// Store output folder
mAsmPath = mPath.substr(0, mPath.find_first_of('/')) +
"/bin" + mPath.substr(mPath.find_first_of('/'),
mPath.find_last_of('.') - mPath.find_first_of('/')) + ".S";
// Make sure output path exists
unsigned last = 0;
while (mAsmPath.find('/', last) != std::string::npos)
{
std::string newDir = "./" + mAsmPath.substr(0, mAsmPath.find('/', last));
_mkdir(newDir.c_str());
last = mAsmPath.find('/', last) + 1;
}
}
shared_ptr<DiagnosticBag> Compiler::Lex()
{
if (mAnyErrors)
return nullptr;
unique_ptr<Syntax::Lexer> lexer = make_unique<Syntax::Lexer>((char*)mPath.c_str());
mTokens.clear();
do
mTokens.push_back(lexer->Lex());
while (!mTokens.back()->Is(Syntax::Token::EndOfFile));
if (PrintDiagnosticBag(lexer->GetDiagnosticBag(), "Lexing"))
return lexer->GetDiagnosticBag();
#if __SY_DEBUG
std::stringstream ss;
for (auto tok : mTokens)
{
tok->Print(ss, "", tok->Is(Syntax::Token::EndOfFile));
ss.put('\n');
}
spdlog::debug("Lex Tokens:\n{}", ss.str());
#endif
return lexer->GetDiagnosticBag();
}
shared_ptr<DiagnosticBag> Compiler::Parse()
{
if (mAnyErrors)
return nullptr;
unique_ptr<Syntax::Parser> parser = make_unique<Syntax::Parser>(mTokens);
mAST = parser->Parse();
if (PrintDiagnosticBag(parser->GetDiagnosticBag(), "Parsing"))
return parser->GetDiagnosticBag();
#if __SY_DEBUG
std::stringstream ss;
mAST->Print(ss);
ss.put('\n');
spdlog::debug("Parse Tree:\n{}", ss.str());
#endif
return parser->GetDiagnosticBag();
}
shared_ptr<DiagnosticBag> Compiler::Bind()
{
if (mAnyErrors)
return nullptr;
shared_ptr<Binding::Binder> binder = make_shared<Binding::Binder>();
mTree = binder->Bind(mAST);
if (PrintDiagnosticBag(binder->GetDiagnosticBag(), "Binding"))
return binder->GetDiagnosticBag();
#if __SY_DEBUG
std::stringstream ss;
mTree->Print(ss);
ss.put('\n');
spdlog::info("Bound Tree:\n{}", ss.str());
using namespace Symple::Util;
ResetConsoleColor();
#endif
return binder->GetDiagnosticBag();
}
shared_ptr<Binding::BoundCompilationUnit> Compiler::BindSymbols()
{
if (mAnyErrors)
return nullptr;
shared_ptr<Binding::Binder> binder = make_shared<Binding::Binder>();
mTree = binder->BindSymbols(mAST);
if (PrintDiagnosticBag(binder->GetDiagnosticBag(), "Importing"))
return mTree;
#if __SY_DEBUG
std::stringstream ss;
mTree->Print(ss);
spdlog::info("Bound Tree:\n{}", ss.str());
ss.put('\n');
using namespace Symple::Util;
ResetConsoleColor();
#endif
return mTree;
}
void Compiler::Emit()
{
if (mAnyErrors)
return;
mEmitter = make_unique<Emit::AsmEmitter>((char*)mAsmPath.c_str());
mEmitter->Emit(mTree);
}
void Compiler::Compile()
{
if (mAnyErrors)
return;
mEmitter->Compile();
mEmitter.release();
}
bool Compiler::Link(std::string_view output, bool isLib)
{
if (mAnyErrors)
return false;
std::stringstream linkcmd;
linkcmd << "clang -m32 --optimize" << (isLib ? " -shared" : "") << " -o " << output << ' ' << mAsmPath.substr(0, mAsmPath.find_last_of('.')) << ".obj";
for (auto unit : sUnits)
linkcmd << ' ' << unit.substr(0, unit.find_last_of('.')) << ".obj";
for (auto lib : sLibraries)
linkcmd << " -l " << lib;
sUnits.clear();
sLibraries.clear();
return !system(linkcmd.str().c_str());
}
int Compiler::Exec(std::string_view args)
{
Util::SetConsoleColor(Util::Yellow);
puts("Executing program...");
Util::ResetConsoleColor();
char* cmd = new char[17 + args.length()];
snprintf(cmd, 17 + args.length(), "sy\\bin\\Main.exe %s", args.data());
int ec = system(cmd);
delete cmd;
Util::SetConsoleColor(Util::Yellow);
printf("\nProgram Exited with code %i (0x%x)", ec, ec);
Util::ResetConsoleColor();
return ec;
}
bool Compiler::PrintDiagnosticBag(shared_ptr<DiagnosticBag> diagnostics, char *step)
{
using namespace Symple::Util;
SetConsoleColor(Yellow);
for (shared_ptr<Diagnostic> diagnostic : diagnostics->GetDiagnostics())
switch (diagnostic->GetLevel())
{
case Diagnostic::Message:
spdlog::info("'{}' {}:{} \"{}\"", diagnostic->GetToken()->GetFile(), diagnostic->GetToken()->GetLine(), diagnostic->GetToken()->GetColumn(), diagnostic->GetMessage());
break;
case Diagnostic::Warning:
spdlog::warn("'{}' {}:{} \"{}\"", diagnostic->GetToken()->GetFile(), diagnostic->GetToken()->GetLine(), diagnostic->GetToken()->GetColumn(), diagnostic->GetMessage());
break;
case Diagnostic::Error:
spdlog::error("'{}' {}:{} \"{}\"", diagnostic->GetToken()->GetFile(), diagnostic->GetToken()->GetLine(), diagnostic->GetToken()->GetColumn(), diagnostic->GetMessage());
break;
}
if (diagnostics->GetErrorCount())
{
spdlog::info("{} '{}' failed with {} errors, {} warnings, {} messages", step, mPath, diagnostics->GetErrorCount(), diagnostics->GetWarningCount(), diagnostics->GetMessageCount());
return mAnyErrors = true;
}
else
{
spdlog::info("{} '{}' completed with {} errors, {} warnings, {} messages", step, mPath, diagnostics->GetErrorCount(), diagnostics->GetWarningCount(), diagnostics->GetMessageCount());
return false;
}
}
}<file_sep>#pragma once
#include "SympleCode/Symbol/TypeSymbol.h"
#include "SympleCode/Symbol/MemberSymbol.h"
namespace Symple::Symbol
{
class StructTypeSymbol: public TypeSymbol
{
private:
MemberList mMembers;
public:
StructTypeSymbol(std::string_view name, unsigned sz, MemberList members)
: TypeSymbol(Struct, name, sz), mMembers(members) {}
virtual Kind GetKind() override
{ return StructType; }
virtual void Print(std::ostream &os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '" << GetName() << '\'';
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto member : GetMembers())
{ os << '\n'; member->Print(os, newIndent, member == GetMembers().back(), "[Member] "); }
}
void PrintShort(std::ostream &os = std::cout)
{
os << GetName() << " { ";
for (auto member : GetMembers())
{
member->PrintShort(os);
if (member != GetMembers().back())
os << ", ";
}
os << " }";
}
MemberList GetMembers()
{ return mMembers; }
};
}<file_sep>- [X] Lexer
- [X] Parser
- [X] Binder
- [X] Assembly Emitter
---
- [X] Functions
- [X] External Functions
- [X] Function Pointers
- [X] Variables
- [X] Assignment
---
- [X] Import Symbols from File
- [X] Link DLL in code
- [ ] C Preprocessor
- [ ] Global Variables
- [ ] Casting
- [ ] Function Types
- [\] Loops
- [X] Labels and Gotos
- [X] Native Code (Assembly)
<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Binding
{
class Node
{
public: enum Kind : unsigned;
protected:
shared_ptr<Syntax::Node> mSyntax;
void PrintName(std::ostream& os = std::cout)
{ os << "Bound" << KindMap[GetKind()]; }
public:
static void PrintIndent(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{ return Syntax::Node::PrintIndent(os, indent, last, label); }
static char* GetAddIndent(bool last = true)
{ return Syntax::Node::GetAddIndent(last); }
public:
Node(shared_ptr<Syntax::Node> syntax)
: mSyntax(syntax) {}
bool Is(Kind kind)
{ return GetKind() == kind; }
template <typename... Args>
bool Is(Kind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
virtual Kind GetKind()
{ return Unknown; }
shared_ptr<Syntax::Node> GetSyntax()
{ return mSyntax; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
PrintIndent(os, indent, last, label);
PrintName(os);
os.put('\n'); GetSyntax()->Print(os, std::string(indent) + GetAddIndent(last), true, "Syntax = ");
}
public:
enum Kind : unsigned
{
Unknown,
CompilationUnit,
Member,
Function,
Label,
Statement,
NativeCode,
IfStatement,
GotoStatement,
BlockStatement,
ReturnStatement,
ExpressionStatement,
VariableDeclaration,
Expression,
ErrorExpression,
UnaryExpression,
BinaryExpression,
LiteralExpression,
AssignmentExpression,
FieldExpression,
DefaultExpression,
ConstantExpression,
ImplicitCastExpression,
CallExpression,
FunctionPointer,
VariableExpression,
Last = VariableExpression,
};
static constexpr char* KindMap[Last + 1] = {
"Unknown",
"CompilationUnit",
"Member",
"Function",
"Label",
"Statement",
"NativeCode",
"IfStatement",
"GotoStatement",
"BlockStatement",
"ReturnStatement",
"ExpressionStatement",
"VariableDeclaration",
"Expression",
"ErrorExpression",
"UnaryExpression",
"BinaryExpression",
"LiteralExpression",
"AssignmentExpression",
"FieldExpression",
"DefaultExpression",
"ConstantExpression",
"ImplicitCastExpression",
"CallExpression",
"FunctionPointer",
"VariableExpression",
};
};
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/MemberSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/VariableDeclarationSyntax.h"
#include "SympleCode/Syntax/TypeSyntax.h"
namespace Symple::Syntax
{
class FunctionDeclarationSyntax : public MemberSyntax
{
private:
shared_ptr<TypeSyntax> mType;
shared_ptr<Token> mOpenParenthesis;
VariableDeclarationList mParameters;
shared_ptr<Token> mCloseParenthesis;
TokenList mModifiers;
shared_ptr<StatementSyntax> mBody;
public:
FunctionDeclarationSyntax(shared_ptr<TypeSyntax> type, shared_ptr<Token> name,
shared_ptr<Token> openParen, VariableDeclarationList& params, shared_ptr<Token> closeParen,
TokenList& modifiers, shared_ptr<StatementSyntax> body)
: MemberSyntax(name), mType(type), mOpenParenthesis(openParen), mParameters(params), mCloseParenthesis(closeParen), mModifiers(modifiers), mBody(body) {}
virtual Kind GetKind() override
{ return FunctionDeclaration; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os); os << ' ' << GetName()->GetText() << '(';
for (auto param : GetParameters())
{
param->GetType()->PrintShort(os);
if (param != GetParameters().back())
os << ", ";
}
os.put(')');
if (!GetModifiers().empty())
os.put(' ');
for (auto mod : GetModifiers())
{
mod->PrintShort(os);
if (mod != GetModifiers().back())
os << ", ";
}
os.put('\'');
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto param : GetParameters())
{ os.put('\n'); param->Print(os, newIndent, false, "[Param] "); }
os.put('\n'); GetBody()->Print(os, newIndent, true, "Body = ");
}
shared_ptr<TypeSyntax> GetType()
{ return mType; }
shared_ptr<Token> GetName()
{ return GetToken(); }
shared_ptr<Token> GetOpenParenthesis()
{ return mOpenParenthesis; }
VariableDeclarationList GetParameters()
{ return mParameters; }
shared_ptr<Token> GetCloseParenthesis()
{ return mCloseParenthesis; }
TokenList& GetModifiers()
{ return mModifiers; }
shared_ptr<StatementSyntax> GetBody()
{ return mBody; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/UnaryExpressionSyntax.h"
#include "SympleCode/Binding/BoundUnaryOperator.h"
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundUnaryExpression : public BoundExpression
{
private:
shared_ptr<BoundUnaryOperator> mOperator;
shared_ptr<BoundExpression> mOperand;
public:
BoundUnaryExpression(shared_ptr<Syntax::UnaryExpressionSyntax> syntax, shared_ptr<BoundUnaryOperator> oqerator, shared_ptr<BoundExpression> operand)
: BoundExpression(syntax), mOperator(oqerator), mOperand(operand)
{}
virtual Kind GetKind() override
{ return UnaryExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return mOperator->GetType(); }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, false, "Type = ");
os.put('\n'); GetOperator()->Print(os, newIndent, false, "Operator = ");
os.put('\n'); GetOperand()->Print(os, newIndent, true, "Operand = ");
}
shared_ptr<BoundUnaryOperator> GetOperator()
{ return mOperator; }
shared_ptr<BoundExpression> GetOperand()
{ return mOperand; }
};
}<file_sep>#pragma once
#include <string>
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/DiagnosticBag.h"
namespace Symple::Syntax
{
class __SYC_API Lexer
{
private:
std::string mSource;
unsigned mPosition = 0;
shared_ptr<Trivia> mTrivia;
char* mFile;
unsigned mLine = 1, mColumn = 0;
shared_ptr<DiagnosticBag> mDiagnosticBag = make_shared<DiagnosticBag>();
public:
Lexer(char* mFile);
Lexer(char* mFile, std::string& mSource);
shared_ptr<Token> Lex();
shared_ptr<Token> LexAtom(Token::Kind);
shared_ptr<Token> LexIdentifier();
shared_ptr<Token> LexString();
shared_ptr<Token> LexNumber();
static bool IsWhiteSpace(char);
static bool IsIdentifier(char);
static bool IsInteger(char);
static bool IsNumber(char);
bool IsNumber();
std::string_view GetSource();
char* GetFile();
shared_ptr<DiagnosticBag> GetDiagnosticBag();
private:
bool CheckNewLine();
char& Peek(unsigned off = 0);
char& Next();
};
}<file_sep>#include "SympleCode/DiagnosticBag.h"
#include <sstream>
#include <spdlog/fmt/fmt.h>
namespace Symple
{
using namespace Syntax;
void DiagnosticBag::ReportMessage(shared_ptr<Token> tok, std::string_view msg)
{
mDiagnostics.push_back(make_shared<Diagnostic>(Diagnostic::Message, tok, msg));
mMessageCount++;
}
void DiagnosticBag::ReportWarning(shared_ptr<Token> tok, std::string_view msg)
{
mDiagnostics.push_back(make_shared<Diagnostic>(Diagnostic::Warning, tok, msg));
mWarningCount++;
}
void DiagnosticBag::ReportError(shared_ptr<Token> tok, std::string_view msg)
{
mDiagnostics.push_back(make_shared<Diagnostic>(Diagnostic::Error, tok, msg));
mErrorCount++;
}
unsigned DiagnosticBag::GetMessageCount()
{ return mMessageCount; }
unsigned DiagnosticBag::GetWarningCount()
{ return mWarningCount; }
unsigned DiagnosticBag::GetErrorCount()
{ return mErrorCount; }
std::vector<shared_ptr<Diagnostic>>& DiagnosticBag::GetDiagnostics()
{ return mDiagnostics; }
#if __SY_ALLOW_UNIMPLIMENTED
void DiagnosticBag::ReportUnimplimentedMessage(shared_ptr<Syntax::Token> tok)
{ ReportWarning(tok, "message not implemented"); }
void DiagnosticBag::ReportUnimplimentedWarning(shared_ptr<Syntax::Token> tok)
{ ReportWarning(tok, "warning not implemented"); }
void DiagnosticBag::ReportUnimplimentedError(shared_ptr<Syntax::Token> tok)
{ ReportWarning(tok, "error not implemented"); }
#endif
void DiagnosticBag::ReportBindError(shared_ptr<Syntax::Node> syntax)
{ ReportError(syntax->GetToken(), "bind error"); }
void DiagnosticBag::ReportExpressionMustHaveValue(shared_ptr<Syntax::ExpressionSyntax> syntax)
{ ReportError(syntax->GetToken(), "expression must have a value"); }
void DiagnosticBag::ReportNoDefaultArgument(shared_ptr<Syntax::CallExpressionSyntax> syntax, unsigned param)
{ ReportError(syntax->GetCloseParenthesis(), fmt::format("no default argument for parameter {}", param + 1)); }
void DiagnosticBag::ReportTooFewArguments(shared_ptr<Syntax::CallExpressionSyntax> syntax)
{ ReportError(syntax->GetCloseParenthesis(), "too few Arguments"); }
void DiagnosticBag::ReportTooManyArguments(shared_ptr<Syntax::CallExpressionSyntax> syntax, unsigned param)
{ ReportError(syntax->GetArguments()[param]->GetToken(), "too many arguments"); }
void DiagnosticBag::ReportNoSuchFunction(shared_ptr<Syntax::CallExpressionSyntax> syntax)
{ ReportError(syntax->GetToken(), "function Doesn't Exist"); }
void DiagnosticBag::ReportUndeclaredLabel(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "undeclared label"); }
void DiagnosticBag::ReportUnexpectedEndOfFile(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "unexpected end of file"); }
void DiagnosticBag::ReportUnexpectedDllImportBody(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "unexpected dllimport body"); }
void DiagnosticBag::ReportUndeclaredIdentifier(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "undeclared identifier"); }
void DiagnosticBag::ReportUnexpectedToken(shared_ptr<Token> tok, Token::Kind expected)
{
std::stringstream tokStr;
tok->PrintShort(tokStr);
ReportError(tok, fmt::format("unexpected token '{}', expected {}", tokStr.str(), Token::KindMap[expected]));
}
void DiagnosticBag::ReportUnknownToken(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, fmt::format("unknown token '{}'", tok->GetText())); }
void DiagnosticBag::ReportInvalidOperation(shared_ptr<Syntax::Token> tok, shared_ptr<Symbol::TypeSymbol> l, shared_ptr<Symbol::TypeSymbol> r)
{
std::stringstream ss;
tok->PrintShort(ss);
std::string tokstr = ss.str();
ss.str({}); // Clear stream
l->PrintShort(ss);
std::string lstr = ss.str();
ss.str({}); // Clear stream
r->PrintShort(ss);
std::string rstr = ss.str();
ReportError(tok, fmt::format("invalid operation [{}] of types {}, and {}", tokstr, lstr, rstr));
}
void DiagnosticBag::ReportInvalidOperation(shared_ptr<Syntax::Token> tok, shared_ptr<Symbol::TypeSymbol> ty)
{
std::stringstream ss;
tok->PrintShort(ss);
std::string tokstr = ss.str();
ss.str({}); // Clear stream
ty->PrintShort(ss);
std::string tystr = ss.str();
ReportError(tok, fmt::format("invalid operation [{}] of type {}", tokstr, tystr));
}
void DiagnosticBag::ReportExpectedUnqualifiedID(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "expected unqualidied-id"); }
void DiagnosticBag::ReportExpectedLValue(shared_ptr<Syntax::Token> tok)
{ ReportError(tok, "expected lvalue"); }
void DiagnosticBag::ReportInvalidLiteral(shared_ptr<LiteralExpressionSyntax> literal)
{
std::stringstream tokStr;
literal->GetLiteral()->PrintShort(tokStr);
ReportError(literal->GetLiteral(), fmt::format("invalid literal '{}'", tokStr.str()));
}
}<file_sep>#include "SympleCode/Util/FileUtil.h"
#include <spdlog/spdlog.h>
namespace Symple::Util
{
FILE* OpenFile(char* path, char* perms)
{
FILE* fs;
errno_t err = fopen_s(&fs, path, perms);
if (err || !fs)
{
char errMsg[32];
if (strerror_s(errMsg, err))
spdlog::error("Error opening file '{}'", path);
else
spdlog::error("Error opening file '{}': {}", path, errMsg);
return nullptr;
}
else
return fs;
}
FILE* OpenTempFile()
{
FILE* fs;
errno_t err = tmpfile_s(&fs);
if (err || !fs)
{
char errMsg[32];
if (strerror_s(errMsg, err))
spdlog::error("Error opening temp file");
else
spdlog::error("Error opening temp file: {}", errMsg);
return nullptr;
}
else
return fs;
}
int (*CloseFile)(FILE*) = fclose;
void DumpFile(FILE* from, FILE* to)
{
unsigned start = ftell(from);
char c;
while ((c = fgetc(from)) != EOF)
fputc(c, to);
fseek(from, start, SEEK_SET);
}
std::string ReadFile(FILE* fs, unsigned max)
{
if (!fs)
return {};
fseek(fs, 0, SEEK_END);
unsigned allocSz = std::min((unsigned)(ftell(fs) + 1), max);
char* src = new char[allocSz];
src[allocSz - 1] = 0;
rewind(fs);
fread_s(src, allocSz - 1, 1, allocSz - 1, fs);
std::string str(src);
delete[] src;
return str;
}
}<file_sep>#include "SympleCode/Binding/BoundBinaryOperator.h"
#include "SympleCode/Binding/Casting.h"
namespace Symple::Binding
{
// Explicit Declaration instead of using 'make_shared' because this is a private constructor
std::vector<shared_ptr<BoundBinaryOperator>> BoundBinaryOperator::sOperators;
shared_ptr<BoundBinaryOperator> BoundBinaryOperator::ErrorOperator = shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Unknown, Unknown, Symbol::TypeSymbol::ErrorType, Symbol::TypeSymbol::ErrorType, Symbol::TypeSymbol::ErrorType));;
BoundBinaryOperator::BoundBinaryOperator(Syntax::Token::Kind tokenKind, Kind kind, shared_ptr<Symbol::TypeSymbol> leftType, shared_ptr<Symbol::TypeSymbol> rightType, shared_ptr<Symbol::TypeSymbol> type, bool mut)
: mTokenKind(tokenKind), mKind(kind), mLeftType(leftType), mRightType(rightType), mType(type), mMutable(mut)
{}
void BoundBinaryOperator::Print(std::ostream& os, std::string_view indent, bool last, std::string_view label)
{
Syntax::Node::PrintIndent(os, indent, last, label);
os << "BoundBinary" << KindMap[GetKind()] << " (" << Syntax::Token::KindMap[GetTokenKind()] << ')';
}
void BoundBinaryOperator::PrintShort(std::ostream& os)
{ os << '(' << KindMap[GetKind()] << ')'; }
shared_ptr<BoundBinaryOperator> BoundBinaryOperator::Bind(Syntax::Token::Kind tokenKind, shared_ptr<Symbol::TypeSymbol> leftType, shared_ptr<Symbol::TypeSymbol> rightType)
{
if (sOperators.empty())
sOperators = {
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Plus, Addition, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Plus, Addition, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Plus, Addition, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Plus, Addition, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Plus, Addition, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Dash, Subtraction, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Dash, Subtraction, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Dash, Subtraction, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Dash, Subtraction, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Dash, Subtraction, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Asterisk, Multiplication, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Asterisk, Multiplication, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Asterisk, Multiplication, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Asterisk, Multiplication, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Asterisk, Multiplication, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Slash, Division, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Slash, Division, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Slash, Division, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Slash, Division, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Slash, Division, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Percentage, Modulo, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Percentage, Modulo, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Percentage, Modulo, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Percentage, Modulo, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Percentage, Modulo, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::ByteType, Symbol::TypeSymbol::ByteType, Symbol::TypeSymbol::ByteType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::ShortType, Symbol::TypeSymbol::ShortType, Symbol::TypeSymbol::ShortType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, Symbol::TypeSymbol::IntType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, Symbol::TypeSymbol::LongType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, Symbol::TypeSymbol::FloatType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, Symbol::TypeSymbol::DoubleType, true)),
shared_ptr<BoundBinaryOperator>(new BoundBinaryOperator(Syntax::Token::Equal, Assign, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, Symbol::TypeSymbol::TripleType, true)),
};
for (auto op : sOperators)
{
bool exactSame = op->GetLeftType()->Equals(leftType) && op->GetRightType()->Equals(rightType);
bool canCast = CastTable::CanImplicitelyCast(op->GetLeftType(), leftType) && CastTable::CanImplicitelyCast(op->GetRightType(), rightType);
if (op->GetTokenKind() == tokenKind && exactSame)
return op;
}
return ErrorOperator;
}
bool BoundBinaryOperator::IsMutable()
{ return mMutable; }
Syntax::Token::Kind BoundBinaryOperator::GetTokenKind()
{ return mTokenKind; }
BoundBinaryOperator::Kind BoundBinaryOperator::GetKind()
{ return mKind; }
shared_ptr<Symbol::TypeSymbol> BoundBinaryOperator::GetLeftType()
{ return mLeftType; }
shared_ptr<Symbol::TypeSymbol> BoundBinaryOperator::GetRightType()
{ return mRightType; }
shared_ptr<Symbol::TypeSymbol> BoundBinaryOperator::GetType()
{ return mType; }
}<file_sep>#include "SympleCode/Syntax/Trivia.h"
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
__SYC_API shared_ptr<Trivia> Trivia::Error = make_shared<Trivia>();
__SYC_API shared_ptr<Trivia> Trivia::Default = make_shared<Trivia>();
Trivia::Trivia(Kind kind, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(), mLine(ln), mColumn(col), mFile(file)
{}
Trivia::Trivia(Kind kind, std::string_view text, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(text), mLine(ln), mColumn(col), mFile(file)
{}
Trivia::Trivia(Kind kind, char* beg, unsigned len, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(beg, len), mLine(ln), mColumn(col), mFile(file)
{}
Trivia::Trivia(Kind kind, char* beg, char* end, unsigned ln, unsigned col, char* file)
: mKind(kind), mText(beg, std::distance(beg, end)), mLine(ln), mColumn(col), mFile(file)
{}
bool Trivia::Is(Kind kind)
{ return mKind & kind; }
void Trivia::Print(std::ostream& os, std::string_view indent, bool last, std::string_view label)
{
Node::PrintIndent(os, indent, last, label);
for (unsigned k = 0; k < Length; k++)
if (Is(KindArray[k]))
os << '[' << KindMap[KindArray[k]] << "] ";
os << "Trivia '" << GetText() << "' <" << GetLine() << ':' << GetColumn() << ">";
}
void Trivia::PrintShort(std::ostream& os)
{
for (unsigned k = 0; k < Length; k++)
if (Is(KindArray[k]))
os << '[' << KindMap[KindArray[k]] << "] ";
}
Trivia::Kind Trivia::GetKind()
{ return mKind; }
std::string_view Trivia::GetText()
{ return mText; }
char* Trivia::GetFile()
{ return mFile; }
unsigned Trivia::GetLine()
{ return mLine; }
unsigned Trivia::GetColumn()
{ return mColumn; }
}<file_sep>workspace "SympleCode"
architecture "x86"
configurations {
"Debug",
"Release"
}
flags "MultiProcessorCompile"
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
include "SympleLang"
-- include "SympleCompiler"<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/Node.h"
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Binding
{
class BoundUnaryOperator
{
public: enum Kind : unsigned;
private:
Syntax::Token::Kind mTokenKind;
Kind mKind;
shared_ptr<Symbol::TypeSymbol> mOperandType, mType;
BoundUnaryOperator(Syntax::Token::Kind, Kind, shared_ptr<Symbol::TypeSymbol> operandType, shared_ptr<Symbol::TypeSymbol> type);
static std::vector<shared_ptr<BoundUnaryOperator>> sOperators;
public:
void Print(std::ostream& = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "");
void PrintShort(std::ostream& os = std::cout);
static shared_ptr<BoundUnaryOperator> Bind(Syntax::Token::Kind, shared_ptr<Symbol::TypeSymbol> operandType);
static shared_ptr<BoundUnaryOperator> ErrorOperator;
Syntax::Token::Kind GetTokenKind();
Kind GetKind();
shared_ptr<Symbol::TypeSymbol> GetOperandType();
shared_ptr<Symbol::TypeSymbol> GetType();
public:
enum Kind : unsigned
{
Unknown,
Positive,
Negative,
Not,
Last = Not,
};
static constexpr char* KindMap[Last + 1] = {
"Unknown",
"Positive",
"Negative",
"Not",
};
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/CallExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Symbol/FunctionSymbol.h"
namespace Symple::Binding
{
typedef Promise<std::pair<shared_ptr<Symbol::FunctionSymbol>, ExpressionList>, shared_ptr<Syntax::CallExpressionSyntax>> FunctionPromise;
class BoundCallExpression : public BoundExpression
{
private:
shared_ptr<FunctionPromise> mFunction;
public:
BoundCallExpression(shared_ptr<Syntax::CallExpressionSyntax> syntax, shared_ptr<FunctionPromise> func)
: BoundExpression(syntax), mFunction(func) {}
virtual Kind GetKind() override
{ return CallExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return GetFunction() ? GetFunction()->GetType() : Symbol::TypeSymbol::IntType; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
//os << " '" << GetSyntax()->GetToken()->GetText(); os << '(' << (GetArguments().size()) << ")'";
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto arg : GetArguments())
{ os.put('\n'); arg->Print(os, newIndent, arg == GetArguments().back()); }
}
shared_ptr<Symbol::FunctionSymbol> GetFunction()
{ return mFunction->GetObject().first; }
ExpressionList GetArguments()
{ return mFunction->GetObject().second; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Binding/Node.h"
namespace Symple::Binding
{
class BoundStatement : public Node
{
public:
BoundStatement(shared_ptr<Syntax::StatementSyntax> syntax)
: Node(syntax) {}
virtual Kind GetKind()
{ return Statement; }
};
}<file_sep>#pragma once
#include <string_view>
#include "SympleCode/DiagnosticBag.h"
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/Syntax/TranslationUnitSyntax.h"
#include "SympleCode/Binding/Binder.h"
#include "SympleCode/Binding/BoundCompilationUnit.h"
#include "SympleCode/Emit/AsmEmitter.h"
namespace Symple
{
class __SYC_API Compiler
{
private:
std::string mPath, mAsmPath;
Syntax::TokenList mTokens;
shared_ptr<Syntax::TranslationUnitSyntax> mAST;
shared_ptr<Binding::BoundCompilationUnit> mTree;
unique_ptr<Emit::AsmEmitter> mEmitter;
bool mAnyErrors = false;
static std::vector<std::string> sLibraries;
static std::vector<std::string> sUnits;
friend class Binding::Binder;
public:
Compiler(char *path);
shared_ptr<DiagnosticBag> Lex();
shared_ptr<DiagnosticBag> Parse();
shared_ptr<DiagnosticBag> Bind();
shared_ptr<Binding::BoundCompilationUnit> BindSymbols();
void Emit();
void Compile();
// Returns true if links successfully
bool Link(std::string_view output = "sy/bin/Main.exe", bool isLibrary = false);
int Exec(std::string_view args = "");
/// <summary>
/// Print Diagnostics
/// </summary>
/// <param name="diagnostics">Diagnostic Bag</param>
/// <param name="step">Step in witch diagnostics are for</param>
/// <returns>Returns true if there is an error</returns>
bool PrintDiagnosticBag(shared_ptr<DiagnosticBag> diagnostics, char *step = "Null Step");
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
#include "SympleCode/Syntax/MemberSyntax.h"
namespace Symple::Syntax
{
class TranslationUnitSyntax : public Node
{
private:
std::vector<shared_ptr<MemberSyntax>> mMembers;
public:
TranslationUnitSyntax(std::vector<shared_ptr<MemberSyntax>>& members, shared_ptr<Token> eof)
: Node(eof), mMembers(members) {}
virtual Kind GetKind() override
{ return TranslationUnit; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto member : GetMembers())
{ os.put('\n'); member->Print(os, newIndent, member == GetMembers().back()); }
}
std::vector<shared_ptr<MemberSyntax>> GetMembers()
{ return mMembers; }
};
}<file_sep>#pragma once
namespace Symple::Util
{
enum ConsoleColor
{
Black,
DarkBlue,
DarkGreen,
DarkCyan,
DarkRed,
DarkMagenta,
DarkYellow,
Grey,
DarkGrey,
Blue,
Green,
Cyan,
Red,
Magenta,
Yellow,
White,
Reset = White,
};
void SetConsoleColor(ConsoleColor c);
ConsoleColor GetConsoleColor();
void ResetConsoleColor();
}<file_sep>#pragma once
#include "SympleCode/Syntax/IfStatementSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundIfStatement : public BoundStatement
{
private:
shared_ptr<BoundExpression> mCondition;
shared_ptr<BoundStatement> mThen;
shared_ptr<BoundStatement> mElse;
public:
BoundIfStatement(shared_ptr<Syntax::IfStatementSyntax> syntax, shared_ptr<BoundExpression> cond, shared_ptr<BoundStatement> then, shared_ptr<BoundStatement> elze)
: BoundStatement(syntax), mCondition(cond), mThen(then), mElse(elze) {}
virtual Kind GetKind() override
{ return IfStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetCondition()->Print(os, newIndent, false, "Condition = ");
os.put('\n'); GetThen()->Print(os, newIndent, false, "Then = ");
os.put('\n'); GetElse()->Print(os, newIndent, true, "Else = ");
}
shared_ptr<BoundExpression> GetCondition()
{ return mCondition; }
shared_ptr<BoundStatement> GetThen()
{ return mThen; }
shared_ptr<BoundStatement> GetElse()
{ return mElse; }
};
}<file_sep>#pragma once
#include "SympleCode/Memory.h"
namespace Symple
{
template<typename T, typename P>
class Promise
{
private:
P mPrompt;
T mObject;
bool mBroken = true;
public:
Promise(P& prompt)
: mPrompt(prompt) {}
P& GetPrompt()
{ return mPrompt; }
T& GetObject()
{ return mObject; }
void Complete(T& obj)
{
mObject = obj;
mBroken = false;
}
bool IsBroken()
{ return mBroken; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Trivia.h"
namespace Symple::Syntax
{
class __SYC_API Token
{
public: enum Kind : unsigned;
private:
Kind mKind;
std::string mText;
shared_ptr<Trivia> mTrivia;
char* mFile;
unsigned mLine, mColumn;
public:
Token(Kind = Unknown, shared_ptr<Trivia> = Trivia::Default, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Token(Kind, std::string_view text, shared_ptr<Trivia> = Trivia::Default, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Token(Kind, char* beg, unsigned len = 1, shared_ptr<Trivia> = Trivia::Default, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
Token(Kind, char* beg, char* end, shared_ptr<Trivia> = Trivia::Default, unsigned ln = 0, unsigned col = 0, char* file = "<NA>");
bool IsKeyword();
bool Is(Kind kind);
template <typename... Args>
bool Is(Kind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
void Print(std::ostream& = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "");
void PrintShort(std::ostream& = std::cout);
Kind GetKind();
std::string_view GetText();
shared_ptr<Trivia> GetTrivia();
char* GetFile();
unsigned GetLine();
unsigned GetColumn();
static shared_ptr<Token> Error;
static shared_ptr<Token> Default;
public:
enum Kind : unsigned
{
EndOfFile,
Unknown,
Identifier,
String,
Integer,
Number,
Float,
Comma,
Colon,
Period,
Semicolon,
Plus,
Dash,
Asterisk,
Slash,
Percentage,
Exclamation,
Equal,
EqualArrow,
OpenParenthesis,
CloseParenthesis,
OpenBrace,
CloseBrace,
FirstKeyword,
VoidKeyword = FirstKeyword,
ByteKeyword,
ShortKeyword,
IntKeyword,
LongKeyword,
BoolKeyword,
CharKeyword,
WCharKeyword,
FloatKeyword,
DoubleKeyword,
TripleKeyword,
ReturnKeyword,
DefaultKeyword,
ExternKeyword,
ImportKeyword,
CDeclKeyword,
StdCallKeyword,
DllImportKeyword,
DllExportKeyword,
StaticKeyword,
LocalKeyword,
GlobalKeyword,
NativeKeyword,
GotoKeyword,
IfKeyword,
ElseKeyword,
StructKeyword,
Last = StructKeyword,
};
static constexpr char* KindMap[Last + 1] = {
"EndOfFile",
"Unknown",
"Identifier",
"String",
"Integer",
"Number",
"Float",
"Comma",
"Colon",
"Period",
"Semicolon",
"Plus",
"Dash",
"Asterisk",
"Slash",
"Percentage",
"Exclamation",
"Equal",
"EqualArrow",
"OpenParenthesis",
"CloseParenthesis",
"OpenBrace",
"CloseBrace",
"VoidKeyword",
"ByteKeyword",
"ShortKeyword",
"IntKeyword",
"LongKeyword",
"BoolKeyword",
"CharKeyword",
"WCharKeyword",
"FloatKeyword",
"DoubleKeyword",
"TripleKeyword",
"ReturnKeyword",
"DefaultKeyword",
"ExternKeyword",
"ImportKeyword",
"CDeclKeyword",
"StdCallKeyword",
"DllImportKeyword",
"DllExportKeyword",
"StaticKeyword",
"LocalKeyword",
"GlobalKeyword",
"NativeKeyword",
"GotoKeyword",
"IfKeyword",
"ElseKeyword",
"StructKeyword",
};
};
typedef std::vector<shared_ptr<Token>> TokenList;
}<file_sep>#pragma once
#include "SympleCode/Syntax/MemberSyntax.h"
namespace Symple::Syntax
{
class ImportStatementSyntax : public MemberSyntax
{
private:
shared_ptr<Token> mKeyword;
public:
ImportStatementSyntax(shared_ptr<Token> key, shared_ptr<Token> import)
: MemberSyntax(import), mKeyword(key) {}
virtual Kind GetKind() override
{ return ImportStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetImport()->Print(os, newIndent, true, "Import = ");
}
shared_ptr<Token> GetKeyword()
{ return mKeyword; }
shared_ptr<Token> GetImport()
{ return GetToken(); }
};
}<file_sep>#pragma once
#include <unordered_map>
#include "SympleCode/DiagnosticBag.h"
#include "SympleCode/Syntax/TypeSyntax.h"
#include "SympleCode/Syntax/ImportStatementSyntax.h"
#include "SympleCode/Syntax/ExternFunctionSyntax.h"
#include "SympleCode/Syntax/GlobalStatementSyntax.h"
#include "SympleCode/Syntax/StructDeclarationSyntax.h"
#include "SympleCode/Syntax/FunctionDeclarationSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/BlockStatementSyntax.h"
#include "SympleCode/Syntax/ExpressionSyntax.h"
#include "SympleCode/Symbol/Symbol.h"
#include "SympleCode/Symbol/FunctionSymbol.h"
#include "SympleCode/Symbol/StructTypeSymbol.h"
#include "SympleCode/Binding/Node.h"
#include "SympleCode/Binding/BoundScope.h"
#include "SympleCode/Binding/BoundCompilationUnit.h"
#include "SympleCode/Binding/BoundLabel.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Binding/BoundNativeCode.h"
#include "SympleCode/Binding/BoundIfStatement.h"
#include "SympleCode/Binding/BoundGotoStatement.h"
#include "SympleCode/Binding/BoundBlockStatement.h"
#include "SympleCode/Binding/BoundReturnStatement.h"
#include "SympleCode/Binding/BoundExpressionStatement.h"
#include "SympleCode/Binding/BoundVariableDeclaration.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Binding/BoundFieldExpression.h"
#include "SympleCode/Binding/BoundCallExpression.h"
#include "SympleCode/Binding/BoundErrorExpression.h"
#include "SympleCode/Binding/BoundUnaryExpression.h"
#include "SympleCode/Binding/BoundBinaryExpression.h"
#include "SympleCode/Binding/BoundLiteralExpression.h"
#include "SympleCode/Binding/BoundVariableExpression.h"
namespace Symple::Binding
{
class Binder
{
private:
static std::unordered_map<std::string, shared_ptr<BoundCompilationUnit>> sImportedSymbols;
shared_ptr<Syntax::TranslationUnitSyntax> mCompilationUnit;
StructMap mStructures;
FunctionMap mFunctions;
Symbol::LabelList mLabels;
std::vector<shared_ptr<GotoPromise>> mGotoPromises;
std::vector<shared_ptr<MemberPromise>> mMemPromises;
std::vector<shared_ptr<FunctionPromise>> mFuncPromises;
shared_ptr<BoundScope> mScope;
shared_ptr<DiagnosticBag> mDiagnosticBag = make_shared<DiagnosticBag>();
void BeginScope();
void EndScope();
void CheckGotoPromises();
void CheckMemberPromises();
void CheckFunctionPromises();
shared_ptr<Node> BindMemberInternal(shared_ptr<Syntax::MemberSyntax>);
shared_ptr<BoundStatement> BindStatementInternal(shared_ptr<Syntax::StatementSyntax>);
shared_ptr<BoundExpression> BindExpressionInternal(shared_ptr<Syntax::ExpressionSyntax>);
public:
shared_ptr<BoundCompilationUnit> BindImport(shared_ptr<Syntax::ImportStatementSyntax>);
shared_ptr<BoundCompilationUnit> BindSymbols(shared_ptr<Syntax::TranslationUnitSyntax>);
shared_ptr<BoundCompilationUnit> Bind(shared_ptr<Syntax::TranslationUnitSyntax>);
shared_ptr<Symbol::Symbol> BindMemberSymbol(shared_ptr<Syntax::MemberSyntax>);
shared_ptr<Node> BindMember(shared_ptr<Syntax::MemberSyntax>);
shared_ptr<Symbol::TypeSymbol> BindType(shared_ptr<Syntax::TypeSyntax>);
shared_ptr<Symbol::LabelSymbol> BindLabelSymbol(shared_ptr<Syntax::LabelSyntax>);
shared_ptr<Symbol::MemberSymbol> BindMember(shared_ptr<Syntax::VariableDeclarationSyntax>);
shared_ptr<Symbol::FunctionSymbol> BindFunction(shared_ptr<Syntax::FunctionDeclarationSyntax>);
shared_ptr<Symbol::FunctionSymbol> BindExternFunction(shared_ptr<Syntax::ExternFunctionSyntax>);
shared_ptr<Symbol::ParameterSymbol> BindParameter(shared_ptr<Syntax::VariableDeclarationSyntax>);
shared_ptr<Symbol::StructTypeSymbol> BindStructType(shared_ptr<Syntax::StructDeclarationSyntax>);
shared_ptr<BoundStatement> BindStatement(shared_ptr<Syntax::StatementSyntax>);
shared_ptr<BoundLabel> BindLabel(shared_ptr<Syntax::LabelSyntax>);
shared_ptr<BoundNativeCode> BindNativeCode(shared_ptr<Syntax::NativeStatementSyntax>);
shared_ptr<BoundIfStatement> BindIfStatement(shared_ptr<Syntax::IfStatementSyntax>);
shared_ptr<BoundStatement> BindGlobalStatement(shared_ptr<Syntax::GlobalStatementSyntax>);
shared_ptr<BoundGotoStatement> BindGotoStatement(shared_ptr<Syntax::GotoStatementSyntax>);
shared_ptr<BoundBlockStatement> BindBlockStatement(shared_ptr<Syntax::BlockStatementSyntax>);
shared_ptr<BoundReturnStatement> BindReturnStatement(shared_ptr<Syntax::ReturnStatementSyntax>);
shared_ptr<BoundExpressionStatement> BindExpressionStatement(shared_ptr<Syntax::ExpressionStatementSyntax>);
shared_ptr<BoundVariableDeclaration> BindVariableDeclaration(shared_ptr<Syntax::VariableDeclarationSyntax>);
shared_ptr<BoundExpression> BindExpression(shared_ptr<Syntax::ExpressionSyntax>);
shared_ptr<BoundExpression> BindCallExpression(shared_ptr<Syntax::CallExpressionSyntax>);
shared_ptr<BoundUnaryExpression> BindUnaryExpression(shared_ptr<Syntax::UnaryExpressionSyntax>);
shared_ptr<BoundExpression> BindBinaryExpression(shared_ptr<Syntax::BinaryExpressionSyntax>);
shared_ptr<BoundExpression> BindLiteralExpression(shared_ptr<Syntax::LiteralExpressionSyntax>);
shared_ptr<BoundExpression> BindNameExpression(shared_ptr<Syntax::NameExpressionSyntax>);
shared_ptr<DiagnosticBag> GetDiagnosticBag();
};
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/ExpressionSyntax.h"
#include "SympleCode/Syntax/TypeSyntax.h"
namespace Symple::Syntax
{
class VariableDeclarationSyntax : public StatementSyntax
{
private:
shared_ptr<TypeSyntax> mType;
shared_ptr<Token> mEquals;
shared_ptr<ExpressionSyntax> mInitializer;
public:
VariableDeclarationSyntax(shared_ptr<TypeSyntax> type, shared_ptr<Token> name, shared_ptr<Token> equals, shared_ptr<ExpressionSyntax> initializer)
: StatementSyntax(name), mType(type), mEquals(equals), mInitializer(initializer) {}
virtual Kind GetKind() override
{ return VariableDeclaration; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os);
if (GetName() != Token::Default)
os << ' ' << GetName()->GetText();
os.put('\'');
if (GetInitializer())
{
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetInitializer()->Print(os, newIndent, true, "Initializer = ");
}
}
virtual void PrintShort(std::ostream& os = std::cout) override
{
GetType()->PrintShort();
if (GetName() != Token::Default)
os << ' ' << GetName()->GetText();
}
shared_ptr<Token> GetName()
{ return GetToken(); }
shared_ptr<TypeSyntax> GetType()
{ return mType; }
shared_ptr<Token> GetEquals()
{ return mEquals; }
shared_ptr<ExpressionSyntax> GetInitializer()
{ return mInitializer; }
};
typedef std::vector<shared_ptr<VariableDeclarationSyntax>> VariableDeclarationList;
}<file_sep>#include "SympleCode/Syntax/Facts.h"
namespace Symple::Syntax
{
unsigned Facts::GetUnaryOperatorPrecedence(Token::Kind kind)
{
switch (kind)
{
case Token::Exclamation:
case Token::Plus:
case Token::Dash:
return 2;
default:
return 0;
}
}
unsigned Facts::GetBinaryOperatorPrecedence(Token::Kind kind)
{
switch (kind)
{
case Token::Period:
return 1;
case Token::Percentage:
case Token::Asterisk:
case Token::Slash:
return 3;
case Token::Plus:
case Token::Dash:
return 4;
case Token::Equal:
return 14;
default:
return 0;
}
}
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
class ExpressionSyntax : public Node
{
public:
ExpressionSyntax(shared_ptr<Token> tok)
: Node(tok) {}
virtual Kind GetKind() override
{ return Expression; }
};
typedef std::vector<shared_ptr<ExpressionSyntax>> ExpressionList;
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
#include "SympleCode/Binding/Node.h"
#include "SympleCode/Binding/BoundConstant.h"
#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Binding
{
class BoundExpression : public Node
{
public:
BoundExpression(shared_ptr<Syntax::ExpressionSyntax> syntax)
: Node(syntax) {}
virtual Kind GetKind()
{ return Expression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType()
{ return Symbol::TypeSymbol::ErrorType; }
virtual bool IsMutable()
{ return false; }
virtual shared_ptr<BoundConstant> ConstantValue()
{ return nullptr; }
virtual void Print(std::ostream & os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, true, "Type = ");
}
};
typedef std::vector<shared_ptr<BoundExpression>> ExpressionList;
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class NameExpressionSyntax : public ExpressionSyntax
{
public:
NameExpressionSyntax(shared_ptr<Token> tok)
: ExpressionSyntax(tok) {}
virtual Kind GetKind() override
{ return NameExpression; }
};
}<file_sep>#include <iostream>
#include <vector>
#include <cstdlib>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include "SympleCode/Compiler.h"
#include "SympleCode/Util/FileUtil.h"
#include "SympleCode/Util/ConsoleColor.h"
using namespace Symple::Util;
using std::shared_ptr;
using std::make_shared;
using std::unique_ptr;
using std::make_unique;
using spdlog::level::level_enum;
static void SetupLogging()
{
spdlog::sinks_init_list sinks = {
#if __SY_RELEASE
make_shared<spdlog::sinks::stdout_color_sink_mt>(),
#endif
make_shared<spdlog::sinks::basic_file_sink_mt>("stdout.log", true)
};
spdlog::set_default_logger(make_shared<spdlog::logger>("Symple Logger", sinks));
spdlog::set_pattern("[Symple]%^<%l>%$: %v");
spdlog::flush_on(level_enum::info);
#if __SY_DEBUG
spdlog::set_level(level_enum::trace);
#else
spdlog::set_level(level_enum::info);
#endif
SetConsoleColor(Yellow);
}
int main()
{
SetupLogging();
unique_ptr<Symple::Compiler> compiler = make_unique<Symple::Compiler>((char*)"sy/Main.sy");
compiler->Lex();
compiler->Parse();
compiler->Bind();
compiler->Emit();
compiler->Compile();
constexpr bool isLib = false;
if (compiler->Link(isLib ? "sy/bin/Main.dll" : "sy/bin/Main.exe", isLib) && !isLib)
compiler->Exec("\"Argument Test!\"");
return !getc(stdin);
}<file_sep>#pragma once
#include "SympleCode/Syntax/NativeStatementSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
namespace Symple::Binding
{
class BoundNativeCode : public BoundStatement
{
public:
BoundNativeCode(shared_ptr<Syntax::NativeStatementSyntax> syntax)
: BoundStatement(syntax)
{}
virtual Kind GetKind() override
{ return NativeCode; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << '\'' << GetAssembly() << '\'';
}
std::string_view GetAssembly()
{ return dynamic_pointer_cast<Syntax::NativeStatementSyntax>(GetSyntax())->GetAssembly()->GetText(); }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/VariableSymbol.h"
#include "SympleCode/Binding/BoundConstant.h"
namespace Symple::Symbol
{
class MemberSymbol: public VariableSymbol
{
private:
shared_ptr<Binding::BoundConstant> mInitializer;
public:
MemberSymbol(shared_ptr<TypeSymbol> ty, std::string_view name, shared_ptr<Binding::BoundConstant> init)
: VariableSymbol(ty, name), mInitializer(init)
{}
virtual Kind GetKind() override
{ return Member; }
virtual void Print(std::ostream &os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os); os << ' ' << GetName();
if (GetInitializer())
{
os << " = ";
GetInitializer()->PrintShort(os);
}
os.put('\'');
}
void PrintShort(std::ostream &os = std::cout)
{
GetType()->PrintShort(os); os << ' ' << GetName();
if (GetInitializer())
{
os << " = ";
GetInitializer()->PrintShort(os);
}
}
shared_ptr<Binding::BoundConstant> GetInitializer()
{ return mInitializer; }
};
typedef std::vector<shared_ptr<MemberSymbol>> MemberList;
}<file_sep>#pragma once
#include "SympleCode/Syntax/BinaryExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Binding/BoundBinaryOperator.h"
namespace Symple::Binding
{
class BoundBinaryExpression : public BoundExpression
{
private:
shared_ptr<BoundBinaryOperator> mOperator;
shared_ptr<BoundExpression> mLeft, mRight;
public:
BoundBinaryExpression(shared_ptr<Syntax::BinaryExpressionSyntax> syntax, shared_ptr<BoundBinaryOperator> oqerator, shared_ptr<BoundExpression> left, shared_ptr<BoundExpression> right)
: BoundExpression(syntax), mOperator(oqerator), mLeft(left), mRight(right)
{}
virtual Kind GetKind() override
{ return BinaryExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return mOperator->GetType(); }
virtual bool IsMutable() override
{ return GetOperator()->GetKind() == BoundBinaryOperator::Assign; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, false, "Type = ");
os.put('\n'); GetOperator()->Print(os, newIndent, false, "Operator = ");
os.put('\n'); GetLeft()->Print(os, newIndent, false, "Left = ");
os.put('\n'); GetRight()->Print(os, newIndent, true, "Right = ");
}
shared_ptr<BoundBinaryOperator> GetOperator()
{ return mOperator; }
shared_ptr<BoundExpression> GetLeft()
{ return mLeft; }
shared_ptr<BoundExpression> GetRight()
{ return mRight; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Token.h"
namespace Symple::Syntax
{
struct Facts
{
static unsigned GetUnaryOperatorPrecedence(Token::Kind);
static unsigned GetBinaryOperatorPrecedence(Token::Kind);
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
class StatementSyntax : public Node
{
public:
StatementSyntax(shared_ptr<Token> tok)
: Node(tok) {}
virtual Kind GetKind() override
{ return Statement; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class UnaryExpressionSyntax : public ExpressionSyntax
{
private:
shared_ptr<ExpressionSyntax> mOperand;
public:
UnaryExpressionSyntax(shared_ptr<Token> op, shared_ptr<ExpressionSyntax> operand)
: ExpressionSyntax(op), mOperand(operand) {}
virtual Kind GetKind()
{ return UnaryExpression; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " [";
GetOperator()->PrintShort(os);
os.put(']');
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetOperand()->Print(os, newIndent, true, "Operand = ");
}
shared_ptr<Token> GetOperator()
{ return GetToken(); }
shared_ptr<ExpressionSyntax> GetOperand()
{ return mOperand; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/BinaryExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Symbol/Promise.h"
#include "SympleCode/Symbol/MemberSymbol.h"
namespace Symple::Binding
{
typedef Promise<shared_ptr<Symbol::MemberSymbol>, std::pair<shared_ptr<BoundExpression>, shared_ptr<Syntax::BinaryExpressionSyntax>>> MemberPromise;
class BoundFieldExpression: public BoundExpression
{
private:
shared_ptr<MemberPromise> mMember;
public:
BoundFieldExpression(shared_ptr<Syntax::BinaryExpressionSyntax> syntax, shared_ptr<MemberPromise> member)
: BoundExpression(syntax), mMember(member) {}
virtual Kind GetKind() override
{ return FieldExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return GetMember() ? GetMember()->GetType() : Symbol::TypeSymbol::VoidType; }
virtual bool IsMutable() override
{ return true; }
virtual void Print(std::ostream &os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os << '\n'; GetOperand()->Print(os, newIndent, false, "Operand = ");
if (GetMember())
{ os << '\n'; GetMember()->Print(os, newIndent, true, "Member = "); }
}
shared_ptr<BoundExpression> GetOperand()
{ return mMember->GetPrompt().first; }
shared_ptr<Symbol::MemberSymbol> GetMember()
{ return mMember->GetObject(); }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Symbol
{
class Symbol
{
public: enum Kind : unsigned;
protected:
void PrintName(std::ostream& os = std::cout)
{ os << KindMap[GetKind()] << "Symbol"; }
public:
static void PrintIndent(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{ return Syntax::Node::PrintIndent(os, indent, last, label); }
static char* GetAddIndent(bool last = true)
{ return Syntax::Node::GetAddIndent(last); }
public:
bool Is(Kind kind)
{ return GetKind() == kind; }
template <typename... Args>
bool Is(Kind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
virtual Kind GetKind()
{ return Unknown; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "")
{
PrintIndent(os, indent, last, label);
PrintName(os);
}
public:
enum Kind : unsigned
{
Unknown,
Type,
StructType,
Member,
Label,
Function,
Variable,
Parameter,
Last = Parameter,
};
static constexpr char* KindMap[Last + 1] = {
"Unknown",
"Type",
"StructType",
"Member",
"Label",
"Function",
"Variable",
"Parameter",
};
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class ReturnStatementSyntax : public StatementSyntax
{
private:
shared_ptr<ExpressionSyntax> mValue;
public:
ReturnStatementSyntax(shared_ptr<Token> tok, shared_ptr<ExpressionSyntax> val)
: StatementSyntax(tok), mValue(val) {}
virtual Kind GetKind() override
{ return ReturnStatement; }
virtual void Print(std::ostream & os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
if (GetValue())
{
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetValue()->Print(os, newIndent, true, "Value = ");
}
}
shared_ptr<ExpressionSyntax> GetValue()
{ return mValue; }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/VariableSymbol.h"
#include "SympleCode/Binding/BoundConstant.h"
namespace Symple::Symbol
{
class ParameterSymbol : public VariableSymbol
{
private:
shared_ptr<Binding::BoundConstant> mInitializer;
public:
ParameterSymbol(shared_ptr<TypeSymbol> ty, std::string_view name, shared_ptr<Binding::BoundConstant> init)
: VariableSymbol(ty, name), mInitializer(init)
{}
virtual Kind GetKind() override
{ return Parameter; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " '"; GetType()->PrintShort(os); os << ' ' << GetName();
if (GetInitializer())
{
os << " = ";
GetInitializer()->PrintShort(os);
}
os.put('\'');
}
void PrintShort(std::ostream& os = std::cout)
{
GetType()->PrintShort(os); os << ' ' << GetName();
if (GetInitializer())
{
os << " = ";
GetInitializer()->PrintShort(os);
}
}
shared_ptr<Binding::BoundConstant> GetInitializer()
{ return mInitializer; }
};
typedef std::vector<shared_ptr<ParameterSymbol>> ParameterList;
}<file_sep>#include "SympleCode/Util/ConsoleColor.h"
#if _WIN32
#include <Windows.h>
#endif
namespace Symple::Util
{
static ConsoleColor sConsoleColor;
void SetConsoleColor(ConsoleColor c)
{
if (sConsoleColor == c)
return;
sConsoleColor = c;
#if _WIN32
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), sConsoleColor);
#endif
}
ConsoleColor GetConsoleColor()
{ return sConsoleColor; }
void ResetConsoleColor()
{ SetConsoleColor(ConsoleColor::Reset); }
}<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/StatementSyntax.h"
namespace Symple::Syntax
{
class BlockStatementSyntax : public StatementSyntax
{
private:
std::vector<shared_ptr<StatementSyntax>> mStatements;
shared_ptr<Token> mClose;
public:
BlockStatementSyntax(shared_ptr<Token> open, std::vector<shared_ptr<StatementSyntax>> statements, shared_ptr<Token> close)
: StatementSyntax(open), mStatements(statements), mClose(close) {}
virtual Kind GetKind() override
{ return BlockStatement; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
for (auto statement : GetStatements())
{ os.put('\n'); statement->Print(os, newIndent, statement == GetStatements().back()); }
}
shared_ptr<Token> GetOpen()
{ return GetToken(); }
std::vector<shared_ptr<StatementSyntax>> GetStatements()
{ return mStatements; }
shared_ptr<Token> GetClose()
{ return mClose; }
};
}<file_sep>#pragma once
#include "SympleCode/Symbol/TypeSymbol.h"
namespace Symple::Binding
{
struct CastTable
{
static bool CanImplicitelyCast(shared_ptr<Symbol::TypeSymbol> from, shared_ptr<Symbol::TypeSymbol> to);
static bool CanExplicitelyCast(shared_ptr<Symbol::TypeSymbol> from, shared_ptr<Symbol::TypeSymbol> to);
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/VariableDeclarationSyntax.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Binding/BoundExpression.h"
#include "SympleCode/Symbol/VariableSymbol.h"
namespace Symple::Binding
{
class BoundVariableDeclaration : public BoundStatement
{
private:
shared_ptr<Symbol::VariableSymbol> mSymbol;
shared_ptr<BoundExpression> mInitializer;
public:
BoundVariableDeclaration(shared_ptr<Syntax::VariableDeclarationSyntax> syntax, shared_ptr<Symbol::VariableSymbol> symbol, shared_ptr<BoundExpression> init)
: BoundStatement(syntax), mSymbol(symbol), mInitializer(init) {}
virtual Kind GetKind() override
{ return VariableDeclaration; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetSymbol()->Print(os, newIndent, !GetInitializer(), "Symbol = ");
if (GetInitializer())
{ os.put('\n'); GetInitializer()->Print(os, newIndent, true, "Initializer = "); }
}
shared_ptr<Symbol::VariableSymbol> GetSymbol()
{ return mSymbol; }
shared_ptr<BoundExpression> GetInitializer()
{ return mInitializer; }
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/LiteralExpressionSyntax.h"
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundLiteralExpression : public BoundExpression
{
private:
shared_ptr<Symbol::TypeSymbol> mType;
shared_ptr<BoundConstant> mValue;
public:
BoundLiteralExpression(shared_ptr<Syntax::LiteralExpressionSyntax> syntax, shared_ptr<Symbol::TypeSymbol> ty, shared_ptr<BoundConstant> val)
: BoundExpression(syntax), mType(ty), mValue(val)
{}
virtual Kind GetKind() override
{ return LiteralExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return mType; }
virtual shared_ptr<BoundConstant> ConstantValue() override
{ return mValue; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
GetLiteral()->Print(os, indent, last, std::string(label)); os << " (BoundLiteralExpression)";
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetType()->Print(os, newIndent, true, "Type = ");
}
shared_ptr<Syntax::Token> GetLiteral()
{ return GetSyntax()->GetToken(); }
};
}<file_sep>#pragma once
#include "SympleCode/Binding/BoundExpression.h"
namespace Symple::Binding
{
class BoundErrorExpression : public BoundExpression
{
public:
BoundErrorExpression(shared_ptr<Syntax::ExpressionSyntax> syntax)
: BoundExpression(syntax) {}
virtual Kind GetKind() override
{ return ErrorExpression; }
virtual shared_ptr<Symbol::TypeSymbol> GetType() override
{ return Symbol::TypeSymbol::ErrorType; }
};
}<file_sep>#include "SympleCode/Syntax/Lexer.h"
#include "SympleCode/Util/FileUtil.h"
#define Current &Peek()
namespace Symple::Syntax
{
Lexer::Lexer(char* file)
: mFile(file)
{
FILE* fs = Util::OpenFile(file, "rb");
if (fs)
{
mSource = Util::ReadFile(fs);
Util::CloseFile(fs);
}
}
Lexer::Lexer(char* file, std::string& source)
: mFile(file), mSource(source)
{}
#define ATOM(char, ty) \
case char: \
return LexAtom(Token::##ty)
#define PUNC(str, ty) \
else if (!strncmp(Current, str, strlen(str))) \
{ \
char *beg = Current; \
for (unsigned i = 0; i < strlen(str); i++) \
Next(); \
return make_shared<Token>(Token::##ty, beg, &Next(), mTrivia, mLine, mColumn, mFile); \
}
shared_ptr<Token> Lexer::Lex()
{
unsigned trKind = mPosition ? Trivia::Unknown : Trivia::StartOfLine;
unsigned trPosition = mPosition;
unsigned trLn = mLine;
unsigned trCl = mColumn;
bool checkNewLine;
while ((checkNewLine = CheckNewLine()) || IsWhiteSpace(Peek()))
{
if (checkNewLine)
trKind |= Trivia::StartOfLine;
else
trKind |= Trivia::LeadingSpace;
Next();
}
mTrivia = make_shared<Trivia>(trKind, &mSource[trPosition], Current, trLn, trCl, mFile);
char c = Peek();
if (!c)
return LexAtom(Token::EndOfFile);
if (IsNumber())
return LexNumber();
else if (IsIdentifier(c))
return LexIdentifier();
PUNC("=>", EqualArrow)
else
switch (c)
{
ATOM(',', Comma);
ATOM(':', Colon);
ATOM('.', Period);
ATOM(';', Semicolon);
ATOM('+', Plus);
ATOM('-', Dash);
ATOM('!', Exclamation);
ATOM('*', Asterisk);
ATOM('/', Slash);
ATOM('%', Percentage);
ATOM('=', Equal);
ATOM('(', OpenParenthesis);
ATOM(')', CloseParenthesis);
ATOM('{', OpenBrace);
ATOM('}', CloseBrace);
case '"':
return LexString();
default:
auto tok = LexAtom(Token::Unknown);
mDiagnosticBag->ReportUnknownToken(tok);
return tok;
}
}
std::string_view Lexer::GetSource()
{ return mSource; }
char* Lexer::GetFile()
{ return mFile; }
shared_ptr<DiagnosticBag> Lexer::GetDiagnosticBag()
{ return mDiagnosticBag; }
bool Lexer::IsWhiteSpace(char c)
{ return c == ' ' || c == '\t' || c == '\r' || c == 0xCC; }
bool Lexer::IsIdentifier(char c)
{ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || (c >= '0' && c <= '9'); }
bool Lexer::IsInteger(char c)
{ return c >= '0' && c <= '9'; }
bool Lexer::IsNumber(char c)
{ return IsInteger(c) || c == '.'; }
bool Lexer::IsNumber()
{
if (IsInteger(Peek()))
return true;
else if (Peek() == '.' && IsInteger(Peek(1)))
return true;
else
return false;
}
bool Lexer::CheckNewLine()
{
if (Peek() == '\n')
{
mLine++;
mColumn = 0;
return true;
}
else
return false;
}
char& Lexer::Peek(unsigned off)
{
unsigned pos = mPosition + off;
if (pos >= mSource.length())
return mSource[mSource.length()];
return mSource[pos];
}
char& Lexer::Next()
{
char& prev = mSource[mPosition];
mColumn++;
mPosition++;
if (mPosition > mSource.length())
{
mColumn--;
mPosition--;
}
return prev;
}
shared_ptr<Token> Lexer::LexAtom(Token::Kind kind)
{ return make_shared<Token>(kind, &Next(), 1, mTrivia, mLine, mColumn, mFile); }
#define KEYWORD(word, key) \
else if (text == #word) \
return make_shared<Token>(Token::##key##Keyword, text, mTrivia, mLine, column, mFile)
shared_ptr<Token> Lexer::LexIdentifier()
{
char* beg = Current;
unsigned column = mColumn;
Next();
while (IsIdentifier(Peek()))
Next();
std::string_view text(beg, std::distance(beg, Current));
if (false);
KEYWORD(void, Void);
KEYWORD(byte, Byte);
KEYWORD(short, Short);
KEYWORD(int, Int);
KEYWORD(integer, Int);
KEYWORD(long, Long);
KEYWORD(bool, Bool);
KEYWORD(boolean, Bool);
KEYWORD(char, Char);
KEYWORD(wchar, WChar);
KEYWORD(wchar_t, WChar);
KEYWORD(float, Float);
KEYWORD(double, Double);
KEYWORD(triple, Triple);
KEYWORD(ret, Return);
KEYWORD(return, Return);
KEYWORD(default, Default);
KEYWORD(extern, Extern);
KEYWORD(external, Extern);
KEYWORD(link, Import);
KEYWORD(import, Import);
KEYWORD(cdecl, CDecl);
KEYWORD(__cdecl, CDecl);
KEYWORD(stdcall, StdCall);
KEYWORD(__stdcall, StdCall);
KEYWORD(dllimport, DllImport);
KEYWORD(__dllimport, DllImport);
KEYWORD(dllexport, DllExport);
KEYWORD(__dllexport, DllExport);
KEYWORD(static, Static);
KEYWORD(local, Local);
KEYWORD(private, Local);
KEYWORD(globl, Global);
KEYWORD(global, Global);
KEYWORD(public, Global);
KEYWORD(__asm, Native);
KEYWORD(native, Native);
KEYWORD(goto, Goto);
KEYWORD(if, If);
KEYWORD(else, Else);
KEYWORD(struct, Struct);
KEYWORD(structure, Struct);
else
return make_shared<Token>(Token::Identifier, text, mTrivia, mLine, column, mFile);
}
shared_ptr<Token> Lexer::LexString()
{
Next(); // Eat "
char* beg = Current;
unsigned ln = mLine;
unsigned column = mColumn;
while (Peek() != '"')
Next();
char* end = Current;
Next();
return make_shared<Token>(Token::String, beg, end, mTrivia, ln, column, mFile);
}
shared_ptr<Token> Lexer::LexNumber()
{
unsigned dotCount = 0;
char* beg = Current;
unsigned column = mColumn;
if (!IsInteger(Next()))
dotCount++;
while (IsInteger(Peek()) || (IsNumber(Peek()) && ++dotCount))
Next();
if (Peek() == 'f' || Peek() == 'F')
return make_shared<Token>(Token::Float, beg, &Next(), mTrivia, mLine, column, mFile);
else if (dotCount)
return make_shared<Token>(Token::Number, beg, Current, mTrivia, mLine, column, mFile);
else
return make_shared<Token>(Token::Integer, beg, Current, mTrivia, mLine, column, mFile);
}
}<file_sep>#pragma once
#include <string>
#include <vector>
#include <iostream>
#include "SympleCode/Memory.h"
#include "SympleCode/Symbol/Symbol.h"
namespace Symple::Symbol
{
class TypeSymbol : public Symbol
{
public: enum TypeKind : unsigned;
private:
TypeKind mTypeKind;
std::string mName;
unsigned mSize;
bool mFloat;
unsigned mPointerCount;
std::vector<char> mModifiers;
public:
TypeSymbol(TypeKind, std::string_view name, unsigned size, bool isFloat = false, unsigned pointerCount = 0, std::vector<char> mods = {});
bool Equals(shared_ptr<TypeSymbol>);
bool Is(TypeKind);
template <typename... Args>
bool Is(TypeKind kind, Args... kinds)
{ return Is(kind) || Is(kinds...); }
void Print(std::ostream & = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "");
void PrintShort(std::ostream & = std::cout);
virtual Kind GetKind() override;
TypeKind GetTypeKind();
std::string_view GetName();
unsigned GetSize();
bool IsFloat();
unsigned GetPointerCount();
std::vector<char>& GetModifiers();
static shared_ptr<TypeSymbol> ErrorType;
static shared_ptr<TypeSymbol> VoidType;
static shared_ptr<TypeSymbol> ByteType;
static shared_ptr<TypeSymbol> ShortType;
static shared_ptr<TypeSymbol> IntType;
static shared_ptr<TypeSymbol> LongType;
static shared_ptr<TypeSymbol> BoolType;
static shared_ptr<TypeSymbol> CharType;
static shared_ptr<TypeSymbol> WCharType;
static shared_ptr<TypeSymbol> FloatType;
static shared_ptr<TypeSymbol> DoubleType;
static shared_ptr<TypeSymbol> TripleType;
static shared_ptr<TypeSymbol> VoidPointerType;
static shared_ptr<TypeSymbol> BytePointerType;
static shared_ptr<TypeSymbol> CharPointerType;
public:
enum TypeKind : unsigned
{
Error,
Void,
Byte,
Short,
Int,
Long,
Bool,
Char,
WChar,
Float,
Double,
Triple,
Struct,
Last = Struct,
};
static constexpr char* TypeKindMap[Last + 1] = {
"Error",
"Void",
"Byte",
"Short",
"Int",
"Long",
"Float",
"Double",
"Triple",
"Struct",
};
};
}<file_sep># Symple C *(Symple Code)* [](LICENSE)

## About Symple C
Symple C is a programming language that is similar to the [C Programming Lanaguage](https://en.wikipedia.org/wiki/C_(programming_language)), but with some additional features.
## Getting the source
```
Disclamer: Symple Code only supports windows at the moment!
```
1) Get required tools
- **Git** (Source control program) you can download from https://git-scm.com/download
- **Visual Studio 2017 or later**
- **Clang** (Compiler)
2) Clone the repository
- `git clone --recursive https://github.com/TeddyTelanoff/SympleCode.git`
3) Run premake
- In your folder, you should see a file called **GenerateProjects.bat**
- Run **GenerateProjects.bat**, it will prompt you what version of visual studio you are using
- for **Visual Studio 2017**, type in `vs2017`
- for **Visual Studio 2019**, type in `vs2019`
- Type enter.
4) Open the Solution
- You should see a file called **SympleCode.sln**, open it and you can view, edit, and compile the source code.
## Remarks
Obviously, making a compiler is no symple task, here are some resources I used:
- [Minsk Compiler (C#)](https://github.com/terrajobst/minsk)
- [Simple C++ Lexer](https://gist.github.com/arrieta/1a309138689e09375b90b3b1aa768e20)
- [chibicc Compiler (C)](https://github.com/rui314/chibicc)
<file_sep>project "SympleLang"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
defines {
"SY_32"
-- "SY_64"
}
files {
"inc/**.h",
"inc/**.hpp",
"src/**.c",
"src/**.cpp",
"sy/**.sy"
}
includedirs {
"inc",
"vendor/spdlog/include"
}
filter "configurations:Debug"
defines "__SY_DEBUG"
symbols "On"
filter "configurations:Release"
defines "__SY_RELEASE"
optimize "On"<file_sep>#pragma once
#include <vector>
#include "SympleCode/Syntax/Lexer.h"
#include "SympleCode/Syntax/Token.h"
#include "SympleCode/Syntax/Node.h"
#include "SympleCode/Syntax/TranslationUnitSyntax.h"
#include "SympleCode/Syntax/MemberSyntax.h"
#include "SympleCode/Syntax/ExternFunctionSyntax.h"
#include "SympleCode/Syntax/FunctionDeclarationSyntax.h"
#include "SympleCode/Syntax/StructDeclarationSyntax.h"
#include "SympleCode/Syntax/StatementSyntax.h"
#include "SympleCode/Syntax/TypeSyntax.h"
#include "SympleCode/Syntax/TypeReferenceSyntax.h"
#include "SympleCode/Syntax/ImportStatementSyntax.h"
#include "SympleCode/Syntax/NativeStatementSyntax.h"
#include "SympleCode/Syntax/LabelSyntax.h"
#include "SympleCode/Syntax/IfStatementSyntax.h"
#include "SympleCode/Syntax/GotoStatementSyntax.h"
#include "SympleCode/Syntax/BlockStatementSyntax.h"
#include "SympleCode/Syntax/ReturnStatementSyntax.h"
#include "SympleCode/Syntax/ExpressionStatementSyntax.h"
#include "SympleCode/Syntax/VariableDeclarationSyntax.h"
#include "SympleCode/Syntax/ExpressionSyntax.h"
#include "SympleCode/Syntax/UnaryExpressionSyntax.h"
#include "SympleCode/Syntax/BinaryExpressionSyntax.h"
#include "SympleCode/Syntax/LiteralExpressionSyntax.h"
#include "SympleCode/Syntax/ParenthesizedExpressionSyntax.h"
#include "SympleCode/Syntax/NameExpressionSyntax.h"
#include "SympleCode/Syntax/CallExpressionSyntax.h"
#include "SympleCode/DiagnosticBag.h"
namespace Symple::Syntax
{
class __SYC_API Parser
{
private:
TokenList mTokens;
unsigned mPosition = 0;
std::vector<std::string> mStructNames;
shared_ptr<DiagnosticBag> mDiagnosticBag = make_shared<DiagnosticBag>();
public:
Parser(shared_ptr<Lexer>);
Parser(shared_ptr<Lexer>, TokenList);
Parser(TokenList);
shared_ptr<TranslationUnitSyntax> Parse();
shared_ptr<MemberSyntax> ParseMember();
shared_ptr<ExternFunctionSyntax> ParseExternFunction();
shared_ptr<FunctionDeclarationSyntax> ParseFunctionDeclaration();
VariableDeclarationList ParseFunctionParameters();
TokenList ParseFunctionModifiers();
shared_ptr<StructDeclarationSyntax> ParseStructDeclaration();
VariableDeclarationList ParseStructMembers();
shared_ptr<StatementSyntax> ParseStatement(bool matchSemicolon = true);
shared_ptr<LabelSyntax> ParseLabel();
shared_ptr<IfStatementSyntax> ParseIfStatement();
shared_ptr<GotoStatementSyntax> ParseGotoStatement();
shared_ptr<BlockStatementSyntax> ParseBlockStatement();
shared_ptr<ReturnStatementSyntax> ParseReturnStatement();
shared_ptr<ImportStatementSyntax> ParseImportStatement();
shared_ptr<NativeStatementSyntax> ParseNativeStatement();
shared_ptr<ExpressionStatementSyntax> ParseExpressionStatement();
shared_ptr<VariableDeclarationSyntax> ParseVariableDeclaration(shared_ptr<TypeSyntax> = nullptr);
shared_ptr<TypeSyntax> ParseType(shared_ptr<TypeSyntax> base = nullptr);
shared_ptr<ExpressionSyntax> ParseExpression();
ExpressionList ParseExpressionList();
shared_ptr<ExpressionSyntax> ParseUnaryExpression(unsigned parentPrecedence = 0);
shared_ptr<ExpressionSyntax> ParseBinaryExpression(unsigned parentPrecedence = 0);
shared_ptr<ExpressionSyntax> ParsePrimaryExpression();
shared_ptr<NameExpressionSyntax> ParseNameExpression();
shared_ptr<CallExpressionSyntax> ParseCallExpression();
shared_ptr<LiteralExpressionSyntax> ParseLiteralExpression();
shared_ptr<ParenthesizedExpressionSyntax> ParseParenthesizedExpression();
shared_ptr<DiagnosticBag> GetDiagnosticBag();
private:
shared_ptr<Token> Peek(unsigned off = 0);
shared_ptr<Token> Next();
shared_ptr<Token> Match(Token::Kind);
bool IsType();
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/Node.h"
namespace Symple::Syntax
{
class MemberSyntax : public Node
{
public:
MemberSyntax(shared_ptr<Token> tok)
: Node(tok) {}
virtual Kind GetKind() override
{ return Member; }
};
}<file_sep>#include "SympleCode/Emit/AsmEmitter.h"
#include <sstream>
#include <spdlog/spdlog.h>
#include "SympleCode/Util/FileUtil.h"
#define _Emit(section, fmt, ...) ((void)fprintf(m##section##Stream, fmt "\n", ##__VA_ARGS__))
namespace Symple::Emit
{
void AsmEmitter::BeginScope()
{ mScope = make_shared<Scope>(mScope); }
void AsmEmitter::EndScope()
{ mScope = mScope->GetBase(); }
char* AsmEmitter::RegAx(unsigned sz)
{
if (sz <= 1)
return "%al";
else if (sz <= 2)
return "%ax";
else if (sz <= 4)
return "%eax";
return nullptr;
}
char* AsmEmitter::RegDx(unsigned sz)
{
if (sz <= 1)
return "%dl";
else if (sz <= 2)
return "%dx";
else if (sz <= 4)
return "%edx";
return nullptr;
}
char AsmEmitter::Suf(unsigned sz)
{
if (sz <= 1)
return 'b';
else if (sz <= 2)
return 'w';
else if (sz <= 4)
return 'l';
return 0xCC;
}
void AsmEmitter::Alloc(unsigned sz)
{
mStackUsage += sz;
if (mStackUsage > mAllocatedStack)
mAllocatedStack = mStackUsage;
}
void AsmEmitter::Free(unsigned sz)
{ mStackUsage -= sz; }
std::string AsmEmitter::GetFunctionAssemblyName(shared_ptr<Symbol::FunctionSymbol> fn)
{
std::stringstream ss;
if (fn->IsDllImport())
ss << "*__imp__";
else
ss << '_';
ss << fn->GetName();
switch (fn->GetCallingConvention())
{
case Symbol::FunctionSymbol::StdCall:
ss << '@';
unsigned numBytes = 0;
for (auto param : fn->GetParameters())
numBytes += param->GetType()->GetSize();
ss << numBytes;
break;
}
return ss.str();
}
AsmEmitter::AsmEmitter(char* file)
: mFile(file)
{
if (mFile)
mTextStream = Util::OpenFile(mFile, "wb+");
else
mTextStream = Util::OpenFile(mFile = "a.S", "wb+");
mDataStream = Util::OpenTempFile();
mBssStream = Util::OpenTempFile();
mExportStream = Util::OpenTempFile();
_Emit(Text, ".text");
_Emit(Data, ".data");
_Emit(Bss, ".bss");
_Emit(Export, "\t.section .drectve,\"yn\"");
}
AsmEmitter::~AsmEmitter()
{ CloseStreams(); }
void AsmEmitter::Compile()
{
CloseStreams();
std::stringstream cmd;
std::string file = mFile;
cmd << "clang -m32 --optimize -c " << mFile << " -o " << file.substr(0, file.find_last_of('.')) << ".obj";
system(cmd.str().c_str());
}
void AsmEmitter::Emit(shared_ptr<Binding::BoundCompilationUnit> unit)
{
mCompilationUnit = unit;
for (auto func : unit->GetFunctions())
EmitFunction(func.first, func.second);
}
void AsmEmitter::EmitFunction(shared_ptr<Symbol::FunctionSymbol> func, shared_ptr<Binding::BoundStatement> body)
{
if (!body) // External Function just ignore
return;
mFunction = func;
mFunctionAssemblyName = GetFunctionAssemblyName(mFunction);
if (mFunction->IsGlobal())
_Emit(Text, ".global %s", mFunctionAssemblyName.c_str());
std::stringstream fnSig;
mFunction->PrintSignature(fnSig);
_Emit(Text, "%s: # %s", mFunctionAssemblyName.c_str(), fnSig.str().c_str());
_Emit(Text, "\t# Begin Stack Frame");
_Emit(Text, "\tpush %%ebp");
_Emit(Text, "\tmov %%esp, %%ebp");
_Emit(Text, "\tsub ..%s.StackSize, %%esp", mFunctionAssemblyName.c_str());
mStackUsage = mAllocatedStack = 0;
BeginScope();
unsigned stackPos = 4;
for (auto param : func->GetParameters())
{
stackPos += 4;
_Emit(Text, "_%s$%i = %i", param->GetName().data(), mScope->GetDepth(), stackPos);
mScope->DeclareVariable(param);
}
mReturning = false;
EmitStatement(body);
EndScope();
if (mReturning)
_Emit(Text, "..%s.Return:", mFunctionAssemblyName.c_str());
_Emit(Text, "\t# End Stack Frame");
_Emit(Text, "\tmov %%ebp, %%esp");
_Emit(Text, "\tpop %%ebp");
_Emit(Text, "\tret");
_Emit(Data, "..%s.StackSize:", mFunctionAssemblyName.c_str());
_Emit(Data, "\t.long %i", mAllocatedStack);
/* Needed for dllexports
.section .drectve,"yn"
.ascii " /EXPORT:%export%"
.addrsig
*/
if (mFunction->IsDllExport())
_Emit(Export, "\t.ascii \" /EXPORT:%s\"", mFunctionAssemblyName.c_str());
}
void AsmEmitter::EmitStatement(shared_ptr<Binding::BoundStatement> stmt)
{
switch (stmt->GetKind())
{
case Binding::Node::Label:
EmitLabel(dynamic_pointer_cast<Binding::BoundLabel>(stmt));
break;
case Binding::Node::NativeCode:
EmitNativeCode(dynamic_pointer_cast<Binding::BoundNativeCode>(stmt));
break;
case Binding::Node::IfStatement:
EmitIfStatement(dynamic_pointer_cast<Binding::BoundIfStatement>(stmt));
break;
case Binding::Node::GotoStatement:
EmitGotoStatement(dynamic_pointer_cast<Binding::BoundGotoStatement>(stmt));
break;
case Binding::Node::BlockStatement:
EmitBlockStatement(dynamic_pointer_cast<Binding::BoundBlockStatement>(stmt));
break;
case Binding::Node::ReturnStatement:
EmitReturnStatement(dynamic_pointer_cast<Binding::BoundReturnStatement>(stmt));
break;
case Binding::Node::ExpressionStatement:
EmitExpressionStatement(dynamic_pointer_cast<Binding::BoundExpressionStatement>(stmt));
break;
case Binding::Node::VariableDeclaration:
EmitVariableDeclaration(dynamic_pointer_cast<Binding::BoundVariableDeclaration>(stmt));
break;
}
}
void AsmEmitter::EmitLabel(shared_ptr<Binding::BoundLabel> stmt)
{ _Emit(Text, "%s.%s:", mFunctionAssemblyName.c_str(), stmt->GetLabel().data()); }
void AsmEmitter::EmitNativeCode(shared_ptr<Binding::BoundNativeCode> stmt)
{ _Emit(Text, "%s", stmt->GetAssembly().data()); }
void AsmEmitter::EmitIfStatement(shared_ptr<Binding::BoundIfStatement> stmt)
{
unsigned c = mDataCount++;
EmitExpression(stmt->GetCondition());
_Emit(Text, "\ttest %%eax, %%eax");
_Emit(Text, "\tje ..else.%i", c);
_Emit(Text, "..if.%i:", c);
EmitStatement(stmt->GetThen());
_Emit(Text, "\tjmp ..end.%i", c);
_Emit(Text, "..else.%i:", c);
EmitStatement(stmt->GetElse());
_Emit(Text, "..end.%i:", c);
}
void AsmEmitter::EmitGotoStatement(shared_ptr<Binding::BoundGotoStatement> stmt)
{ _Emit(Text, "\tjmp %s.%s", mFunctionAssemblyName.c_str(), stmt->GetLabel().data()); }
void AsmEmitter::EmitBlockStatement(shared_ptr<Binding::BoundBlockStatement> stmt)
{
BeginScope();
unsigned pStackUsage = mStackUsage;
for (auto ln : stmt->GetStatements())
EmitStatement(ln);
mStackUsage = pStackUsage;
EndScope();
}
void AsmEmitter::EmitReturnStatement(shared_ptr<Binding::BoundReturnStatement> stmt)
{
EmitExpression(stmt->GetValue());
_Emit(Text, "\tjmp ..%s.Return", GetFunctionAssemblyName(mFunction).c_str());
mReturning = true;
}
void AsmEmitter::EmitExpressionStatement(shared_ptr<Binding::BoundExpressionStatement> stmt)
{ EmitExpression(stmt->GetExpression()); }
void AsmEmitter::EmitVariableDeclaration(shared_ptr<Binding::BoundVariableDeclaration> stmt)
{
std::string_view name = stmt->GetSymbol()->GetName();
unsigned sz = stmt->GetSymbol()->GetType()->GetSize();
Alloc(sz);
_Emit(Text, "_%s$%i = -%i", name.data(), mScope->GetDepth(), mStackUsage);
if (stmt->GetInitializer())
{
EmitExpression(stmt->GetInitializer());
_Emit(Text, "\tmov %s, _%s$%i(%%ebp)", RegAx(sz), name.data(), mScope->GetDepth());
}
mScope->DeclareVariable(stmt->GetSymbol());
}
void AsmEmitter::EmitConstant(shared_ptr<Binding::BoundConstant> val)
{ _Emit(Text, "\tmov $%i, %%eax", val->GetValue()); }
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitExpression(shared_ptr<Binding::BoundExpression> expr)
{
if (expr->ConstantValue())
{
EmitConstant(expr->ConstantValue());
return expr->GetType();
}
else if (expr->GetType()->Equals(Symbol::TypeSymbol::CharPointerType) && expr->Is(Binding::Node::LiteralExpression)) // String Literal
{
for (unsigned i = 0; i < mStringLiterals.size(); i++)
if (mStringLiterals[i] == expr->GetSyntax()->GetToken()->GetText())
{
_Emit(Text, "\tlea ..%i, %%eax", i);
return expr->GetType();
}
_Emit(Data, "..%i:", mDataCount);
_Emit(Data, "\t.string \"%s\"", expr->GetSyntax()->GetToken()->GetText().data());
mStringLiterals.push_back(std::string(expr->GetSyntax()->GetToken()->GetText()));
_Emit(Text, "\tlea ..%i, %%eax", mDataCount++);
return expr->GetType();
}
switch (expr->GetKind())
{
case Binding::Node::CallExpression:
return EmitCallExpression(dynamic_pointer_cast<Binding::BoundCallExpression>(expr));
case Binding::Node::UnaryExpression:
return EmitUnaryExpression(dynamic_pointer_cast<Binding::BoundUnaryExpression> (expr));
case Binding::Node::FunctionPointer:
return EmitFunctionPointer(dynamic_pointer_cast<Binding::BoundFunctionPointer> (expr));
case Binding::Node::BinaryExpression:
return EmitBinaryExpression(dynamic_pointer_cast<Binding::BoundBinaryExpression> (expr));
case Binding::Node::VariableExpression:
return EmitVariableExpression(dynamic_pointer_cast<Binding::BoundVariableExpression> (expr));
default:
_Emit(Text, "\tmov @@ERROR, %%eax");
return Symbol::TypeSymbol::ErrorType;
}
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitCallExpression(shared_ptr<Binding::BoundCallExpression> expr)
{
for (unsigned i = expr->GetArguments().size(); i; i--)
{
EmitExpression(expr->GetArguments()[i - 1]);
_Emit(Text, "\tpush %%eax");
}
_Emit(Text, "\tcall %s", GetFunctionAssemblyName(expr->GetFunction()).c_str());
if (expr->GetFunction()->GetCallingConvention() != Symbol::FunctionSymbol::StdCall)
_Emit(Text, "\tadd $%i, %%esp", expr->GetFunction()->GetParameters().size() * 4);
return expr->GetFunction()->GetType();
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitUnaryExpression(shared_ptr<Binding::BoundUnaryExpression> expr)
{
EmitExpression(expr->GetOperand());
switch (expr->GetOperator()->GetKind())
{
case Binding::BoundUnaryOperator::Negative:
_Emit(Text, "\tneg %%eax");
break;
case Binding::BoundUnaryOperator::Not:
_Emit(Text, "\ttest %%eax, %%eax");
_Emit(Text, "\tsete %%al");
_Emit(Text, "\tmovzbl %%al, %%eax");
break;
}
return expr->GetType();
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitFunctionPointer(shared_ptr<Binding::BoundFunctionPointer> expr)
{
_Emit(Text, "\tlea %s, %%eax", GetFunctionAssemblyName(expr->GetSymbol()).c_str());
return expr->GetType();
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitBinaryExpression(shared_ptr<Binding::BoundBinaryExpression> expr)
{
EmitExpression(expr->GetRight());
_Emit(Text, "\tpush %%eax");
if (expr->IsMutable()) // Assignment
{
EmitExpressionPointer(expr->GetLeft());
_Emit(Text, "\tpop %%edx");
switch (expr->GetOperator()->GetKind())
{
case Binding::BoundBinaryOperator::Assign:
_Emit(Text, "\tmov %s, (%%eax)", RegDx(expr->GetLeft()->GetType()->GetSize()));
break;
}
}
else
{
EmitExpression(expr->GetLeft());
_Emit(Text, "\tpop %%edx");
switch (expr->GetOperator()->GetKind())
{
case Binding::BoundBinaryOperator::Addition:
_Emit(Text, "\tadd %%edx, %%eax");
break;
case Binding::BoundBinaryOperator::Subtraction:
_Emit(Text, "\tsub %%edx, %%eax");
break;
case Binding::BoundBinaryOperator::Multiplication:
_Emit(Text, "\timul %%edx, %%eax");
break;
case Binding::BoundBinaryOperator::Division:
_Emit(Text, "\tmov %%edx, %%ecx");
_Emit(Text, "\tcltd");
_Emit(Text, "\tidiv %%ecx");
break;
case Binding::BoundBinaryOperator::Modulo:
_Emit(Text, "\tmov %%edx, %%ecx");
_Emit(Text, "\tcltd");
_Emit(Text, "\tidiv %%ecx");
_Emit(Text, "\tmov %%edx, %%eax");
break;
}
}
return expr->GetType();
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitVariableExpression(shared_ptr<Binding::BoundVariableExpression> expr)
{
shared_ptr<Symbol::VariableSymbol> var = mScope->GetVariableSymbol(expr->GetSymbol()->GetName());
if (var != expr->GetSymbol())
{
abort(); // Something bad, happening in code...
return Symbol::TypeSymbol::ErrorType;
}
std::string_view name = var->GetName();
unsigned depth = mScope->GetVariableDepth(var->GetName());
unsigned sz = var->GetType()->GetSize();
_Emit(Text, "\tmov _%s$%i(%%ebp), %s", name.data(), depth, RegAx(sz));
if (sz <= 2)
_Emit(Text, "\tmovs%cl %s, %%eax", Suf(sz), RegAx(sz));
return expr->GetType();
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitExpressionPointer(shared_ptr<Binding::BoundExpression> expr)
{
switch (expr->GetKind())
{
case Binding::Node::VariableExpression:
return EmitVariableExpressionPointer(dynamic_pointer_cast<Binding::BoundVariableExpression>(expr));
default:
_Emit(Text, "\tmov @@ERROR, %%eax");
return Symbol::TypeSymbol::ErrorType;
}
}
shared_ptr<Symbol::TypeSymbol> AsmEmitter::EmitVariableExpressionPointer(shared_ptr<Binding::BoundVariableExpression> expr)
{
shared_ptr<Symbol::VariableSymbol> var = mScope->GetVariableSymbol(expr->GetSymbol()->GetName());
__SY_ASSERT(var == expr->GetSymbol(), "Internal Error");
std::string_view name = var->GetName();
unsigned depth = mScope->GetVariableDepth(var->GetName());
_Emit(Text, "\tlea _%s$%i(%%ebp), %%eax", name.data(), depth);
return var->GetType();
}
void AsmEmitter::CloseStreams()
{
if (!mClosed)
{
rewind(mDataStream);
Util::DumpFile(mDataStream, mTextStream);
rewind(mBssStream);
Util::DumpFile(mBssStream, mTextStream);
_Emit(Export, "\t.addrsig");
rewind(mExportStream);
Util::DumpFile(mExportStream, mTextStream);
// Print Output
rewind(mTextStream);
std::stringstream ss;
ss << Util::ReadFile(mTextStream);
Util::SetConsoleColor(Util::ConsoleColor::Yellow);
spdlog::debug("Assembly Code:\n{}", ss.str());
Util::ResetConsoleColor();
Util::CloseFile(mDataStream);
Util::CloseFile(mBssStream);
Util::CloseFile(mTextStream);
mClosed = true;
}
}
}
<file_sep>#pragma once
#include <cstdio>
#include "SympleCode/Binding/BoundLabel.h"
#include "SympleCode/Binding/BoundStatement.h"
#include "SympleCode/Binding/BoundNativeCode.h"
#include "SympleCode/Binding/BoundIfStatement.h"
#include "SympleCode/Binding/BoundGotoStatement.h"
#include "SympleCode/Binding/BoundCallExpression.h"
#include "SympleCode/Binding/BoundCompilationUnit.h"
#include "SympleCode/Binding/BoundReturnStatement.h"
#include "SympleCode/Binding/BoundUnaryExpression.h"
#include "SympleCode/Binding/BoundBinaryExpression.h"
#include "SympleCode/Binding/BoundVariableExpression.h"
#include "SympleCode/Binding/BoundExpressionStatement.h"
#include "SympleCode/Binding/BoundVariableDeclaration.h"
#include "SympleCode/Binding/BoundFunctionPointer.h"
#include "SympleCode/Symbol/FunctionSymbol.h"
#include "SympleCode/Emit/Scope.h"
namespace Symple::Emit
{
class AsmEmitter
{
protected:
char* mFile;
FILE* mTextStream;
FILE* mDataStream;
FILE* mBssStream;
FILE* mExportStream;
shared_ptr<Symbol::FunctionSymbol> mFunction;
shared_ptr<Binding::BoundCompilationUnit> mCompilationUnit;
shared_ptr<Scope> mScope;
std::vector<std::string> mStringLiterals;
void BeginScope();
void EndScope();
char* RegAx(unsigned sz);
char* RegDx(unsigned sz);
char Suf(unsigned sz);
void Alloc(unsigned sz);
void Free(unsigned sz);
bool mClosed = false;
bool mReturning;
std::string mFunctionAssemblyName;
unsigned mAllocatedStack = 0;
unsigned mStackUsage = 0;
unsigned mDataCount = 0;
public:
AsmEmitter(char* file = nullptr);
~AsmEmitter();
void Compile();
void Emit(shared_ptr<Binding::BoundCompilationUnit>);
void EmitFunction(shared_ptr<Symbol::FunctionSymbol>, shared_ptr<Binding::BoundStatement>);
void EmitStatement(shared_ptr<Binding::BoundStatement>);
void EmitLabel(shared_ptr<Binding::BoundLabel>);
void EmitNativeCode(shared_ptr<Binding::BoundNativeCode>);
void EmitIfStatement(shared_ptr<Binding::BoundIfStatement>);
void EmitGotoStatement(shared_ptr<Binding::BoundGotoStatement>);
void EmitBlockStatement(shared_ptr<Binding::BoundBlockStatement>);
void EmitReturnStatement(shared_ptr<Binding::BoundReturnStatement>);
void EmitExpressionStatement(shared_ptr<Binding::BoundExpressionStatement>);
void EmitVariableDeclaration(shared_ptr<Binding::BoundVariableDeclaration>);
void EmitConstant(shared_ptr<Binding::BoundConstant>);
shared_ptr<Symbol::TypeSymbol> EmitExpression(shared_ptr<Binding::BoundExpression>);
shared_ptr<Symbol::TypeSymbol> EmitCallExpression(shared_ptr<Binding::BoundCallExpression>);
shared_ptr<Symbol::TypeSymbol> EmitUnaryExpression(shared_ptr<Binding::BoundUnaryExpression>);
shared_ptr<Symbol::TypeSymbol> EmitFunctionPointer(shared_ptr<Binding::BoundFunctionPointer>);
shared_ptr<Symbol::TypeSymbol> EmitBinaryExpression(shared_ptr<Binding::BoundBinaryExpression>);
shared_ptr<Symbol::TypeSymbol> EmitVariableExpression(shared_ptr<Binding::BoundVariableExpression>);
shared_ptr<Symbol::TypeSymbol> EmitExpressionPointer(shared_ptr<Binding::BoundExpression>);
shared_ptr<Symbol::TypeSymbol> EmitVariableExpressionPointer(shared_ptr<Binding::BoundVariableExpression>);
static std::string GetFunctionAssemblyName(shared_ptr<Symbol::FunctionSymbol>);
private:
void CloseStreams();
};
}<file_sep>#pragma once
#include "SympleCode/Syntax/ExpressionSyntax.h"
namespace Symple::Syntax
{
class BinaryExpressionSyntax : public ExpressionSyntax
{
private:
shared_ptr<ExpressionSyntax> mLeft, mRight;
public:
BinaryExpressionSyntax(shared_ptr<Token> op, shared_ptr<ExpressionSyntax> left, shared_ptr<ExpressionSyntax> right)
: ExpressionSyntax(op), mLeft(left), mRight(right) {}
virtual Kind GetKind() override
{ return BinaryExpression; }
virtual void Print(std::ostream& os = std::cout, std::string_view indent = "", bool last = true, std::string_view label = "") override
{
PrintIndent(os, indent, last, label);
PrintName(os);
os << " [";
GetOperator()->PrintShort(os);
os.put(']');
std::string newIndent(indent);
newIndent += GetAddIndent(last);
os.put('\n'); GetLeft()->Print(os, newIndent, false, "Left = ");
os.put('\n'); GetRight()->Print(os, newIndent, true, "Right = ");
}
shared_ptr<Token> GetOperator()
{ return GetToken(); }
shared_ptr<ExpressionSyntax> GetLeft()
{ return mLeft; }
shared_ptr<ExpressionSyntax> GetRight()
{ return mRight; }
};
}
|
04260882f019ceaa126075e5050e1e0e25eaec44
|
[
"Markdown",
"C++",
"Lua"
] | 95
|
C++
|
TeddyTelanoff/SympleCode
|
687e6f1ed176a2e7186b3faa8fc796640b4a7794
|
f0c5534911181c5571c06b7d7c90f6e78ea364f4
|
refs/heads/master
|
<repo_name>dolymood/vue3-plugin-polyfill<file_sep>/src/mixin.ts
import { getCurrentInstance, defineComponent } from 'vue'
function def(obj: any, key: string, attrs: object) {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
...attrs,
})
}
function handlePolyfillProxy(
instance = getCurrentInstance() as any,
...props: object[]
) {
const proxy = instance.proxy
const getter = proxy['___@getter___']
const setter = proxy['___@setter___']
const target = instance.ctx
if (getter) {
props.forEach(prop => {
Object.keys(prop).forEach(k => {
if (k === '_') {
return
}
def(proxy, k, {
get: getter.bind(target, k),
set: setter.bind(target, k),
})
})
})
return true
}
return false
}
const publicPropertiesMap = {
$: 1,
$el: 1,
$data: 1,
$props: 1,
$attrs: 1,
$slots: 1,
$refs: 1,
$parent: 1,
$root: 1,
$emit: 1,
$options: 1,
$forceUpdate: 1,
$nextTick: 1,
$watch: 1,
}
export const PolyfillMixin = defineComponent({
beforeCreate() {
const instance = getCurrentInstance() as any
handlePolyfillProxy(
instance,
instance.props,
instance.setupState,
instance.appContext.config.globalProperties,
publicPropertiesMap
)
},
created() {
const instance = getCurrentInstance() as any
handlePolyfillProxy(instance, instance.data, instance.ctx) &&
// force call effects agagin to collect deps
instance.effects &&
instance.effects.forEach((effect: Function) => {
effect()
})
},
})
<file_sep>/babel.config.js
const runtimeVersion = require('@babel/runtime/package.json').version
module.exports = {
ignore: [/core-js/, /@babel\/runtime/],
presets: [
[
'@babel/preset-env',
{
corejs: 3,
modules: false,
useBuiltIns: 'usage',
},
],
'@babel/preset-typescript',
],
plugins: [
[
'@babel/plugin-transform-runtime',
{
absoluteRuntime: false,
corejs: false,
helpers: true,
regenerator: false,
useESModules: false,
version: runtimeVersion,
},
],
],
}
<file_sep>/__tests__/mixin.spec.ts
import { mount } from '@vue/test-utils'
import { PolyfillMixin } from '../src/mixin'
import { h, defineComponent, ref, computed, watch, nextTick } from 'vue'
import 'vue-reactivity-polyfill'
import { mockWarn } from 'jest-mock-warn'
const SetupComponent = defineComponent({
props: ['msg'],
mixins: [PolyfillMixin],
setup(props) {
const data = ref('data' + props.msg)
const computedMsg = computed(() => `computed${data.value}`)
watch(
() => data.value,
() => {
console.warn(`watch:${data.value}`)
}
)
const say = () => {
data.value = data.value + props.msg
console.warn(`say:${props.msg},${data.value},${computedMsg.value}`)
}
return () => {
return h('div', [
h('p', null, [props.msg]),
h('p', null, [data.value]),
h('p', null, [computedMsg.value]),
h('button', { onClick: say }, 'say'),
])
}
},
})
const OptionsComponent = defineComponent({
mixins: [PolyfillMixin],
props: ['msg'],
render() {
return h('div', [
h('p', null, [this.msg]),
h('p', null, [this.data]),
h('p', null, [this.computedMsg]),
h('button', { onClick: this.say }, 'say'),
])
},
data() {
return {
data: 'data' + this.msg,
}
},
computed: {
computedMsg(): string {
return `computed${this.data}`
},
},
watch: {
data(newData) {
console.warn(`watch:${newData}`)
},
},
methods: {
say() {
this.data += this.msg
console.warn(`say:${this.msg},${this.data},${this.computedMsg}`)
},
},
})
describe('Polyfill Plugin', () => {
mockWarn()
const propsMsg = 'props-msg'
const components = [
{
name: 'SetupComponent',
create: () => {
return mount(SetupComponent, {
props: {
msg: propsMsg,
},
})
},
},
{
name: 'OptionsComponent',
create: () => {
return mount(OptionsComponent, {
props: {
msg: propsMsg,
},
})
},
},
]
components.forEach(Component => {
describe(Component.name, () => {
test('should render correct', () => {
const wrapper = Component.create()
const msgEle = wrapper.find('p:nth-child(1)')
const dataEle = wrapper.find('p:nth-child(2)')
const computedEle = wrapper.find('p:nth-child(3)')
const actionEle = wrapper.find('button')
expect(msgEle.text()).toEqual(propsMsg)
expect(dataEle.text()).toEqual(`data${propsMsg}`)
expect(computedEle.text()).toEqual(`computeddata${propsMsg}`)
expect(actionEle.text()).toEqual('say')
})
test('should make data reactive', async () => {
const wrapper = Component.create()
const actionEle = wrapper.find('button')
actionEle.trigger('click')
// say
expect(
`say:${propsMsg},data${propsMsg}${propsMsg},computeddata${propsMsg}${propsMsg}`
).toHaveBeenWarnedTimes(1)
await nextTick()
// watch
expect(`watch:data${propsMsg}${propsMsg}`).toHaveBeenWarnedTimes(1)
})
})
})
})
<file_sep>/CHANGELOG.md
# [0.1.0](https://github.com/dolymood/vue3-plugin-polyfill/compare/v0.0.4...v0.1.0) (2020-09-17)
### Bug Fixes
- peer deps ([b44286d](https://github.com/dolymood/vue3-plugin-polyfill/commit/b44286d5658aef13038047f49e7a04dd4174b2e3))
- vue-reactivity to 0.1 ([edb2a74](https://github.com/dolymood/vue3-plugin-polyfill/commit/edb2a74aa89da644c99bd26d893f0a2a482b8395))
## [0.0.4](https://github.com/dolymood/vue3-plugin-polyfill/compare/v0.0.3...v0.0.4) (2020-08-28)
### Bug Fixes
- fix (c) ([ca12c03](https://github.com/dolymood/vue3-plugin-polyfill/commit/ca12c03dafaba09acae5cc60903268b9bd0c22c0))
## [0.0.3](https://github.com/dolymood/vue3-plugin-polyfill/compare/v0.0.2...v0.0.3) (2020-08-26)
### Features
- Use vue-reactivity-polyfill
## [0.0.2](https://github.com/dolymood/vue3-plugin-polyfill/compare/v0.0.1...v0.0.2) (2020-08-25)
### Bug Fixes
- **mixin:** instance can not get correct raw ([39b129a](https://github.com/dolymood/vue3-plugin-polyfill/commit/39b129a6c0efa974abcf3f1441ad42d11478839d))
## 0.0.1 (2020-08-23)
### Features
- init polyfill plugin ([9c21df3](https://github.com/dolymood/vue3-plugin-polyfill/commit/9c21df3d98658928ba4fbda198454e78e4e6b80b))
<file_sep>/src/index.ts
import { App } from 'vue'
import { PolyfillMixin } from './mixin'
export interface PolyfillPlugin {
install(app: App): void
}
export function createPolyfillPlugin(): PolyfillPlugin {
const plugin: PolyfillPlugin = {
install(app: App) {
// mixin PolyfillMixin
app.mixin(PolyfillMixin)
},
}
return plugin
}
<file_sep>/README.md
# vue3-plugin-polyfill [](https://circleci.com/gh/dolymood/vue3-plugin-polyfill)
Vue 3 Ployfill Plugin. Use [vue-reactivity-polyfill](https://github.com/dolymood/vue-reactivity-polyfill).
A full usage demo, [vue-next-demo](https://github.com/dolymood/vue-next-demo).
### Usage
```js
import { createPolyfillPlugin } from 'vue3-plugin-polyfill'
const polyfillPlugin = createPolyfillPlugin()
app.use(polyfillPlugin)
```
<file_sep>/scripts/setupJestEnv.ts
// @ts-ignore
global.Proxy = undefined
// // @ts-ignore
// global.Symbol = undefined
// // @ts-ignore
// global.Reflect = undefined
// // @ts-ignore
// global.Set = undefined
// // @ts-ignore
// global.Map = undefined
// // @ts-ignore
// global.WeakSet = undefined
// // @ts-ignore
// global.WeakMap = undefined
// // @ts-ignore
// const _Symbol = require('core-js/es/symbol')
// // @ts-ignore
// const _Reflect = require('core-js/es/reflect')
// // @ts-ignore
// const _Set = require('core-js/es/set')
// // @ts-ignore
// const _Map = require('core-js/es/map')
// // @ts-ignore
// const _WeakSet = require('core-js/es/weak-set')
// // @ts-ignore
// const _WeakMap = require('core-js/es/weak-map')
// global.Symbol = _Symbol
// global.Reflect = _Reflect
// global.Set = _Set
// global.Map = _Map
// global.WeakSet = _WeakSet
// global.WeakMap = _WeakMap
|
5409bef830b79a20e837c9ff1064df92aca1b0fa
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 7
|
TypeScript
|
dolymood/vue3-plugin-polyfill
|
ff3dc24c659eabfb80784ccac1cf33eb0ec3a5cd
|
35c5553c27d97984b86d9be2012dbbb9a6ee8a3e
|
refs/heads/master
|
<file_sep>const Converter = require('./converter.js');
console.log(Converter.format(100000000))
console.log(Converter.format(10000000))
console.log(Converter.format(1000000))
console.log(Converter.format(100000))
console.log(Converter.format(10000))
console.log(Converter.format(1000))
console.log(Converter.format(123450000))
console.log(Converter.format(12345678))
console.log(Converter.format(1234567))
console.log(Converter.format(123456))
console.log(Converter.format(12345))
console.log(Converter.format(1234))
console.log(Converter.format(123))
console.log(Converter.format(12))
|
1204e7dcc58e4aaf968389b6d2abd96f3f3ff29a
|
[
"JavaScript"
] | 1
|
JavaScript
|
ryanckhung/numberChineseFormat
|
b9926f3edb2c6dfe5dd77b5e823f719c570a8330
|
75f4e77de3bba8de1ed89ec8841678fce7f50d88
|
refs/heads/master
|
<repo_name>michaelcoca/ch7-ex3<file_sep>/ch7-ex3p2/IHasExteriorDoor.cs
namespace ch7_ex3p2
{
interface IHasExteriorDoor
{
string DoorDescription {get;}
Location DoorLocation {get;set;}
}
}
<file_sep>/ch7-ex3p2/Form1.cs
using System;
using System.Windows.Forms;
namespace ch7_ex3p2
{
public partial class Form1 : Form
{
private Location currentLocation;
OutsideWithDoor backYard = new OutsideWithDoor("Back Yard", true, "a screen door");
OutsideWithHidingPlace garden = new OutsideWithHidingPlace("Garden", false, "in the shed");
OutsideWithDoor frontYard = new OutsideWithDoor("Front Yard", false, "an oak door with a brass knob");
RoomWithDoor livingRoom = new RoomWithDoor("Living Room", "an antique carpet", "in the closet", "an oak door with a brass knob");
Room diningRoom = new Room("Dining Room", "a crystal chandelier");
RoomWithDoor kitchen = new RoomWithDoor("Kitchen", "stainless steel appliances", "in the cabinet", "a screen door");
Room stairs = new Room("Stairs", "a wooden banister");
RoomWithHidingPlace upstairsHallway = new RoomWithHidingPlace("Upstairs Hallway", "a picture of a dog", "in the closet");
RoomWithHidingPlace masterBedroom = new RoomWithHidingPlace("Master Bedroom", "a large bed", "under the bed");
RoomWithHidingPlace secondBedroom = new RoomWithHidingPlace("Second Bedroom", "a small bed", "under the bed");
RoomWithHidingPlace bathroom = new RoomWithHidingPlace("Bathroom", "a sink and a toilet", "in the shower");
OutsideWithHidingPlace driveway = new OutsideWithHidingPlace("Driveway", false, "in the garage");
Opponent opponent;
int totalMoves = -1;
public Form1()
{
InitializeComponent();
CreateObjects();
}
public void CreateObjects()
{
backYard.Exits = new Location[] { kitchen, garden, driveway };
garden.Exits = new Location[] { backYard, frontYard };
frontYard.Exits = new Location[] { garden, livingRoom, driveway };
livingRoom.Exits = new Location[] { frontYard, diningRoom, stairs };
diningRoom.Exits = new Location[] { livingRoom, kitchen };
kitchen.Exits = new Location[] { diningRoom, backYard };
stairs.Exits = new Location[] { livingRoom, upstairsHallway };
upstairsHallway.Exits = new Location[] { masterBedroom, secondBedroom, bathroom, stairs };
masterBedroom.Exits = new Location[] { upstairsHallway };
secondBedroom.Exits = new Location[] { upstairsHallway };
bathroom.Exits = new Location[] { upstairsHallway };
driveway.Exits = new Location[] { backYard, frontYard };
livingRoom.DoorLocation = frontYard;
frontYard.DoorLocation = livingRoom;
kitchen.DoorLocation = backYard;
backYard.DoorLocation = kitchen;
MoveToANewLocation(backYard);
goHere.Visible = false;
check.Visible = false;
exits.Visible = false;
goThroughTheDoor.Visible = false;
}
private void MoveToANewLocation(Location newLocation)
{
currentLocation = newLocation;
exits.Items.Clear();
foreach (var item in currentLocation.Exits)
{
exits.Items.Add(item.Name);
}
exits.SelectedIndex = 0;
description.Text = currentLocation.Description;
goThroughTheDoor.Visible = (currentLocation is IHasExteriorDoor);
if (currentLocation is IHidingPlace)
{
check.Visible = true;
IHidingPlace hidingLocation = currentLocation as IHidingPlace;
check.Text = "Check " + hidingLocation.HidingPlaceName;
}
else
check.Visible = false;
totalMoves++;
description.Text += "The player has moved " + totalMoves.ToString() + " times. ";
}
private void goHere_Click(object sender, EventArgs e)
{
MoveToANewLocation(currentLocation.Exits[exits.SelectedIndex]);
}
private void goThroughTheDoor_Click(object sender, EventArgs e)
{
if (currentLocation is IHasExteriorDoor)
{
IHasExteriorDoor withDoor = currentLocation as IHasExteriorDoor;
MoveToANewLocation(withDoor.DoorLocation);
}
}
private void check_Click(object sender, EventArgs e)
{
totalMoves++;
description.Text += "The player has moved " + totalMoves.ToString() + " times. ";
bool isFound = opponent.Check(currentLocation);
if (isFound)
ResetGame();
//else
}
private void ResetGame()
{
MessageBox.Show("You found me in " + totalMoves + " moves!");
IHidingPlace foundLocation = currentLocation as IHidingPlace;
description.Text = "The opponent was hiding " + currentLocation.Name + " in " + totalMoves.ToString() + " moves. ";
opponent = new Opponent(frontYard);
hide.Visible = true;
check.Visible = false;
goHere.Visible = false;
exits.Visible = false;
goThroughTheDoor.Visible = false;
totalMoves = 0;
}
private void RedrawForm()
{
hide.Visible = false;
if (currentLocation is IHidingPlace)
{
check.Visible = true;
IHidingPlace hidingLocation = currentLocation as IHidingPlace;
check.Text = "Check " + hidingLocation.HidingPlaceName;
}
else
check.Visible = false;
goHere.Visible = true;
goThroughTheDoor.Visible = true;
exits.Visible = true;
}
private void hide_Click(object sender, EventArgs e)
{
opponent = new Opponent(frontYard);
for (int i = 0; i < 10; i++)
{
int theCount = i + 1;
description.Text += theCount.ToString() + "... ";
Application.DoEvents();
System.Threading.Thread.Sleep(200);
opponent.Move();
}
description.Text += "Ready or not, here I come! ";
Application.DoEvents();
System.Threading.Thread.Sleep(500);
RedrawForm();
}
}
}
<file_sep>/ch7-ex3/OutsideWithDoor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ch7_ex3
{
public class OutsideWithDoor:Outside, IHasExteriorDoor
{
public OutsideWithDoor(string name, bool hot):base(name, hot)
{
}
private Location doorLocation;
public Location DoorLocation
{
get
{
return doorLocation;
}
set
{
doorLocation = value;
}
}
private string doorDescription;
public string DoorDescription
{
get { return doorDescription; }
}
}
}
<file_sep>/ch7-ex3p2/Opponent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ch7_ex3p2
{
public class Opponent
{
private Location myLocation;
private Random random;
public Opponent(Location myLocation)
{
this.myLocation = myLocation;
this.random = new Random();
}
public void Move()
{
if (myLocation is IHasExteriorDoor && random.Next(2) == 1)
{
IHasExteriorDoor locationWithExteriorDoor = myLocation as IHasExteriorDoor;
myLocation = locationWithExteriorDoor.DoorLocation;
}
do
{
myLocation = myLocation.Exits[random.Next(myLocation.Exits.Length)];
} while (!(myLocation is IHidingPlace));
}
public bool Check(Location location)
{
return location == myLocation;
}
}
}
<file_sep>/ch7-ex3p2/OutsideWithHidingPlace.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ch7_ex3p2
{
public class OutsideWithHidingPlace:Outside, IHidingPlace
{
private string hidingPlaceName;
public string HidingPlaceName
{
get { return hidingPlaceName; }
set { hidingPlaceName = value; }
}
public OutsideWithHidingPlace(string name, bool hot, string hidingPlaceName) :base(name, hot)
{
this.hidingPlaceName = hidingPlaceName;
}
public override string Description
{
get
{
return base.Description + " Someone could hide in " + hidingPlaceName + ". ";
}
}
}
}
|
6d9eb0d63f0851c796281f1601de07d9713833cd
|
[
"C#"
] | 5
|
C#
|
michaelcoca/ch7-ex3
|
08c29c7004e1986bf7676929779c35ad604060c0
|
13f0aabc908ba8d64ce74e6d0ed77736e2f667d9
|
refs/heads/main
|
<file_sep>//
// SearchBarExtension.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import UIKit
extension UISearchBar {
/// This method checks that SearchBar's TextField contains some text or not.
func isSearchable() -> Bool {
if text?.count == 0 {
return false
}
if text?.replacingOccurrences(of: " ", with: "").count == 0 {
return false
}
return true
}
/// This method modifies attributes of searchField
func modifyAttributes(forWeatherCondition condition: String) {
searchTextField.leftView?.tintColor = .white
tintColor = .white
searchTextField.textColor = .white
searchTextField.attributedPlaceholder = NSAttributedString(string: searchTextField.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
searchTextField.layer.borderWidth = 1
searchTextField.layer.borderColor = UIColor.white.cgColor
}
}
<file_sep>//
// LoadedData.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Structure to generate presentable data for view through data loaded from database.
struct LoadedData: Presentable {
var city: String
var temperatureString: String
var feelsLikeTemperatureString: String
var highestTemperatureString: String
var lowestTemperatureString: String
var condition: String
var lastFetchedAt: Date
}
<file_sep>//
// HomeViewController.swift
// Open Weather
//
// Created by <NAME> on 13/10/20.
//
import UIKit
class HomeViewController: UIViewController {
// IBOutlets
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var feelsLikeTempLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var highTempLabel: UILabel!
@IBOutlet weak var LowTempLabel: UILabel!
@IBOutlet weak var weatherConditionImageView: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
// Initialise Weather Manager
var weatherManager = WeatherManager(api: .OpenWeatherMap)
}
//MARK:- Override
extension HomeViewController {
// View Methods
override func viewDidLoad() {
super.viewDidLoad()
searchBar.modifyAttributes(forWeatherCondition: "")
weatherManager.delegate = self
weatherManager.removeDataHavingTimeInterval(86400) // 24 hours
searchBar.delegate = self
}
// User Touches
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
searchBar.endEditing(true)
}
}
//MARK:- SearchBarDelegate
extension HomeViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if searchBar.isSearchable() {
weatherManager.fetchWeather(for: searchBar.text!)
DispatchQueue.main.async {
self.searchBar.text = nil
}
if searchBar.isFirstResponder {
searchBar.endEditing(true)
}
}
}
}
//MARK:- WeatherManagerDelegate
extension HomeViewController: WeatherManagerDelegate {
func didReadData(_ weatherData: Presentable, for city: String, from location: DataRetrievalLocation) {
feelsLikeTempLabel.text = weatherData.feelsLikeTemperatureString
tempLabel.text = weatherData.temperatureString
highTempLabel.text = weatherData.highestTemperatureString
LowTempLabel.text = weatherData.lowestTemperatureString
weatherConditionImageView.image = UIImage(named: weatherData.condition)
cityLabel.text = weatherData.city
}
}
<file_sep>//
// WeatherManager.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
import RealmSwift
/// Structure used to manage tasks related to request creation, execution and fetching weather data using API.
struct WeatherManager: Parsable {
let realmInstance = try? Realm()
var api: WeatherAPI
var delegate: WeatherManagerDelegate?
/// This method creates an URL for API request.
private func createRequest(for city: String) -> URL? {
if let baseUrlString = try? api.getUrl(), let apiKeyWithParameterName = try? api.getKeyWithParameterName(), let cityWithParameterName = try? api.getParameterName(for: .city) + city.replacingOccurrences(of: " ", with: "%20"), let unitWithParameterName = try? api.getParameterName(for: .unit) + "metric" {
let urlString = baseUrlString + cityWithParameterName + "&" + unitWithParameterName + "&" + apiKeyWithParameterName
if let url = URL(string: urlString) {
return url
}
}
return nil
}
/// This methods calls necessary methods to fetch weather data.
func fetchWeather(for city: String) {
if let databaseResults = load(weatherFor: city) {
if let presentableData = generatePresentableData(databaseResults) {
DispatchQueue.main.async {
delegate?.didReadData(presentableData, for: city, from: .Database)
}
}
} else if let url = createRequest(for: city) {
performRequest(for: url)
}
}
/// This method creates a session and retrieves data using API.
private func performRequest(for url: URL) {
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: url) { (data, urlResponse, error) in
if let sessionError = error {
print(sessionError)
return
}
guard let sessionData = data else {
fatalError("error reading session data")
}
if let parsedData = parse(data: sessionData) {
DispatchQueue.main.async {
store(weather: parsedData, of: parsedData.city)
delegate?.didReadData(parsedData, for: parsedData.city, from: .API)
}
}
}
dataTask.resume()
}
}
//MARK:- Database Handling
extension WeatherManager: DatabaseHandling {
func store(weather: WeatherData, of city: String) {
guard let realm = realmInstance else {fatalError("realm instance found nil while storing data")}
do {
let weatherInfo = WeatherInfo()
weatherInfo.addParameters(for: city, weather.temperatureString, weather.feelsLikeTemperatureString, weather.highestTemperatureString, weather.lowestTemperatureString, weather.condition)
try realm.write {
realm.add(weatherInfo)
}
} catch {
print(error.localizedDescription)
}
}
func load(weatherFor city: String? = nil) -> Results<WeatherInfo>? {
guard let realm = realmInstance else {fatalError("realm instance found nil while loading data")}
var databaseResult: Results<WeatherInfo>?
if let cityName = city {
let cityPredicate = NSPredicate(format: "city CONTAINS %@", cityName)
databaseResult = realm.objects(WeatherInfo.self).filter(cityPredicate)
} else {
databaseResult = realm.objects(WeatherInfo.self)
}
if databaseResult?.count == 0 {
return nil
}
return databaseResult
}
func generatePresentableData(_ data: Results<WeatherInfo>) -> Presentable? {
guard let firstResult = data.first else {
print("error loading first element from results")
return nil
}
return LoadedData(city: firstResult.city, temperatureString: firstResult.temperature, feelsLikeTemperatureString: firstResult.feelsLike, highestTemperatureString: firstResult.highestTemperature, lowestTemperatureString: firstResult.lowestTemperature, condition: firstResult.condition, lastFetchedAt: firstResult.fetchedAt)
}
func removeDataHavingTimeInterval(_ timeInterval: TimeInterval) {
if let databaseResults = load() {
for result in databaseResults {
let timeDifference = Date().timeIntervalSince(result.fetchedAt)
if timeDifference > timeInterval {
guard let realm = realmInstance else {fatalError("realm instance found nil while trying to remove database objects")}
do {
try realm.write {
realm.delete(result)
}
} catch {
print(error.localizedDescription)
}
}
}
}
}
}
<file_sep>//
// Presentable.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Contains variables required to present data on a view.
protocol Presentable {
var city: String { get }
var condition: String { get }
var temperatureString: String { get }
var feelsLikeTemperatureString: String { get }
var highestTemperatureString: String { get }
var lowestTemperatureString: String { get }
var lastFetchedAt: Date { get }
}
<file_sep># Open-Weather
An iOS Application to fetch and store weather data.
<b>Features</b>
- Fetches weather data for searched city and stores it in database (Realm Database).
- When same city is searched before 24hrs time interval, the weather data is loaded from the database.
- The weather data in database is deleted after 24hrs.
## Screenshot
<img src="HomeScreen.png" width="250">
## Technologies Used
- Swift Programming Language
- UIKit
- Storyboard
- CocoaPods
- RealmDB
## Credits
- <a href="https://developer.apple.com/documentation"> Apple Developer Documentation </a>
<file_sep>//
// WeatherError.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Errors occurred during tasks related to weather fetching.
enum WeatherError: Error {
case APIKeyNotFound
case APIURLNotFound
case APINotFound
}
<file_sep>//
// DatabaseHandling.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
import RealmSwift
/// Protocol used for handling Realm Database Operations.
protocol DatabaseHandling {
/// This method stores weather data for provided city name in database.
func store(weather: WeatherData, of city: String)
/// This method loads all weather data from database or only for provided city name, depending on the function parameter availability.
func load(weatherFor city: String?) -> Results<WeatherInfo>?
/// This method returns weather data in presentable form to display data on view..
func generatePresentableData(_ data: Results<WeatherInfo>) -> Presentable?
/// This method loads data from database and removes objects which have crossed the timeInterval limit.
/// IMPROVEMENT: Should execute while launching application and loading/fetching data.
func removeDataHavingTimeInterval(_ timeInterval: TimeInterval)
}
<file_sep>//
// WeatherInfo.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
import RealmSwift
class WeatherInfo: Object {
@objc dynamic var city = ""
@objc dynamic var fetchedAt = Date()
@objc dynamic var temperature = ""
@objc dynamic var feelsLike = ""
@objc dynamic var highestTemperature = ""
@objc dynamic var lowestTemperature = ""
@objc dynamic var condition = ""
/// This method makes updating values of an instance easier.
func addParameters(for city: String, _ temperature: String, _ feelsLike: String, _ highestTemperature: String, _ lowestTemperature: String, _ condition: String) {
self.city = city
self.temperature = temperature
self.feelsLike = feelsLike
self.highestTemperature = highestTemperature
self.lowestTemperature = lowestTemperature
self.condition = condition
}
}
<file_sep>//
// WeatherData.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// This structure is the data model required to parse data from OpenWeatherMap API.
struct WeatherData: Decodable {
let weather: [Weather]?
let main: Main
let visibility: Double
let wind: Wind
let sys: Sys
let name: String
}
// Weather Data Parameters
struct Weather: Decodable {
let id: Int
let description: String
}
struct Main: Decodable {
let temp: Double
let feels_like: Double
let temp_min: Double
let temp_max: Double
}
struct Wind: Decodable {
let speed: Double
let deg: Double
}
struct Sys: Decodable {
let country: String
}
// Presentable Variables
extension WeatherData: Presentable {
var lastFetchedAt: Date {
return Date()
}
var city: String {
return name
}
var temperatureString: String {
return String(format: "%.1fºC", main.temp)
}
var feelsLikeTemperatureString: String {
return String(format: "Feels like: %.1fºC", main.feels_like)
}
var lowestTemperatureString: String {
return String(format: "L: %.1fºC", main.temp_min)
}
var highestTemperatureString: String {
return String(format: "H: %.1fºC", main.temp_max)
}
var condition: String {
switch weather![0].id {
case 200...232:
return "bolt"
case 300...321:
return "drizzle"
case 500...531:
return "rain"
case 600...622:
return "snow"
case 701...781:
return "fog"
case 800:
return "sun"
case 801...804:
return "bolt"
default:
return "clouds"
}
}
}
<file_sep>//
// Parsable.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Protocol for tasks related to data parsing.
protocol Parsable {
func parse(data: Data) -> WeatherData?
}
extension Parsable {
/// This method parses WeatherData from retrieved data.
func parse(data: Data) -> WeatherData? {
let decoder = JSONDecoder()
do {
let weatherData = try decoder.decode(WeatherData.self, from: data)
return weatherData
} catch {
print(error)
}
print("unidentified error occurred")
return nil
}
}
<file_sep>//
// WeatherAPI.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Enumeration of Weather APIs for using multiple APIs.
enum WeatherAPI {
case OpenWeatherMap
/// Enumeration of API parameters.
enum Parameter {
case city
case unit
}
}
extension WeatherAPI {
/// This method returns URL String for selected WeatherAPI.
func getUrl() throws -> String {
switch self {
case .OpenWeatherMap:
return "https://api.openweathermap.org/data/2.5/weather?"
@unknown default:
print("url for selected api isn't registered")
throw WeatherError.APIURLNotFound
}
}
/// This method returns Key as String for selected WeatherAPI.
func getKey() throws -> String {
switch self {
case .OpenWeatherMap:
return "871398ec921f8a0d4942d486dedc4d22"
@unknown default:
print("key for selected api isn't registered")
throw WeatherError.APIKeyNotFound
}
}
/// This method returns Key with respective Parameter Name as String according to selected WeatherAPI.
func getKeyWithParameterName() throws -> String {
switch self {
case .OpenWeatherMap:
let key = "871398ec921f8a0d4942d486dedc4d22"
return "appid=\(key)"
@unknown default:
print("key for selected api isn't registered")
throw WeatherError.APIKeyNotFound
}
}
/// This method returns Parameter Name as String for provided Parameter.
func getParameterName(for parameter: Parameter) throws -> String {
switch self {
case .OpenWeatherMap:
switch parameter {
case .unit:
return "units="
case .city:
return "q="
}
@unknown default:
print("API isn't registered")
throw WeatherError.APINotFound
}
}
}
<file_sep>//
// WeatherManagerDelegate.swift
// Open Weather
//
// Created by <NAME> on 14/10/20.
//
import Foundation
/// Contains ways through which data can be retrieved.
enum DataRetrievalLocation {
case Database
case API
}
/// Protocol used as delegate to present weather data on Views.
protocol WeatherManagerDelegate {
/// Tells the delegate that weather data is available for provided city name from specified data retrieval location and is ready to present data on view.
func didReadData(_ weatherData: Presentable, for city: String, from location: DataRetrievalLocation)
}
|
d2862d6ae424137d627cfbc9779e2317eddcc715
|
[
"Swift",
"Markdown"
] | 13
|
Swift
|
nishanttaneja/Open-Weather
|
7277a1452a0b28ea5afa1c9b712c61cef748dc61
|
56278afc6928e360acbdf9291cd08752c7f9c2a2
|
refs/heads/master
|
<repo_name>martafd/learn-python<file_sep>/multithead.py
import threading
import multiprocessing
import time
import random
from multiprocessing import Pool
def worker(number):
sl = random.randrange(1, 10)
time.sleep(sl)
print "Worker {0} sleep {1} seconds".format(number, sl)
print "All threads are running, let's wait until they end!"
for i in range(5):
t = multiprocessing.Process(target=worker, args=(i,))
t.start()
def f(x):
return x*x
if __name__ == '__main__':
p = Pool(3)
print p.map(f, [1, 2, 3])
<file_sep>/first_lesson.py
# coding: utf-8 #if we use python 2
d = 7
if 2!=3 \
and d > 5:
print()
# READ PEP 8!!!!!!!!!!!!!!
# function id() shaw identity of object, functional value ; copywrite semantica, унікальний ідентифікатор
a = 1
b = 1
a is b #перевірка по ід, чи займають об*єкти одну комірку в пам*яті
#найчастіше викор для перевірки a is None
import sys
print(sys.getrefcount(1)) # show how many references to '1'
import gc # garbage collector
for i in range(10):
d = {}
d[0] = d
gc.collect() #show how much elements we delete from memory
gc.get_threshold() # show when garbade collector runs
print(type(NotImplemented)) # ???
print(type(...)) # Ellipsis
# NaN ділення на 0
#memoryview(l)
frozenset([1,2,3,4])
# EAPF !! read about
import builtins
print(dir(builtins))
print( 10/4**3.0)
# raise remember
import random
i = 0
s = random.randint(1, 10)
while i < 5:
try:
ans = int(input('?'))
except ValueError:
continue
if s == ans:
print('ok')
break
elif s < ans:
print('<')
else:
print('>')
i += 1
else:
print('You loose')
print(divmod(5,6)) #ціла частина і остача від ділення
#>pydoc -w ./module.py
#wrote module.html
#python
#--------------factorial-------
def text_prompt(msg):
try:
return input(msg)
except NameError:
return input(msg)
n = int(text_prompt('enter n: '))
if n >= 0:
i = 0
res = 1
for i in range(n):
i += 1
res *= i
print(res)
else:
print('error! number < 0 do not have fact !')
#------------ triangle ---------
def text_prompt(msg):
try:
return input(msg)
except NameError:
return input(msg)
a = float(text_prompt('enter a'))
b = float(text_prompt('enter b'))
c = float(text_prompt('enter c'))
if a > 0 and b > 0 and c > 0:
if a + b <= c :
print('not triangle')
elif a + c <= b :
print('not triangle')
elif b + c <= a :
print('not triangle')
else:
print('triangle')
else:
print('not triangle')
#----------------fibonachi--------
L = [0,1]
n = int(input('enter n:'))
for i in range(n):
k = L[-1] + L[-2]
L.append(k)
print(L[n])
#----------palindroms--------------
def test_prompt(msg):
try:
return input(msg)
except NameError:
return input(msg)
a = input('enter a: ')
a = a.lower()
a = a.replace(' ', '')
if a == a[::-1]:
print('YES')
else:
print("NO")
#-------------strings-1---------
a = input('enter a: ')
k = a.split(' ')
for i in k:
l = k[::-1]
a = ' '.join(l)
print(a)
#--------------tickets-----------
a = int(input('enter a: '))
b = int(input('enter b: '))
j = 0
for i in range(a, b + 1):
x = list(str(i)) # !!!!!!!!
while len(x) < 6:
x.insert(0, 0)
if (int(x[0]) + int(x[1]) + int(x[2])) == (int(x[3]) + int(x[4]) + int(x[5])):
j += 1
print(j)
#------------decoding------------
KEY = '<KEY>'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
a = 'I canT DAnCE i CANt TAlK Hey'
a = a.replace(' ', '')
ab = ''
new = ''
for i in a:
if i.islower():
ab += 'a'
else:
ab += 'b'
for i in range(0,len(a),5):
part = ab[i:i+5]
if len(part) == 5:
new += alphabet[KEY.find(part)]
print(new)
#------------countiog 0-------------
line = '2345'
def count_h(line):
line = str(line)
if line != '' and line[0] == '-':
line = line[1:]
if line is '':
return 'ERROR'
h = {'0': 1, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 1, '7': 0, '8': 2, '9': 1}
count = 0
chars_allowed = h.keys()
not_zero_char = chars_allowed[:]
not_zero_char.remove('0')
num_start = False
for i in line:
if not (i in chars_allowed):
return 'ERROR'
if i in not_zero_char:
num_start = True
if num_start:
count += int(h[i])
print(count)
if not num_start:
count = 188
return count
#------------------------------
class Human:
name = None
sex = None
birth_year = None
def __init__(self, name, year, mother = None, father = None):
self.name = name
self.birth_year = year
self.mother = mother
self.father = father
def get_age(self):
if type(self.birth_year) == int:
return 2016 - self.birth_year
return None
def say_parents(self):
p1 = ''
if self.mother:
p1 = 'mother is ' + self.mother.name
p2 = ''
if self.father:
p2 = 'father is ' + self.father.name
if p2 and p2:
return 'My ' + p1 + ' and my ' + p2
return 'My ' + p1 + p2
def say(self, msg):
return self.name + ' says: ' + msg + '.'
sergey = Human('Sergey', 1998)
print(sergey.name)
print(sergey.get_age())
alena = Human('Alena', 1968)
taras = Human('Taras', 1966)
vova = Human('Vova', 1994, alena, taras)
print(vova.say_parents())
print(vova.say(vova.say_parents()))
class Student(Human):
vuz = None
marks = []
def __init__(self, name, year, vuz, marks = [], mother = None, father = None):
super(Student, self).__init__(name, year, mother, father)
self.vuz = vuz
self.marks = marks
def aver_marks(self):
if len(self.marks):
return 1.0 * sum(self.marks) / len(self.marks)
return 0
def has_grand(self):
return True
vlad = Student('Vlad', 1993, 'KPI', [3,4,5,5,5], vova, alena)
print(vlad.vuz)
class Student_KPI(Student):
def __init__(self, name, year, marks = ''):
super(Student_KPI, self).__init__(name, year, 'KPI', marks)
def has_grand(self):
return self.aver_marks() >= 4
class Student_KNU(Student):
def __init__(self, name, year, marks = []):
super(Student_KNU, self).__init__(name, year, 'KNU', marks)
def has_grand(self):
return min(self.marks) >= 4
sonya = Student_KNU('Sonya', 1994, [3,4,5,5,5,5,4,3])
print(sonya.has_grand())
nata = Student_KPI('Natalka', 1995, [3,4,5,5,4,5,])
print(nata.has_grand())
#-----------------------------------
import math
class Sphere:
radius = 1
x_0 = 0
y_0 = 0
z_0 = 0
def __init__(self,r = 1., x = 0., y = 0., z = 0.):
self.radius = r
self.x_0 = x
self.y_0 = y
self.z_0 = z
def get_volume(self):
return 4.0/3 * math.pi * pow(self.radius, 3)
def get_square(self):
return 4 * math.pi * pow(self.radius, 2)
def get_radius(self):
return self.radius
def get_center(self):
return (self.x_0, self.y_0, self.z_0)
def set_radius(self, r):
self.radius = r
def set_center(self, x, y, z):
self.x_0 = x
self.y_0 = y
self.z_0 = z
def is_point_inside(self, x, y, z):
if self.x_0 - x <= self.radius and self.y_0 - y <= self.radius and self.z_0 - z <= self.radius:
return True
else:
return False
s = Sphere(0.5)
print(s.get_center())
print(s.get_volume())
print(s.is_point_inside(0, -1.5, 0))
s.set_radius(1.6)
print(s.is_point_inside(0, -1.5, 0))
print(s.get_radius())
#--------------------class student prometheus --------------
class Student_prom():
name = ''
marks = {}
conf = {}
def __init__(self, name, conf):
self.name = name
self.conf = conf
self.marks = {}
self.marks['exam'] = 0
self.marks['labs'] = []
for i in range(self.conf['lab_num']):
self.marks['labs'].append(0)
def make_lab(self, mark , number = None):
mark = min(mark, self.conf['lab_max']) # m cant be more than lab_max
if number is None: # if n is not given; find the first task with no mark, set the mark and reload m
if 0 in self.marks['labs']:
self.marks['labs'][self.marks['labs'].index(0)] = mark
elif number >= 0 and number < len(self.marks['labs']): #if the task with n exist, reload m
self.marks['labs'][number] = mark
return self
def make_exam(self,mark):
self.marks['exam'] = min(mark, self.conf['exam_max'])
return self
def is_certified(self):
total_max = self.conf['exam_max'] + self.conf['lab_max'] * self.conf['lab_num'] # possible maximum
sum = 1.0* self.marks['exam']
for i in range(len(self.marks['labs'])):
sum = sum + min(self.conf['lab_max'], self.marks['labs'][i])
return (sum, sum >= total_max * self.conf['k'])
oleg = Student_prom('Oleg', {'exam_max': 30, 'lab_max': 7, 'lab_num': 10, 'k': 0.61})
oleg.make_lab(1) # labs: 1 0 0 0 0 0 0 0 0 0, exam: 0
oleg.make_lab(8,0) # labs: 7 0 0 0 0 0 0 0 0 0, exam: 0
oleg.make_lab(1) # labs: 7 1 0 0 0 0 0 0 0 0, exam: 0
oleg.make_lab(10,7) # labs: 7 1 0 0 0 0 0 7 0 0, exam: 0
oleg.make_lab(4,1) # labs: 7 4 0 0 0 0 0 7 0 0, exam: 0
oleg.make_lab(5) # labs: 7 4 5 0 0 0 0 7 0 0, exam: 0
oleg.make_lab(6.5) # labs: 7 4 5 6.5 0 0 0 7 0 0, exam: 0
oleg.make_exam(32) # labs: 7 4 5 6.5 0 0 0 7 0 0, exam: 30
print(oleg.is_certified() )# (59.5, False)
oleg.make_lab(7,1) # labs: 7 7 5 6.5 0 0 0 7 0 0, exam: 30
print(oleg.is_certified()) # (62.5, True)
#---------------class SuperStr-------------------------
class SuperStr(str):
def __init__(self, s):
self.s = s
def is_repeatance(self,subs):
if type(subs) == str and len(subs) != 0:
multiply = int(len(self.s) / len(subs))
if self.s == subs * multiply:
return True
else:
return False
else:
return False
def is_palindrom(self):
if self.s.lower().replace(' ', '') == self.s[::-1].lower().replace(' ', ''):
return True
else:
return False
s = SuperStr('123123123123')
print(s.is_repeatance('123')) # True
print(s.is_repeatance('123123')) # True
print(s.is_repeatance('123123123123')) # True
print(s.is_repeatance('12312')) # False
print(s.is_repeatance(123)) # False
print(s.is_palindrom()) # False
print(s) # 123123123123 (рядок)
print(int(s)) # 123123123123 (ціле число)
print(s + 'qwe') # 123123123123qwe
p = SuperStr('123_321')
print(p.is_palindrom()) # True
<file_sep>/decorators.py
# decorators are like wrappers for function
def dec(func):
def func_wrap():
print 'Before func '
func()
print 'After func '
return func_wrap
@dec
def hello():
print 'hello world'
# hello()
# decorators are used to find executable time
import time
from random import randint
def time_ex(count):
def wrapper(fn):
def wrap(*args):
times = []
for i in xrange(count):
start = time.time()
res = fn(*args)
end = time.time()
times.append(round(end-start, 5))
print 'Avg. time {0}s. \nMax time {1}s. \nMin time {2}s.'.format(sum(times) / count,
max(times) / count, min(times) / count)
return res
return wra
return wrapper
@time_ex(3)
def slow_fn(x):
time.sleep(randint(1000, 3000)/1000)
return x*x
# decorators are used to check types
def typed(*types):
def wrapper(fn):
def wrap(*func_args):
for i in range(len(types)):
if type(func_args[i]) != types[i]:
print func_args[i]
raise TypeError('Not correct type!!!!')
return fn(*func_args)
return wrap
return wrapper
@typed(int, int, int)
def typed_fn(x, y, z):
return x * y * z
@typed(str, str, str)
def typed_fn2(x, y, z):
return x + y + z
@typed(str, str, int)
def typed_fn3(x, y, z=""):
return (x + y) * z
# decorators are used in db transactions
def transaction(db):
def wrapper(fn):
def wrap(*args):
res = None
db.start_transaction()
try:
res = fn(*args)
except Exception as e:
db.rollback()
raise e
else:
db.end_transaction()
return wrap()
return wrapper()
@transaction(db)
def action(db):
db.ids.insert(1/0)
<file_sep>/README.md
# learn-python
My learning python project
|
dc78864f0de63ae0b7312a5f9ab63296d210063e
|
[
"Markdown",
"Python"
] | 4
|
Python
|
martafd/learn-python
|
40e8afb5de33598d8916577e15993d85d0004b7a
|
7f895f105a033635f24b2de8f343662086270167
|
refs/heads/master
|
<repo_name>zyfgfg/data-structure<file_sep>/family/cmake-build-debug/CMakeFiles/family.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/family.dir/family.c.o"
"family"
"family.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/family.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/ch05/example/biTreeNode.c
#include "biTreeNode.h"
void printBiTreeElement(BiTreeElement elem) {
printf("%s ", elem);
}
/**
* 创建树
* @return 树根节点指针
*/
BiTreeNodeAddr biTreeCreate(BiTreeElement elem) {
BiTreeNodeAddr rlt = (BiTreeNodeAddr) malloc(sizeof(BiTreeNode));
rlt->element = elem;
rlt->left = NULL;
rlt->right = NULL;
return rlt;
}
int biTreePutLeaf(BiTreeNodeAddr nodeAddr, BiTreeElement leftElem, BiTreeElement rightElem) {
if (leftElem != NULL) {
if (nodeAddr->left == NULL) {
nodeAddr->left = biTreeCreate(leftElem);
} else {
nodeAddr->left->element = leftElem;
}
}
if (rightElem != NULL) {
if (nodeAddr->right == NULL) {
nodeAddr->right = biTreeCreate(rightElem);
} else {
nodeAddr->right->element = rightElem;
}
}
return 1;
}
void biTreePreOrder(BiTreeNodeAddr nodeAddr) {
if (nodeAddr == NULL) {
return;
}
printBiTreeElement(nodeAddr->element);
biTreePreOrder(nodeAddr->left);
biTreePreOrder(nodeAddr->right);
}
void biTreeInOrder(BiTreeNodeAddr nodeAddr) {
if (nodeAddr == NULL) {
return;
}
biTreeInOrder(nodeAddr->left);
printBiTreeElement(nodeAddr->element);
biTreeInOrder(nodeAddr->right);
}
void biTreePostOrder(BiTreeNodeAddr nodeAddr) {
if (nodeAddr == NULL) {
return;
}
biTreePostOrder(nodeAddr->left);
biTreePostOrder(nodeAddr->right);
printBiTreeElement(nodeAddr->element);
}
<file_sep>/family/family.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <stdbool.h>
char bir[20][400];
int number=0;
typedef struct Infomation {
char num[400];
char name[400];
char sexy[400];
char birth[400];
char child[400];
} Info;
typedef struct bnode {
Info person;
struct bnode *lchild, *rchild;
} BNode, *BiTree;
static Info human[10000];
static int n;
void new_left(BiTree p, Info info) {
BiTree q = (BiTree) malloc(sizeof(BNode));
q->person = info;
q->lchild = q->rchild = NULL;
p->lchild = q;}
void new_right(BiTree p, Info info) {
BiTree q = (BiTree) malloc(sizeof(BNode));
q->person = info;
q->lchild = q->rchild = NULL;
p->rchild = q;}
BiTree create() { BiTree bt;
FILE *fp = NULL; // 文件指针
long len; // 家谱文件长度
int n; // 家谱文件中的记录个数
fp = fopen(".family", "r");
if(fp == NULL)
{
n = 0;
return 0;
}
fseek(fp, 0, SEEK_END); // 家谱文件位置指针移到家谱文件末尾
len = ftell(fp); // len求出家谱文件长度
rewind(fp); // 家谱文件位置指针移到家谱文件开头
n = len / sizeof(Info);// n求出家谱文件中的记录个数
for(int i = 0; i < 1; i++)
fread(&human[i], sizeof(Info), 1, fp); // 将家谱文件中的数据读到fam数组中
fclose(fp);
struct Infomation human[7] ={{"第一代", "张一", "男", "2019-1-11", "张二,张三"},
{"第二代", "张二", "男", "2049-2-11", "张四,张五"},
{"第二代", "张三", "男", "2041-3-11", "张六,张七"},
{"第三代", "张四", "男", "2079-4-11", " 无"},
{"第三代", "张五", "男", "2080-5-11", " 无"},
{"第三代", "张六", "男", "2099-6-11", " 无"},
{"第三代", "张七", "男", "2100-7-11", " 无"}};
bt= (BiTree) malloc(sizeof(BNode));
bt->person = human[0];
bt->lchild = bt->rchild = NULL;
new_left(bt,human[1]);
new_right(bt, human[2]);
new_left(bt->lchild, human[3]);
new_right(bt->lchild, human[4]);
new_left(bt->rchild, human[5]);
new_right(bt->rchild, human[6]);
return bt;}
void output(BiTree p)//输出某结点的信息
{printf("%s %s %s %s %s\n", p->person.num, p->person.name, p->person.sexy, p->person.birth,p->person.child);}
void display(BiTree t) //输出数据
{BiTree q[400], p;
int front, rear;
front = rear = 0;
printf("1.从文件读取家族信息并显示\n");
printf(" 辈 分 姓名 性别 出 生 日 期 孩子 \n");
if (t) {
rear++;
q[rear] = t;
while (front != rear) {
front = (front + 1) % 20;
p = q[front];
output(p);
if ((rear + 1) % 20 != front && p->lchild != NULL) {
rear = (rear + 1) % 20;
q[rear] = p->lchild;}
if ((rear + 1) % 20 != front && p->rchild != NULL) {
rear = (rear + 1) % 20;
q[rear] = p->rchild;}}}}
BiTree Parent(BiTree bt, BiTree p) //找到结点p的双亲并返回
{BiTree l_result, r_result;
if (!bt || bt == p)
return NULL;
if (bt->lchild == p || bt->rchild == p)
return bt;
else {
l_result = Parent(bt->lchild, p);
r_result = Parent(bt->rchild, p);
return l_result ? l_result : (r_result ? r_result : NULL);}}
BiTree search_name(BiTree bt, char na[]) //通过名字找到结点并返回
{BiTree l_result, r_result;
if (!bt)
return NULL;
if (strcmp(bt->person.name, na) == 0)
return bt;
else {
l_result = search_name(bt->lchild, na);
r_result = search_name(bt->rchild, na);
return l_result ? l_result : (r_result ? r_result : NULL);}}
void search(BiTree bt)//根据姓名查找信息
{char na[400];
BiTree node, child[2];
printf("请输入你想查找的那个人的姓名:\n");
scanf("%s", na);
node = search_name(bt, na);
printf("你查找的这个人的信息为:\n");
printf("辈分 姓名 性别 出 生 日 期 孩子 \n");
output(node);}
void add(BiTree bt) //添加孩子
{char na[20];
int i;
BiTree p;
Info new_child;
printf("请输入你想让其拥有孩子的那个人的名字:\n");
scanf("%s", na);
p = search_name(bt, na);
printf("你是想让他有熊孩子呀,还是奶孩子呀?左孩子请按1,右孩子请按0:\n");
scanf("%d", &i);
switch (i) {
case 1:
if (p->lchild != NULL) {
printf("添加失败!超生了!!!\n");
break;
} else {
printf("请输入新孩子的辈分");
scanf("%s", new_child.num);
printf("请输入新孩子的姓名:\n");
scanf("%s", new_child.name);
printf("请输入新孩子的性别:\n");
scanf("%s", new_child.sexy);
printf("请输入新孩子的出生日期:\n");
scanf("%s", new_child.birth);
printf("请输入新孩子的孩子:\n");
scanf("%s", new_child.child);
new_left(p, new_child);
break;}
case 2:
if (p->rchild != NULL) {
printf("添加失败!超生了\n");
break;}
else {printf("请输入新孩子的辈分");
scanf("%s", new_child.num);
printf("请输入新孩子的姓名:\n");
scanf("%s", new_child.name);
printf("请输入新孩子的性别:\n");
scanf("%s", new_child.sexy);
printf("请输入新孩子的出生日期:\n");
scanf("%s", new_child.birth);
printf("请输入新孩子的孩子:\n");
scanf("%s", new_child.child);
new_right(p, new_child);
break;}}}
void update(BiTree bt)//更改信息
{char na[20];
BiTree p;
printf("请输入你想修改孩子的姓名:\n");
scanf("%s", na);
p = search_name(bt, na);
printf("请输入修改过后的辈分:\n");
scanf("%s", p->person.num);
printf("请输入修改过后的姓名:\n");
scanf("%s", p->person.name);
printf("请输入修改过后的性别:\n");
scanf("%s", p->person.sexy);
printf("请输入修改过后的出生日期:\n");
scanf("%s", p->person.birth);
printf("请输入修改过后的所拥有的孩子:\n");
scanf("%s", p->person.child);}
void delete(BiTree bt) //删除一个结点和他的孩子们孙子们
{char na[20];
BiTree p, f;
printf("请输入你想删除的那个人的姓名,删除之后他的孩子孙子们也将一并删除!\n");
scanf("%s", na);
p = search_name(bt, na);
f = Parent(bt, p);
if (f != NULL) {
if (f->lchild == p) {
f->lchild = NULL;
free(p);}
if (f->rchild == p) {
f->rchild = NULL;
free(p);}
} else { bt = NULL; }}
BiTree search_birth(BiTree bt, char bir[]) //通过生日找到结点并返回
{BiTree l_result, r_result;
if (!bt)
return NULL;
if (strcmp(bt->person.birth, bir) == 0)
return bt;
else {
l_result = search_birth(bt->lchild, bir);
r_result = search_birth(bt->rchild, bir);
return l_result ? l_result : (r_result ? r_result : NULL);}}
void transport(BiTree bt) //把家谱中所有人的生日传参给二维数组bir[][]
{if (bt) {strcpy(bir[(number)++], bt->person.birth);
{transport(bt->rchild);
transport(bt->lchild);}}}
void transfer(BiTree bt, int n)//将二维数组升序排序并输出
{n = 1;
char t[20]={};
int i, j;
BiTree p;
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++)
if (strcmp(bir[i], bir[j]) > 0) {
strcpy(t, bir[i]);
strcpy(bir[i], bir[j]);
strcpy(bir[j], t);}
for (i = 0; i < n; i++) {
p = search_birth(bt, bir[i]);
output(p);}
puts("");}
void menu() {printf("1.从文件读取家族信息并显示\n2. 根据姓名查询,输出成员信息\n3. 给某个成员添加孩⼦\n""4. 修改某个成员信息\n""5. 删除某成员(连同其后代) \n6. 按出⽣生⽇日期增顺显示家族成员\n7. 退出系统\n");}
int main() {
BiTree bt;
int i,a = 0;
printf("欢迎来到家谱管理系统!\n");
bt = create();
LL1:menu();
printf("请输入你的选择:");
scanf("%d", &i);
switch (i) {
case 1:
display(bt);
goto LL1;
case 2:
search(bt);
goto LL1;
case 3:
add(bt);
goto LL1;
case 4:
update(bt);
goto LL1;
case 5:
delete(bt);
goto LL1;
case 6:
transport(bt);
transfer(bt,a);
goto LL1;
case 7:
break;
default:
printf("你的输入有误,请重新输入!\n");
goto LL1;}}
<file_sep>/ch04/example/queueDemo.c
//n
// Created by 李熠 on 2019/10/12.
//
#include "queue.h"
int main(void) {
SeqList *seqListAddr = seqListCreate();
seqQueueOffer(seqListAddr,50);
seqQueueOffer(seqListAddr,100);
seqQueueOffer(seqListAddr,65);
seqListDisplay(seqListAddr);
printf("\n%d\n",seqQueuePoll(seqListAddr));
printf("%d\n",seqQueuePoll(seqListAddr));
printf("peek=%d\n",seqQueuePeek(seqListAddr));
printf("isEmpty=%d\n",seqQueueIsEmpty(seqListAddr));
printf("%d\n",seqQueuePoll(seqListAddr));
printf("isEmpty=%d\n",seqQueueIsEmpty(seqListAddr));
seqListDisplay(seqListAddr);
printf("\n\n");
SinglyIntNode *singlyListAddr= singlyIntNodeCreate();
linkedQueueOffer(singlyListAddr,50);
linkedQueueOffer(singlyListAddr,100);
linkedQueueOffer(singlyListAddr,65);
singlyIntNodeDisplay(singlyListAddr);
printf("%d\n",linkedQueuePoll(singlyListAddr));
printf("%d\n",linkedQueuePoll(singlyListAddr));
printf("peek=%d\n",linkedQueuePeek(singlyListAddr));
printf("isEmpty=%d\n",linkedIsEmpty(singlyListAddr));
printf("%d\n",linkedQueuePoll(singlyListAddr));
printf("isEmpty=%d\n",linkedIsEmpty(singlyListAddr));
singlyIntNodeDisplay(singlyListAddr);
return 0;
}<file_sep>/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/stack.dir/Users/edz/project/data-structure/ch01/examples/seqlist.c.o"
"CMakeFiles/stack.dir/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o"
"CMakeFiles/stack.dir/stack.c.o"
"CMakeFiles/stack.dir/stackDemo.c.o"
"stack"
"stack.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/stack.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/ch02/example/singlyIntNode.c
//
// Created by 李熠 on 2019/10/10.
//
#include "singlyIntNode.h"
SinglyIntNode *singlyIntNodeCreate() {
SinglyIntNode *rlt = (SinglyIntNode *) malloc(sizeof(SinglyIntNode));
rlt->value = 0;
rlt->next = NULL;
return rlt;
}
void singlyIntNodeAdd(SinglyIntNode *head, int elem) {
SinglyIntNode *newNode = singlyIntNodeCreate();
SinglyIntNode *lastNode = head;
while (lastNode->next) {
lastNode = lastNode->next;
}
newNode->value = elem;
lastNode->next = newNode;
head->value++;
}
void singlyIntNodeDisplay(const SinglyIntNode *head) {
printf("singly node size=%d\n", head->value);
SinglyIntNode *curNode = head->next;
int count = 0;
while (curNode != NULL) {
printf("[%d]=%d ", count++, curNode->value);
curNode = curNode->next;
}
printf("\n");
}
void singlyIntNodeDestroy(SinglyIntNode *head) {
SinglyIntNode *curNode = head;
SinglyIntNode *temp;
while (curNode != NULL) {
temp = curNode->next;
free(curNode);
curNode = temp;
}
}
int singlyIntNodeInsert(SinglyIntNode *head, int index, int elem) {
if (index < 0 || index >= head->value) {
printf("index is illegal!");
return 0;
}
SinglyIntNode *beforeIndexNode = head;
for (int i = 0; i < index; ++i) {
beforeIndexNode = beforeIndexNode->next;
}
SinglyIntNode *newNode = singlyIntNodeCreate();
newNode->next = beforeIndexNode->next;
newNode->value = elem;
beforeIndexNode->next = newNode;
head->value++;
}
<file_sep>/ch03/example/cmake-build-debug/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.15
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake
# The command to remove a file.
RM = /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/edz/project/data-structure/ch03/example
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/edz/project/data-structure/ch03/example/cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles /Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named stack
# Build rule for target.
stack: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 stack
.PHONY : stack
# fast build rule for target.
stack/fast:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/build
.PHONY : stack/fast
Users/edz/project/data-structure/ch01/examples/seqlist.o: Users/edz/project/data-structure/ch01/examples/seqlist.c.o
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.o
# target to build an object file
Users/edz/project/data-structure/ch01/examples/seqlist.c.o:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch01/examples/seqlist.c.o
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.c.o
Users/edz/project/data-structure/ch01/examples/seqlist.i: Users/edz/project/data-structure/ch01/examples/seqlist.c.i
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.i
# target to preprocess a source file
Users/edz/project/data-structure/ch01/examples/seqlist.c.i:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch01/examples/seqlist.c.i
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.c.i
Users/edz/project/data-structure/ch01/examples/seqlist.s: Users/edz/project/data-structure/ch01/examples/seqlist.c.s
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.s
# target to generate assembly for a file
Users/edz/project/data-structure/ch01/examples/seqlist.c.s:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch01/examples/seqlist.c.s
.PHONY : Users/edz/project/data-structure/ch01/examples/seqlist.c.s
Users/edz/project/data-structure/ch02/examples/singlyIntNode.o: Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.o
# target to build an object file
Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o
Users/edz/project/data-structure/ch02/examples/singlyIntNode.i: Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.i
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.i
# target to preprocess a source file
Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.i:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.i
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.i
Users/edz/project/data-structure/ch02/examples/singlyIntNode.s: Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.s
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.s
# target to generate assembly for a file
Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.s:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.s
.PHONY : Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.s
stack.o: stack.c.o
.PHONY : stack.o
# target to build an object file
stack.c.o:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stack.c.o
.PHONY : stack.c.o
stack.i: stack.c.i
.PHONY : stack.i
# target to preprocess a source file
stack.c.i:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stack.c.i
.PHONY : stack.c.i
stack.s: stack.c.s
.PHONY : stack.s
# target to generate assembly for a file
stack.c.s:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stack.c.s
.PHONY : stack.c.s
stackDemo.o: stackDemo.c.o
.PHONY : stackDemo.o
# target to build an object file
stackDemo.c.o:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stackDemo.c.o
.PHONY : stackDemo.c.o
stackDemo.i: stackDemo.c.i
.PHONY : stackDemo.i
# target to preprocess a source file
stackDemo.c.i:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stackDemo.c.i
.PHONY : stackDemo.c.i
stackDemo.s: stackDemo.c.s
.PHONY : stackDemo.s
# target to generate assembly for a file
stackDemo.c.s:
$(MAKE) -f CMakeFiles/stack.dir/build.make CMakeFiles/stack.dir/stackDemo.c.s
.PHONY : stackDemo.c.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... stack"
@echo "... Users/edz/project/data-structure/ch01/examples/seqlist.o"
@echo "... Users/edz/project/data-structure/ch01/examples/seqlist.i"
@echo "... Users/edz/project/data-structure/ch01/examples/seqlist.s"
@echo "... Users/edz/project/data-structure/ch02/examples/singlyIntNode.o"
@echo "... Users/edz/project/data-structure/ch02/examples/singlyIntNode.i"
@echo "... Users/edz/project/data-structure/ch02/examples/singlyIntNode.s"
@echo "... stack.o"
@echo "... stack.i"
@echo "... stack.s"
@echo "... stackDemo.o"
@echo "... stackDemo.i"
@echo "... stackDemo.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/ch01/example/seqlist.c
#include "seqlist.h"
SeqList *seqListCreate() {
SeqList *seqListAddr = (SeqList *) malloc(sizeof(SeqList));
seqListAddr->head = (int *) calloc(CAPACITY_STEP_SIZE, sizeof(int));
seqListAddr->length = 0;
seqListAddr->capacity = CAPACITY_STEP_SIZE;
return seqListAddr;
}
void seqListDestroy(SeqList *list) {
int *p = list->head;
free(list);
free(p);
}
SeqList seqListCreateDirect() {
SeqList seqList;
seqList.head = (int *) calloc(CAPACITY_STEP_SIZE, sizeof(int));
seqList.length = 0;
seqList.capacity = CAPACITY_STEP_SIZE;
printf("inside = %p\n", &seqList);
return seqList;
}
void seqListDisplay(const SeqList *seqList) {
for (int i = 1; i < seqList->length; i++) {
printf("[%d]=%d", i, seqList->head[i]);
}putchar('\n');
}
/**
* 结尾追加元素
* @param list
* @param elem
*/
void seqListAdd(SeqList *list, int elem) {
//插入位置判断,取值范围为0~length
// if (elem > list->length || elem < 0) {
// printf("插入位置有误\n");
// return 1;
// }
//重新分配内存
if (list->length == list->capacity) {
int *temp = (int *)realloc(list->head, (list->capacity + 1) * sizeof(int));
if (!temp) {
printf("内存分配失败!\n");
// return 1;
}
list->head = temp;
list->capacity += 1;
list->length+=1;
}
// for (int i = list->length - 1; i >= elem ; i--) {
// list->head[i + 1] = list->head[i];
// }
list->head[list->length] = elem;//元素插入空出的位置
list->length++;//表长度+1
// return *list;
}
/**
* 删除指定位置的数据
* @param list
* @param index
* @return 1成功删除,0index不合法或者是超出范围
*/
int seqListDelete(SeqList *list, int index){
//删除位置判断,取值范围为0~length-1
if (index >= list->length || index< 0) {
printf("删除位置有误\n");
return 1;}
//将删除位置后续元素依次前移
for (int i = index ; i < list->length - 1 ; i++) {
list->head[i] = list->head[i + 1];
}
list->length--;//表长度-1
return 1;
}
/**
* 删除第一个遇到的元素,注意后续的元素依次前移,并且修改length
* @param list
* @param elem
* @return 1成功删除,0元素没有查找到
*/
int seqListDeleteElem(SeqList *list, int elem){
if (elem >= list->length || elem< 0) {
printf("没有查找到\n");
// return 1;
}
//将删除位置后续元素依次前移
for (int i = 0 ; i < list->length - 1 ; i++)
{list->head[i] = list->head[i + 1];}
list->length--;//表长度-1
return 1;
}
/**
* 将数据倒序
* @param list
*/
void seqListRevert(SeqList *list){
for(int i=0;i<list->length/2;i++){
int temp=*list->head;
list->head[i]=list->head[list->length-i];
list->head[list->length-i]=temp;
// list->head++;
}
}
/**
* 向指定位置插入数据,后面的数据后移,如果插入的位置超过最大位置,则提示插入失败,返回0
* @param list
* @param index
* @param elem
* @return 插入成功返回1,失败返回0
*/
int seqListInsert(SeqList *list, int index, int elem){
//插入位置判断,取值范围为0~length
if (elem > list->length || elem < 0) {
printf("插入位置有误\n");
return 1;}
//重新分配内存
if (list->length == list->capacity) {
int *temp = (int *)realloc(list->head, (list->capacity + 1) * sizeof(int));
if (!temp) {
printf("插入失败\n");
}
list->head = temp;
list->capacity += 1;
return 1;
}
//插入位置及以后的元素依次后移一位
for (int i = list->length - 1; i >= elem ; i--) {
list->head[i + 1] = list->head[i];
}
list->head[elem] = index;//元素插入空出的位置
list->length++;//表长度+1
return 1;
}
/**
* 更新指定位置的数据
* @param list
* @param index
* @param elem
* @return 更新成功返回1,传入的index不合法返回0
*/
int seqListUpdate(SeqList *list, int index, int elem){
int pos = seqListGet(list, index);
list->head[pos] = elem;
return 1;
}
/**
* 查询指定位置的数字
* @param list
* @param index
* @return index不合法返回0
*/
int seqListGet(SeqList *list, int index)
{ //顺序查找
for (int i = 0; i < list->length; i++) {
if (list->head[i] == index) {
return i;
}
}
return 1;
}
// int main(void) {
// SeqList seqList = seqListCreateDirect();
// for (int i = 0; i < 5; i++) {
// *list->head = i + 1;
// list->length++;
// list->head++;
// }
// }
<file_sep>/ch02/example/doublyIntListDemo.c
//#include "doublyIntNode.h"
int main(void) {
// DoublyIntNode *node = doublyIntNodeCreate();
// doublyIntNodeAdd(node,10);
// doublyIntNodeAdd(node,2);
// doublyIntNodeAdd(node,4);
// doublyIntNodeAdd(node,3);
// doublyIntNodeAdd(node,6);
// doublyIntNodeDisplay(node);
// doublyIntNodeInsert(node, 2, 25);
//
// doublyIntNodeDisplay(node);
// doublyIntNodeInsert(node, 6, 25);
// doublyIntNodeDisplay(node);
//
//
// doublyIntNodeDestroy(node);
}<file_sep>/ch02/example/singlyIntListDemo.c
#include "singlyIntNode.h"
int main(void) {
SinglyIntNode *node = singlyIntNodeCreate();
singlyIntNodeAdd(node, 10);
singlyIntNodeAdd(node, 2);
singlyIntNodeAdd(node, 4);
singlyIntNodeAdd(node, 3);
singlyIntNodeAdd(node, 6);
// singlyIntNodeDisplay(node);
// singlyIntNodeInsert(node, 2, 25);
singlyIntNodeDisplay(node);
singlyIntNodeInsert(node, 4, 100);
singlyIntNodeDisplay(node);
singlyIntNodeDestroy(node);
node = NULL;
}
<file_sep>/family/CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(family C)
set(CMAKE_C_STANDARD 11)
add_executable(family
family.c
)
<file_sep>/ch01/example/main.c
//
// Created by 李熠 on 2019/10/8.
//
#include "seqlist.h"
#define SIZE 5
#define ADDNUM 9
#define ADDPOS 3
#define DELPOS 3
#define SEARCHNUM 4
#define MODIFYNUM 27
//int *getIntList() {
// int a = 5;
// return &a;
//}
// int main(void) {
// SeqList *seqList = seqListCreate();
// seqListAdd(seqList, 14);
// seqListAdd(seqList, 20);
// seqListAdd(seqList, 15);
// seqListAdd(seqList, 11);
// seqListAdd(seqList, 13);
// seqListAdd(seqList, 11);
// seqListAdd(seqList, 12);
// seqListAdd(seqList, 13);
// seqListAdd(seqList, 16);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListAdd(seqList, 124);
// seqListDisplay(seqList);
// seqListDestroy(seqList);}
int main(void) {
SeqList *seqlist = seqListCreate();
for (int i = 0; i < SIZE; i++) {
seqlist->head[i] = i + 1;
seqlist->length++;
}
printf("顺序表中存储的元素分别是:\n");
seqListDisplay(seqlist);
printf("在顺序表的末尾插入元素:%d\n", ADDPOS);
seqListAdd(seqlist, ADDPOS);
seqListDisplay(seqlist);
printf("删除第%d个元素\n", DELPOS);
seqListDelete(seqlist, 3);
seqListDisplay(seqlist);
printf("删除第一个元素\n");
seqListDeleteElem(seqlist, 1);
seqListDisplay(seqlist);
printf("数据倒序\n");
seqListRevert(seqlist);
seqListDisplay(seqlist);
printf("在顺序表的第%d位插入元素%d\n", 2, 323);
seqListInsert(seqlist, 323, 2);
seqListDisplay(seqlist);
printf("将%d更新为%d\n", 323, 23);
seqListUpdate(seqlist, 323, 23);
seqListDisplay(seqlist);
printf("查找元素为%d的位置\n", 23);
int pos=seqListGet(seqlist,23);
printf("元素%d的位置为第%d个\n", 23, pos);
printf("内存空间为%d 数组长度为%d\n", seqlist->capacity, seqlist->length);
free(seqlist->head);
seqlist->head = NULL;
return 0;
}
// int *p = getIntList();
// printf("%d\n", *p);
// *p = 10;
// printf("*p = %d\n", *p);
// printf("p = %p\n", p);
// int *p2 = getIntList();
// printf("*p2 = %d\n", *p2);
// printf("p2 = %p\n", p2);
// *p2 = 15;
// printf("*p = %d\n", *p);
// printf("p = %p\n", p);
// printf("*p2 = %d\n", *p2);
// printf("p2 = %p\n", p2);
// printf("*p = %d\n", *p);
// printf("p = %p\n", p);
<file_sep>/ch03/example/stack.c
//
// Created by 李熠 on 2019/10/10.
//
#include "stack.h"
/**
* 返回位于栈顶的元素,并在堆栈中删除它
* @param list
* @return 栈顶的元素
*/
int seqStackPop(SeqList *list) {
int rlt = seqListGet(list, list->length - 1);
seqListDelete(list, list->length - 1);
return rlt;
}
int seqStackPush(SeqList *list, int elem) {
seqListAdd(list, elem);
return elem;
}
int seqStackIsEmpty(SeqList *list) {
return list->length == 0;
}
int seqStackPeek(SeqList *list) {
return seqListGet(list, list->length - 1);
}
int seqStackSearch(SeqList *list, int elem) {
int j = 0;
for (int i = 0;
i < list->
length;
i++) {
if (list->head[i] == elem) {
j = i;
return
i;
}
}
if (j == 0) {
return -1;
}
}
int linkedStackPush(SinglyIntNode *list, int elem) {
singlyIntNodeAdd(list, elem);
return elem;
}
int linkedStackPop(SinglyIntNode *list){
int i=singlyIntNodeGet(list,list->value-1);
singlyIntNodeDelete(list,list->value-1);
return i;
}
int linkedStackSearch(SinglyIntNode *list, int elem){
SinglyIntNode*del=list;
int j=0;
for(int i=0;i<list->value;i++) {
del = del->next;
if (del->value == elem) {
return i;
}
}
if(j==0)
return 0;
}
int linkedStackPeek(SinglyIntNode *list){
return singlyIntNodeGet(list,list->value-1);
}
int linkedStackIsEmpty(SinglyIntNode *list){
return (list->value==0);
}<file_sep>/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/DependInfo.cmake
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"C"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
"/Users/edz/project/data-structure/ch01/examples/seqlist.c" "/Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/Users/edz/project/data-structure/ch01/examples/seqlist.c.o"
"/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c" "/Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/Users/edz/project/data-structure/ch02/examples/singlyIntNode.c.o"
"/Users/edz/project/data-structure/ch03/example/stack.c" "/Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/stack.c.o"
"/Users/edz/project/data-structure/ch03/example/stackDemo.c" "/Users/edz/project/data-structure/ch03/example/cmake-build-debug/CMakeFiles/stack.dir/stackDemo.c.o"
)
set(CMAKE_C_COMPILER_ID "AppleClang")
# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
"../."
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
|
39c8d7fb6bab75171ea4f040d79a65312ac92a5c
|
[
"Makefile",
"C",
"CMake"
] | 14
|
CMake
|
zyfgfg/data-structure
|
e64ec7aa7269f1e067626701d56e1a15580e9e48
|
b269b548a5a5acb82648e04d1d4283c64987a76f
|
refs/heads/master
|
<file_sep>#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
template <typename T>
struct Node
{
T data;
Node <T>* next;
};
template <typename T>
class LinkedList
{
private:
Node<T> * start;
Node<T> * end;
void del();
public:
LinkedList();
LinkedList(LinkedList const&);
void add(T);
bool remove (int);
void print();
bool isEmpty();
bool getItem(int,T&);
~LinkedList();
LinkedList& operator= (LinkedList const&);
};
#endif // LINKEDLIST_H_INCLUDED
<file_sep>//
// Wheel.h
// TestMonday
//
// Created by <NAME> on 3/23/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef __TestMonday__Wheel__
#define __TestMonday__Wheel__
#include <iostream>
using namespace std;
class Wheel {
int size;//cannot be accessed from outside
string model;
static int n;
public:
Wheel();
Wheel(int);
Wheel(string, int);
void printWheel();
int getSize()const;
string getModel()const;
static int getN();
friend bool operator< (const Wheel&, const Wheel&);
Wheel& operator= (const Wheel&);
friend ostream& operator<< (ostream&, const Wheel&);
~Wheel();
};
#endif /* defined(__TestMonday__Wheel__) */
<file_sep>//
// Dashboard.h
// TestMonday
//
// Created by 101 Dalmatians on 4/6/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef __TestMonday__Dashboard__
#define __TestMonday__Dashboard__
#include <iostream>
class Dashboard {
bool engineLight;
bool checkOil;
int speedGauge;
int rpmGauge;
bool isMetric;
int gear;
char* style;
public:
Dashboard();
Dashboard(const Dashboard&);
~Dashboard();
Dashboard& operator= (const Dashboard&);
Dashboard& setGear(int);
Dashboard& setSpeed(int);
Dashboard& setRpm(int);
Dashboard& printDashboard();
};
#endif /* defined(__TestMonday__Dashboard__) */
<file_sep>//
// ElasticStack.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/30/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include "ElasticStack.h"
ElasticStack::ElasticStack() {
init = new Node();
current = init;
}
bool ElasticStack::empty() const{
if((current->empty()) && (current->previousNode == 0))
return true;
return false;
}
int& ElasticStack::top() {
return current->getVal();
}
void ElasticStack::pop() {
if(!this->empty()) {
if (current->empty()) {
Node* temp = current;
current = current->previousNode;
delete temp;
current->pop();
} else {
current->pop();
}
}
}
void ElasticStack::push(const int& val) {
if(current->full()) {
Node* temp = new Node();
temp->previousNode = current;
current->nextNode = temp;
current = temp;
}
current->push(val);
}<file_sep>//
// Wheel.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/23/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include "Wheel.h"
using namespace std;
Wheel::Wheel():model("default"), size(19) {
}
Wheel::Wheel(int wheelSize) : model("default"), size(wheelSize) {
}
Wheel::Wheel(string wheelModel, int wheelSize): size(wheelSize) {
model = wheelModel;
}
int Wheel::getSize()const {
return size;
}
string Wheel::getModel()const {
return model;
}
void Wheel::printWheel() {
cout<<size<<" "<<model<<endl;
}
bool operator<(const Wheel& a, const Wheel& b) {
return a.getSize() < b.getSize();
}
Wheel& Wheel::operator= (const Wheel& param) {
cout<<"INFO: Assignment operator called.";
size = param.size;
model = param.model;
return *this;
}
int Wheel::n = 0;
int Wheel::getN() {
return n;
}
ostream& operator<< ( ostream& stream, const Wheel& wheel){
stream<<wheel.getModel()<<'#'<<wheel.getSize()<<'\n';
return stream;
}
Wheel::~Wheel() {
}<file_sep>//
// main.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/23/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include "Wheel.h"
#include "Node.h"
#include "ElasticStack.h"
#include "Dashboard.h"
int main(int argc, const char * argv[])
{
/*
pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:
*/
int * foo;
foo = new int [5]; // if allocation fails, an exception is thrown(bad_alloc exception)
Dashboard* dashboard = new Dashboard;
Dashboard* combo = new Dashboard[5];
/*
In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer). Therefore, foo now points to a valid block of memory with space for five elements of type int. The first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent).
There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of memory using new. The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run, whereas the dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.
The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, there are no guarantees that all requests to allocate memory using operator new are going to be granted by the system.
*/
int * bar;
bar = new (nothrow) int [5];
if (bar == nullptr) {
// error assigning memory. Take measures.
}
delete dashboard;
delete[] combo;
/*The first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new and a size in brackets ([]).
The value passed as argument to delete shall be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
*/
Dashboard board = *(new Dashboard());
board.printDashboard().setGear(5).printDashboard();
Dashboard baz;
Dashboard qux (baz); // object initialization: copy constructor called
Dashboard quux = baz; // object initialization: copy constructor called
baz = qux;
Dashboard copy = Dashboard(baz);
/*
A static member function does not have a this pointer.
The type of the this pointer for a member function of a class type X, is X* const. If the member function is declared with the const qualifier, the type of the this pointer for that member function for class X, is const X* const.
*/
return 0;
}
<file_sep>#include <iostream>
#include "SettingsManager.h"
using namespace std;
int main (int argc, char * const argv[]) {
SettingsManager *sm = SettingsManager::Instance();
cout <<std::boolalpha<< sm->isFullscreenOn()<<endl;
(*sm).toggleFullscreen();
cout << sm->isFullscreenOn();
return 0;
}
<file_sep>//
// ElasticStack.h
// TestMonday
//
// Created by <NAME> on 3/30/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef __TestMonday__ElasticStack__
#define __TestMonday__ElasticStack__
#include "Node.h"
#include <iostream>
class ElasticStack {
Node* init;
Node* current;
public:
ElasticStack();
bool empty() const;
int& top();
void pop();
void push(const int& val);
};
#endif /* defined(__TestMonday__ElasticStack__) */
<file_sep>//
// MyContainer.h
// TestMonday
//
// Created by 101 Dalmatians on 4/14/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef TestMonday_MyContainer_h
#define TestMonday_MyContainer_h
// template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T getElement() {return element;}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
#endif
<file_sep>//
// Dashboard.cpp
// TestMonday
//
// Created by 101 Dalmatians on 4/6/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include "Dashboard.h"
using namespace std;
Dashboard::Dashboard() {
this->engineLight = false;
this->checkOil = false;
this->speedGauge = 0;
this->rpmGauge = 1100;
this->isMetric = false;
this->gear = 0;
this->style = new char[5];
strcpy(this->style, "aero");
}
Dashboard& Dashboard::setGear(int g){
this->gear = g;
return *this;
}
Dashboard& Dashboard::setSpeed(int g){
this->speedGauge = g;
return *this;
}
Dashboard& Dashboard::setRpm(int g){
this->rpmGauge = g;
return *this;
}
Dashboard& Dashboard::printDashboard(){
cout<<"engineLight:\t\t\t"<<boolalpha<<engineLight<<endl;
cout<<"checkOil:\t\t\t"<<checkOil<<endl;
cout<<"speed:\t\t\t"<<speedGauge<<" kM/h"<<endl;
cout<<"rpm:\t\t\t"<<rpmGauge<<" rpm"<<endl;
cout<<"gear:\t\t\t"<<gear<<endl;
cout<<"style:\t\t\t"<<style<<endl;
return *this;
}
Dashboard::~Dashboard() {
delete [] style;
}
Dashboard::Dashboard(const Dashboard& mould): engineLight(mould.engineLight), checkOil(mould.checkOil), speedGauge(mould.speedGauge), rpmGauge(mould.rpmGauge), gear(mould.gear) {
style = new char[strlen(mould.style)+1];
strcpy(style, mould.style);
}
Dashboard& Dashboard::operator= (const Dashboard& x) {
delete [] style; // delete currently pointed string
style = new char[strlen(x.style)+1];
strcpy(style, x.style);
engineLight = x.engineLight;
checkOil = x.checkOil;
speedGauge = x.speedGauge;
rpmGauge = x.rpmGauge;
gear = x.gear;
return *this;
}<file_sep>#ifndef COLOR_H_INCLUDED
#define COLOR_H_INCLUDED
class Color {
private:
int red;
int green;
int blue;
public:
~Color();
Color(int = 0, int = 0, int = 0);
void setRed(int);
void setGreen(int);
void setBlue(int);
int getRed() const;
int getGreen() const;
int getBlue() const;
};
#endif // COLOR_H_INCLUDED
<file_sep>//
// MyPair.h
// TestMonday
//
// Created by <NAME> on 4/13/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef __TestMonday__MyPair__
#define __TestMonday__MyPair__
#include <iostream>
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
T getKey() const {
return values[0];
}
T getValue() const {
return values[1];
}
};
#endif /* defined(__TestMonday__MyPair__) */
<file_sep>//
// main.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/23/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include "Wheel.h"
int main(int argc, const char * argv[])
{
Wheel one(22);
Wheel* twoPtr = new Wheel(19);
Wheel two = *twoPtr;
Wheel defaultWheel = Wheel();
std::cout << "Hello, World!\n";
one.printWheel();
twoPtr->printWheel();
two.printWheel();
defaultWheel.printWheel();
cout<<boolalpha<<(two<one)<<endl;
cout<<(one<two)<<endl;
one = two;
cout<<one.getSize()<<two.getSize()<<endl;
Wheel dummyWheel;
cout<<dummyWheel.getN()<<endl;
std::cout<<two;
return 0;
}
<file_sep>//
// Node.h
// TestMonday
//
// Created by <NAME> on 3/30/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef __TestMonday__Node__
#define __TestMonday__Node__
#define CONTAINER_SIZE 10
#include <iostream>
class Node {
int cellContainer[CONTAINER_SIZE];
int currentIndex;
public:
Node* previousNode;
Node* nextNode;
bool empty();
bool full();
bool push(const int& val);
bool pop();
int& getVal();
void printNode();
Node();
};
#endif /* defined(__TestMonday__Node__) */
<file_sep>//
// Utility.h
// TestMonday
//
// Created by 101 Dalmatians on 4/14/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef TestMonday_Utility_h
#define TestMonday_Utility_h
class Utility {
public:
template <class SomeType>
static SomeType sum (SomeType a, SomeType b)
{
return a+b;
}
template <class T, int N>
static T fixed_multiply (T val)
{
return val * N;
}
};
#endif
<file_sep>//
// Node.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/30/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node() {
previousNode = 0;
nextNode = 0;
currentIndex = -1;
}
bool Node::empty() {
return (currentIndex==-1) ? true : false;
}
bool Node::full() {
return (currentIndex>=CONTAINER_SIZE) ? true : false;
}
bool Node::push(const int& val){
if (this->full())
return false;
else {
cellContainer[++currentIndex] = val;
return true;
}
}
bool Node::pop() {
if(this->empty()) {
return false;
}
else {
currentIndex--;
return true;
}
}
int& Node:: getVal() {
return cellContainer[currentIndex];
}
void Node::printNode() {
for(int i = 0; i < CONTAINER_SIZE; i++) {
cout << cellContainer[i]<<" ";
}
cout<<endl;
}<file_sep>#include <iostream>
#include "Car.h"
#include "Color.h"
#include "Driver.h"
int main() {
Color* green = new Color(0, 200, 0);
Car* c = new Car("Mazda", 300, 2, 12, green);
Driver* me = new Driver("Rosen", 0.0, 0, c);
std::cout<<"Driver: "<<me->getName()<<std::endl;
std::cout<<"Vehicle: "<<c->getModel()<<" "<<c->getTopSpeed()<<" "<<c->getAcceleration()<<std::endl;
std::cout<<"Color (RGB): "<<c->getColor()->getRed()<<" "<<c->getColor()->getGreen()<<" "<<c->getColor()->getBlue()<<std::endl;
return 0;
}
<file_sep>#include "Driver.h"
#include <cstring>
#include <iostream>
Driver::Driver(char* _name, double _rating,
int _level, Car* _vehicle) : name(NULL),
rating(_rating),
level(_level),
vehicle(_vehicle)
{
setName(_name);
}
Driver::~Driver() {
std::cout<<"Driver destroyed!"<<std::endl;
delete[] name;
}
char* Driver::getName() const {
return name;
}
double Driver::getRating() const {
return rating;
}
int Driver::getLevel() const {
return level;
}
Car* Driver::getVehicle() const {
return vehicle;
}
void Driver::setName(char* value) {
if(name != NULL) {
delete[] name;
}
name = new char[sizeof(value)/sizeof(char)];
strcpy(name, value);
}
void Driver::setRating(double value) {
rating = value;
}
void Driver::setLevel(int value) {
level = value;
}
void Driver::setVehicle(Car* value) {
vehicle = value;
}
<file_sep>Racing
======
assets for educational purposes
<file_sep>//
// YourPair.h
// TestMonday
//
// Created by <NAME> on 4/13/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#ifndef TestMonday_YourPair_h
#define TestMonday_YourPair_h
template <typename T, typename U>
class yourpair {
T key;
U value;
public:
yourpair() {
}
yourpair (T first, U second) {
key = first;
value = second;
}
T getKey() {
return key;
}
U getValue() {
return value;
}
};
#endif
<file_sep>/*
* SettingsManager.h
* Racing
*
* Created by <NAME> on 3/9/14.
* Copyright 2014 __MyCompanyName__. All rights reserved.
*
*/
class SettingsManager {
public:
static SettingsManager* Instance();
void toggleFullscreen();
bool isFullscreenOn();
protected:
SettingsManager();
private:
static SettingsManager* _instance;
bool isFullscreen;
};<file_sep>#include "LinkedList.h"
#include <iostream>
using namespace std;
// <NAME>. На едно място дава segmentation fault (пипа се чужда памет),
// трябва да бъде оправена. Ще има бонус за човека, който я оправи.
template <typename T>
LinkedList <T>:: LinkedList()
{
start = end = NULL;
}
template <typename T>
LinkedList <T>:: LinkedList (LinkedList const& a)
{
*this = a;
}
template<typename T>
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> const& l)
{
if(!isEmpty())
{
del();
}
start = new Node<T>;
Node <T>* iterator = l.getStart();
while (iterator != NULL)
{
add(iterator->data);
iterator = iterator-> next;
}
return *this;
}
template <typename T>
void LinkedList<T>:: add (T _data)
{
if (!isEmpty())
{
Node<T>* temp = new Node<T>;
temp-> data = _data;
temp-> next = NULL;
end -> next = temp;
end = temp;
}
else
{
start = new Node<T>;
start-> data = _data;
start-> next = NULL;
end = start;
}
}
template <typename T>
bool LinkedList <T>:: isEmpty()
{
return start==NULL;
}
template <typename T>
bool LinkedList <T>:: remove (int index)
{
Node<T>* iter= start;
if (isEmpty()) return false;
for (int i = 0; i< index-1 ; i++)
{
if(iter -> next == NULL)
{
return false;
}
else
{
iter = iter -> next;
}
}
Node<T>* temp = iter -> next;
iter -> next = temp -> next;
delete temp;
return true;
}
template <typename T>
void LinkedList <T>:: print()
{
Node<T>* iter = start;
while(iter != NULL)
{
cout << iter -> data << " ";
iter = iter->next;
}
cout << endl;
}
template <typename T>
bool LinkedList <T>:: getItem (int index , T& result)
{
if(isEmpty())
return false;
Node<T>* iter = start;
for(int i=0; i<index; i++)
{
if(iter->next = NULL)
{
return false;
}
iter = iter->next;
}
result = iter->data;
return true;
}
// da se dovurshi
template <typename T>
LinkedList <T>:: ~LinkedList ()
{
del();
}
template<typename T>
void LinkedList<T>::del()
{
Node<T>* temp=start;
Node<T>* next=start->next;
while(temp!=NULL)
{
delete temp;
temp = next;
if(next != NULL)
next = next->next;
}
}
<file_sep>/*
* SettingsManager.cpp
* Racing
*
* Created by <NAME> on 3/9/14.
* Copyright 2014 __MyCompanyName__. All rights reserved.
*
*/
#include "SettingsManager.h"
SettingsManager* SettingsManager::_instance = 0;
bool isFullscreen = false;
SettingsManager* SettingsManager::Instance () {
if (_instance == 0) {
_instance = new SettingsManager;
}
return _instance;
}
SettingsManager::SettingsManager() {
}
void SettingsManager::toggleFullscreen() {
isFullscreen = isFullscreen ? false : true;
}
bool SettingsManager::isFullscreenOn() {
return isFullscreen;
}<file_sep>//
// main.cpp
// TestMonday
//
// Created by 101 Dalmatians on 3/23/14.
// Copyright (c) 2014 101 Dalmatians. All rights reserved.
//
#include <iostream>
#include <vector>
#include "MyPair.h"
#include "YourPair.h"
#include "Tuple.h"
#include "MyContainer.h"
#include "Utility.h"
using namespace std;
int main(int argc, const char * argv[])
{
mypair<int> myobject (115, 36);
mypair<double> myfloats (3.0, 2.18);
cout<<myobject.getKey()<<" ";
cout<<myobject.getValue()<<endl;
yourpair<long, string> * person = new yourpair<long,string>(80539, "<NAME>");
cout<<person->getKey()<<" "<<person->getValue()<<endl;
cout <<endl;
Tuple<int, int, int> tuple(1,2,3);
cout<<tuple.getA()<<endl;
cout<<tuple.getB()<<endl;
cout<<tuple.getC()<<endl;
Tuple<int, string, double> info(23, "Simeon", 0.5);
cout<<info.getA()<<endl;
cout<<info.getB()<<endl;
cout<<info.getC()<<endl;
mycontainer<int> myint (7);
mycontainer<char> mychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
Utility* ptr;
cout<<ptr->sum(1,2)<<endl;
cout<<ptr->sum(2.5,4.1)<<endl;
cout<<ptr->sum(string("My car is "), string("red."))<<endl;
cout << ptr->fixed_multiply<int,2>(10) << '\n';
cout << ptr->fixed_multiply<int,3>(10) << '\n';
mycontainer<int> b = myint;
try {
if(strcmp(typeid (b.getElement()).name(), "i")==0) {
//throw 2;
}
//throw string("pesho");
throw 3.5;
} catch(int n) {
cout << "Integer thrown: " << n << endl;
} catch (char param) { cout << "char exception"; }
catch (string param) { cout << "string" << param; }
catch(...) {
cout<<"Default handler";
}
return 0;
}
<file_sep>#include "Color.h"
#include <iostream>
Color::Color(int r, int g, int b) : red(r), green(g), blue(b) { }
Color::~Color() {
std::cout<<"Color destroyed!"<<std::endl;
}
void Color::setRed(int value) {
red = value;
}
void Color::setGreen(int value) {
green = value;
}
void Color::setBlue(int value) {
blue = value;
}
int Color::getRed() const {
return red;
}
int Color::getGreen() const {
return green;
}
int Color::getBlue() const {
return blue;
}
<file_sep>#ifndef CAR_H_INCLUDED
#define CAR_H_INCLUDED
#include <string>
#include <cstring>
#include "Color.h"
class Car {
private:
char* model;
int top_speed;
int acceleration;
int stability;
Color* color;
public:
~Car();
Car(char* = NULL, int = 0, int = 0, int = 0, Color* = NULL);
char* getModel() const;
int getTopSpeed() const;
int getAcceleration() const;
int getStability() const;
Color* getColor() const;
void setModel(char*);
void setTopSpeed(int);
void setAcceleration(int);
void setStability(int);
void setColor(Color*);
};
class Builder
{
public:
virtual char* getCurrentModel() = 0;
virtual int getCurrentTopSpeed() = 0;
virtual int getCurrentAcceleration() = 0;
virtual int getCurrentStability() = 0;
virtual Color* getCurrentColor() = 0;
};
class Director
{
Builder* builder;
public:
void setBuilder(Builder* newBuilder);
Car* getCar();
};
class MitsubishiEvo9Builder : public Builder {
public:
virtual char* getCurrentModel();
virtual int getCurrentTopSpeed();
virtual int getCurrentStability();
virtual int getCurrentAcceleration();
virtual Color* getCurrentColor();
MitsubishiEvo9Builder();
};
#endif // CAR_H_INCLUDED
<file_sep>#ifndef DRIVER_H_INCLUDED
#define DRIVER_H_INCLUDED
#include "Car.h"
class Driver {
private:
char* name;
double rating;
int level;
Car* vehicle;
public:
Driver(char* = NULL, double = 0.0, int = 0, Car* = NULL);
~Driver();
char* getName() const;
double getRating() const;
int getLevel() const;
Car* getVehicle() const;
void setName(char*);
void setRating(double);
void setLevel(int);
void setVehicle(Car*);
};
#endif // DRIVER_H_INCLUDED
<file_sep>#include "Car.h"
#include <cstring>
#include <iostream>
Car::~Car() {
std::cout<<"Car destroyed!"<<std::endl;
delete[] model;
}
Car::Car(char* _model, int _top_speed,
int _acceleration, int _stability, Color* _color) : model(NULL),
top_speed(_top_speed),
acceleration(_acceleration),
stability(_stability),
color(_color)
{
setModel(_model);
}
char* Car::getModel() const {
return model;
}
int Car::getTopSpeed() const {
return top_speed;
}
int Car::getAcceleration() const {
return acceleration;
}
int Car::getStability() const {
return stability;
}
Color* Car::getColor() const {
return color;
}
void Car::setModel(char* value) {
if(model != NULL) {
delete[] model;
}
model = new char[sizeof(value)/sizeof(char)];
strcpy(model, value);
}
void Car::setTopSpeed(int value) {
top_speed = value;
}
void Car::setAcceleration(int value) {
acceleration = value;
}
void Car::setStability(int value) {
stability = value;
}
void Car::setColor(Color* value) {
color = value;
}
void Director::setBuilder(Builder* newBuilder)
{
builder = newBuilder;
}
Car* Director::getCar()
{
Car* car = new Car(builder->getCurrentModel(), builder->getCurrentTopSpeed(), builder->getCurrentAcceleration(), builder->getCurrentStability(), builder->getCurrentColor());
return car;
}
MitsubishiEvo9Builder::MitsubishiEvo9Builder() {
}
char* MitsubishiEvo9Builder::getCurrentModel() {
return "Mitsubishi";
}
int MitsubishiEvo9Builder::getCurrentTopSpeed() {
return 300;
}
int MitsubishiEvo9Builder::getCurrentStability() {
return 5;
}
int MitsubishiEvo9Builder::getCurrentAcceleration() {
return 4;
}
Color* MitsubishiEvo9Builder::getCurrentColor() {
return new Color(125,125,125);
}
|
f3616f4c67c53dc28f1950af8e9075f92f19e580
|
[
"Markdown",
"C++"
] | 28
|
C++
|
simeonbonev/Racing
|
9c8e67f0d428582fc18fe0ff06efd53745da1255
|
18a0777bbbb4c18297500c2ae5eed12a0d81b8e7
|
refs/heads/main
|
<repo_name>shirleyzj16/app<file_sep>/src/main/java/com/tuto/testgithub/MainActivity.java
package com.tuto.testgithub;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn_msj;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_msj = findViewById(R.id.btn_msj);
btn_msj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Funciona suuuuuper",Toast.LENGTH_SHORT).show();
}
});
}//fin del onCreate
}//fin de la clase
|
9e2ce396aa4bb4944576343418088672793aa438
|
[
"Java"
] | 1
|
Java
|
shirleyzj16/app
|
c4e508081f3c36148a1f59c729c74a06c1985054
|
6177edb59f88a8a0d92a0054b254a64b319e32a1
|
refs/heads/master
|
<repo_name>Shreya0123/Pro-45<file_sep>/Buttons.js
class Buttons{
constructor() {
//this.va = createSprite();
//this.va.position(100,200);
//this.va.addImage("va",buttonImg);
this.va = createButton('VOICE ASSISTANT');
this.pic = createButton('TAKE A PIC!');
this.overallWG = createButton('TIPS TO MANAGE OVERALL WASTE GENERATION');
this.specificWM = createButton('TIPS TO REDUCE A SPECIFIC WASTE MATERIAL');
//this.other = createInput("");
/*this.twoThreeKg = createButton('2-3 kg');
this.fourFiveKg = createButton('4-5 kg');
this.sixSevenKg = createButton('6-7 kg');*/
/*this.greeting = createElement('h2');
this.title = createElement('h2');
this.reset = createButton('Reset');*/
}
hide(){
this.va.hide();
this.pic.hide();
this.overallWG.hide();
this.specificWM.hide();
}
changeColor() {
//va.style.backgroundColor = "green";
}
display(){
this.va.position(60,200);
this.pic.position(60,300);
this.overallWG.position(60,400);
this.specificWM.position(60,500);
this.va.mousePressed(()=>{
//this.va.changeColor();
this.va.hide();
this.pic.hide();
this.overallWG.hide();
this.specificWM.hide();
textSize(25);
//fill("turqouise")
this.speak = createButton('Press to speak!');
this.speak.position(130,500);
this.back = createButton('Go to Home Page');
this.back.position(30,650);
this.back.mousePressed(()=>{
this.speak.hide();
this.back.hide();
this.va = createButton('VOICE ASSISTANT');
this.pic = createButton('TAKE A PIC!');
this.overallWG = createButton('TIPS TO MANAGE OVERALL WASTE GENERATION');
this.specificWM = createButton('TIPS TO REDUCE A SPECIFIC WASTE MATERIAL');
});
this.speak.mousePressed(()=>{
/*var talk = new p5.Speech(); // speech synthesis object
talk.speak('How can I help you?'); // say something
talk = new p5.SpeechRec(); // speech recognition object (will prompt for mic access)
talk.onResult = showResult; // bind callback function to trigger when speech is recognized
talk.start(); // start listening*/
/*function showResult()
{
console.log(talk.resultString);// log the result
}*/
}
);
});
this.pic.mousePressed(()=>{
this.va.hide();
this.pic.hide();
this.overallWG.hide();
this.specificWM.hide();
this.takeAPic = createElement('h3');
this.takeAPic.position(130,500);
this.takeAPic.html("Take a pic!");
/* textSize(25);
text("TAKE A PIC!",130,500);*/
this.back = createButton('Go to Home Page');
this.back.position(30,650);
this.back.mousePressed(()=>{
this.takeAPic.hide();
this.back.hide();
this.va = createButton('VOICE ASSISTANT');
this.pic = createButton('TAKE A PIC!');
this.overallWG = createButton('TIPS TO MANAGE OVERALL WASTE GENERATION');
this.specificWM = createButton('TIPS TO REDUCE A SPECIFIC WASTE MATERIAL');
});
});
this.overallWG.mousePressed(()=>{
this.va.hide();
this.pic.hide();
this.overallWG.hide();
this.specificWM.hide();
textSize(16);
/*text("How much waste do you generate per day",100,100);
text("2-3 kg",100, 250);
text("4-5 kg",100,350);
text("6-7 kg",100,450);*/
//text("Other: ",100,550);
this.other = createInput("Other");
//this.other.size(250);
this.twoThreeKg = createButton('2-3 kg');
this.fourFiveKg = createButton('4-5 kg');
this.sixSevenKg = createButton('6-7 kg');
this.twoThreeKg.position(100,250);
this.fourFiveKg.position(100,350);
this.sixSevenKg.position(100,450);
this.other.position(100,550);
this.twoThreeKg.mousePressed(()=>{
this.twoThreeKg.hide();
this.fourFiveKg.hide();
this.sixSevenKg.hide();
this.other.hide();
text("2-3 kg! That is very good!",50,120);
text("Here are some tips to reduce that :",50,140);
this.reduce1 = createButton('Reduce');
//this.reduce1.color = "green";
this.reuse1 = createButton('Reuse');
this.recycle1 = createButton('Recycle');
this.reduce1.position(50,180);
this.reuse1.position(50,220);
this.recycle1.position(50,260);
this.reduce1.mousePressed(()=>{
this.reduce1.hide();
this.reuse1.hide();
this.recycle1.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.reuse1.mousePressed(()=>{
this.reduce1.hide();
this.reuse1.hide();
this.recycle1.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.recycle1.mousePressed(()=>{
this.reduce1.hide();
this.reuse1.hide();
this.recycle1.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
});
this.fourFiveKg.mousePressed(()=>{
this.twoThreeKg.hide();
this.fourFiveKg.hide();
this.sixSevenKg.hide();
this.other.hide();
text("4-5 kg! You can do better!",50,120);
text("Here are some tips to reduce that :",50,140);
this.reduce2 = createButton('Reduce');
this.reuse2 = createButton('Reuse');
this.recycle2 = createButton('Recycle');
this.reduce2.position(50,180);
this.reuse2.position(50,220);
this.recycle2.position(50,260);
this.reduce2.mousePressed(()=>{
this.reduce2.hide();
this.reuse2.hide();
this.recycle2.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.reuse2.mousePressed(()=>{
this.reduce2.hide();
this.reuse2.hide();
this.recycle2.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.recycle2.mousePressed(()=>{
this.reduce2.hide();
this.reuse2.hide();
this.recycle2.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
});
this.sixSevenKg.mousePressed(()=>{
this.twoThreeKg.hide();
this.fourFiveKg.hide();
this.sixSevenKg.hide();
this.other.hide();
text("6-7 kg! That is very hazardous!",50,120);
text("Here are some tips to reduce that :",50,140);
this.reduce3 = createButton('Reduce');
this.reuse3 = createButton('Reuse');
this.recycle3 = createButton('Recycle');
this.reduce3.position(50,180);
this.reuse3.position(50,220);
this.recycle3.position(50,260);
this.reduce3.mousePressed(()=>{
this.reduce3.hide();
this.reuse3.hide();
this.recycle3.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.reuse3.mousePressed(()=>{
this.reduce3.hide();
this.reuse3.hide();
this.recycle3.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
this.recycle3.mousePressed(()=>{
this.reduce3.hide();
this.reuse3.hide();
this.recycle3.hide();
text("1)........",50, 200);
text("2)............",50,230);
text("3).......",50,260);
});
});
});
this.specificWM.mousePressed(()=>{
this.va.hide();
this.pic.hide();
this.overallWG.hide();
this.specificWM.hide();
this.search = createInput("");
this.search.position(35,120);
this.search.size(320);
this.back = createButton('Go to Home Page');
this.back.position(30,650);
this.back.mousePressed(()=>{
this.search.hide();
this.back.hide();
this.va = createButton('VOICE ASSISTANT');
this.pic = createButton('TAKE A PIC!');
this.overallWG = createButton('TIPS TO MANAGE OVERALL WASTE GENERATION');
this.specificWM = createButton('TIPS TO REDUCE A SPECIFIC WASTE MATERIAL');
});
});
}
}
|
0e28213ca026b9d9b7dc16e81a68f385aa8c527f
|
[
"JavaScript"
] | 1
|
JavaScript
|
Shreya0123/Pro-45
|
0f0122ad5b301ea1b9ee92d1f51ae802695d02d9
|
428a2012472bd0eddca812b4886b88829b0d0f12
|
refs/heads/master
|
<repo_name>Nielk1/bz1-geo-editor<file_sep>/BZ1GeoEditor/Geo.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace BZ1GeoEditor
{
public class GeoHeader
{
// note it is very important that this flags remain unchanged
public const long _GOURAUD_SHADED = 0x001;
public const long _TILED_BITMAP = 0x002;
public const long _TEXTURE_MAP = 0x004;
public const long _PARALLEL = 0x008;
public const long _TRUE_PERSPECTIVE = 0x010;
public const long _WIRE_FRAME = 0x020;
public const long _TRANSPARENT_PIXELS = 0x040;
public const long _ONE_THIRD_TRANSLUCENT_PIXELS = 0x080;
// Special Cases and specials flags
public const long _PROJECT_POLYGON_ONLY = 0x100;
// Composit
public const long _ALPHA_BLEND = (_TRANSPARENT_PIXELS | _ONE_THIRD_TRANSLUCENT_PIXELS);
public const long _TWO_THIRD_TRANSLUCENT_PIXELS = (_WIRE_FRAME | _ONE_THIRD_TRANSLUCENT_PIXELS);
public const long _FLAT_PERSPECTIVE_MAP = (0xff & (~(_PARALLEL | _GOURAUD_SHADED | _TILED_BITMAP)));
public const long _FLAT_TILED_PERSPECTIVE_MAP = (0xff & (~(_PARALLEL | _GOURAUD_SHADED)));
public const long _HALLOW_WIRE_FRAME = (0xff & (~(_PARALLEL | _TRUE_PERSPECTIVE | _TEXTURE_MAP)));
public long Tag; // '.GEO' File tag
public long cksum; // File checksum
public char[] Name; // Object name
public long NumVerts; // Number of vertices in object
public long NumPolys; // Number of faces in object
public long Flags; // Object Flags
public bool Flags_GOURAUD_SHADED
{
get { return (Flags & _GOURAUD_SHADED) == _GOURAUD_SHADED; }
set { Flags = value ? (long)(Flags | _GOURAUD_SHADED) : (long)(Flags & ~_GOURAUD_SHADED); }
}
public bool Flags_TILED_BITMAP
{
get { return (Flags & _TILED_BITMAP) == _TILED_BITMAP; }
set { Flags = value ? (long)(Flags | _TILED_BITMAP) : (long)(Flags & ~_TILED_BITMAP); }
}
public bool Flags_TEXTURE_MAP
{
get { return (Flags & _TEXTURE_MAP) == _TEXTURE_MAP; }
set { Flags = value ? (long)(Flags | _TEXTURE_MAP) : (long)(Flags & ~_TEXTURE_MAP); }
}
public bool Flags_PARALLEL
{
get { return (Flags & _PARALLEL) == _PARALLEL; }
set { Flags = value ? (long)(Flags | _PARALLEL) : (long)(Flags & ~_PARALLEL); }
}
public bool Flags_TRUE_PERSPECTIVE
{
get { return (Flags & _TRUE_PERSPECTIVE) == _TRUE_PERSPECTIVE; }
set { Flags = value ? (long)(Flags | _TRUE_PERSPECTIVE) : (long)(Flags & ~_TRUE_PERSPECTIVE); }
}
public bool Flags_WIRE_FRAME
{
get { return (Flags & _WIRE_FRAME) == _WIRE_FRAME; }
set { Flags = value ? (long)(Flags | _WIRE_FRAME) : (long)(Flags & ~_WIRE_FRAME); }
}
public bool Flags_TRANSPARENT_PIXELS
{
get { return (Flags & _TRANSPARENT_PIXELS) == _TRANSPARENT_PIXELS; }
set { Flags = value ? (long)(Flags | _TRANSPARENT_PIXELS) : (long)(Flags & ~_TRANSPARENT_PIXELS); }
}
public bool Flags_ONE_THIRD_TRANSLUCENT_PIXELS
{
get { return (Flags & _ONE_THIRD_TRANSLUCENT_PIXELS) == _ONE_THIRD_TRANSLUCENT_PIXELS; }
set { Flags = value ? (long)(Flags | _ONE_THIRD_TRANSLUCENT_PIXELS) : (long)(Flags & ~_ONE_THIRD_TRANSLUCENT_PIXELS); }
}
public bool Flags_PROJECT_POLYGON_ONLY
{
get { return (Flags & _PROJECT_POLYGON_ONLY) == _PROJECT_POLYGON_ONLY; }
set { Flags = value ? (long)(Flags | _PROJECT_POLYGON_ONLY) : (long)(Flags & ~_PROJECT_POLYGON_ONLY); }
}
public bool Flags_Composit_ALPHA_BLEND
{
get { return (Flags & _ALPHA_BLEND) == _ALPHA_BLEND; }
set { Flags = value ? (long)(Flags | _ALPHA_BLEND) : (long)(Flags & ~_ALPHA_BLEND); }
}
public bool Flags_Composit_TWO_THIRD_TRANSLUCENT_PIXELS
{
get { return (Flags & _TWO_THIRD_TRANSLUCENT_PIXELS) == _TWO_THIRD_TRANSLUCENT_PIXELS; }
set { Flags = value ? (long)(Flags | _TWO_THIRD_TRANSLUCENT_PIXELS) : (long)(Flags & ~_TWO_THIRD_TRANSLUCENT_PIXELS); }
}
public bool Flags_Composit_FLAT_PERSPECTIVE_MAP
{
get { return (Flags & _FLAT_PERSPECTIVE_MAP) == _FLAT_PERSPECTIVE_MAP; }
set { Flags = value ? (long)(Flags | _FLAT_PERSPECTIVE_MAP) : (long)(Flags & ~_FLAT_PERSPECTIVE_MAP); }
}
public bool Flags_Composit_FLAT_TILED_PERSPECTIVE_MAP
{
get { return (Flags & _FLAT_TILED_PERSPECTIVE_MAP) == _FLAT_TILED_PERSPECTIVE_MAP; }
set { Flags = value ? (long)(Flags | _FLAT_TILED_PERSPECTIVE_MAP) : (long)(Flags & ~_FLAT_TILED_PERSPECTIVE_MAP); }
}
public bool Flags_Composit_HALLOW_WIRE_FRAME
{
get { return (Flags & _HALLOW_WIRE_FRAME) == _HALLOW_WIRE_FRAME; }
set { Flags = value ? (long)(Flags | _HALLOW_WIRE_FRAME) : (long)(Flags & ~_HALLOW_WIRE_FRAME); }
}
public string Name_STR
{
get { return new string(Name).TrimEnd('\0'); }
set
{
Array.Clear(Name, 0, Name.Length);
value.Substring(0, Math.Min(value.Length, 16)).ToArray().CopyTo(Name, 0);
}
}
public GeoHeader()
{
Tag = 0x2E47454F;
Name = new char[16];
}
public GeoHeader(BinaryReader reader)
{
Tag = Utility.ReadInt32(reader);
cksum = Utility.ReadInt32(reader);
Name = reader.ReadChars(16);
NumVerts = Utility.ReadInt32(reader);
NumPolys = Utility.ReadInt32(reader);
Flags = Utility.ReadInt32(reader);
}
internal void Save(BinaryWriter writer)
{
Utility.Write(writer, Tag);
Utility.Write(writer, cksum);
writer.Write(Name, 0, 16);
Utility.Write(writer, NumVerts);
Utility.Write(writer, NumPolys);
Utility.Write(writer, Flags);
}
};
public struct Vector3D
{
public float x; // x, y, and z components of a 3D vector
public float y;
public float z;
public Vector3D(BinaryReader reader)
{
x = Utility.ReadSingle(reader);
y = Utility.ReadSingle(reader);
z = Utility.ReadSingle(reader);
}
public void Save(BinaryWriter writer)
{
Utility.Write(writer, x);
Utility.Write(writer, y);
Utility.Write(writer, z);
}
};
public struct ColorRGB
{
public byte r, g, b; // Red/Green/Blue values of color
public ColorRGB(BinaryReader reader)
{
r = reader.ReadByte();
g = reader.ReadByte();
b = reader.ReadByte();
}
public void Save(BinaryWriter writer)
{
writer.Write(r);
writer.Write(g);
writer.Write(b);
}
};
public struct GeoCollisionInfo
{
public Vector3D GeoCenter; // Geometric Center of Object
public float SphereRadius; // Bounding Sphere Radius
public float BoxHalfHeightX; // Bounding Box X Axis
public float BoxHalfHeightY; // Bounding Box Y Axis
public float BoxHalfHeightZ; // Bounding Box Z Axis
};
public struct FaceNode
{
public long VertexId; // Index into vertex list
public long VertexNormalId; // Index into vertex normal list
public float u, v; // Textmap u, v coordinates
public FaceNode(BinaryReader reader)
{
VertexId = Utility.ReadInt32(reader);
VertexNormalId = Utility.ReadInt32(reader);
u = Utility.ReadSingle(reader);
v = Utility.ReadSingle(reader);
}
public void Save(BinaryWriter writer)
{
Utility.Write(writer, VertexId);
Utility.Write(writer, VertexNormalId);
Utility.Write(writer, u);
Utility.Write(writer, v);
}
};
public struct SurfacePlane
{
public Vector3D SurfaceNormal; // Unit vector of surface normal
public float Distance; // Shortest distance from the origin to a point
// on the plane perpendicular to the surface normal
public SurfacePlane(BinaryReader reader)
{
SurfaceNormal = new Vector3D(reader);
Distance = reader.ReadSingle();
}
public void Save(BinaryWriter writer)
{
SurfaceNormal.Save(writer);
Utility.Write(writer, Distance);
}
};
public class Face
{
// values in Face ShadeType
public const byte GEO_WIREFRAME = 1;
public const byte GEO_SOLID_WIREFRAME = 2;
public const byte GEO_CONSTANT_SHADED = 3;
public const byte GEO_FLAT_SHADED = 4;
public const byte GEO_GOUROUD_SHADED = 5;
// values in Face TextureType
public const byte GEO_TRUE_PERSPECTIVE = 0x01;
public const byte GEO_TILED_TEXTUREMAP = 0x02;
public const byte GEO_XPARENT_TEXTMAP = 0x04;
// values in Face XluscentType
public const byte GEO_NO_XLUSCENCY = 0;
public const byte GEO_ONE_THIRD_XLUSCENCY = 1;
public const byte GEO_TWO_THIRD_XLUSCENCY = 2;
// values in Face TreeBranch
public const bool BACK = false;
public const bool FRONT = true;
public long Index; // Index of this face
public long VertexCount; // Number of vertices in face
public ColorRGB Color; // Color of the face
public SurfacePlane Plane; // Surface normal
public float PolyArea; // Surface area of the polygon
public byte ShadeType; // Poly shade type (constant, flat, gouroud)
public byte TextureType; // Poly texturemap type (afine, true perspective, tiled, xparent)
public byte XluscentType; // Transluscency type (0%, 33%, 66%)
public char[] TextureName; // pointer to a texture to be applied to the
public long ParentFace; // Index into face list of BSP parent
public bool TreeBranch; // Face is front/back branch in BSP tree
public FaceNode[] Wireframe; // List of vertices in face
public bool TextureType_TRUE_PERSPECTIVE
{
get { return (TextureType & GEO_TRUE_PERSPECTIVE) == GEO_TRUE_PERSPECTIVE; }
set { TextureType = value ? (byte)(TextureType | GEO_TRUE_PERSPECTIVE) : (byte)(TextureType & ~GEO_TRUE_PERSPECTIVE); }
}
public bool TextureType_TILED_TEXTUREMAP
{
get { return (TextureType & GEO_TILED_TEXTUREMAP) == GEO_TILED_TEXTUREMAP; }
set { TextureType = value ? (byte)(TextureType | GEO_TILED_TEXTUREMAP) : (byte)(TextureType & ~GEO_TILED_TEXTUREMAP); }
}
public bool TextureType_XPARENT_TEXTMAP
{
get { return (TextureType & GEO_XPARENT_TEXTMAP) == GEO_XPARENT_TEXTMAP; }
set { TextureType = value ? (byte)(TextureType | GEO_XPARENT_TEXTMAP) : (byte)(TextureType & ~GEO_XPARENT_TEXTMAP); }
}
public string TextureName_STR {
get { return new string(TextureName).TrimEnd('\0'); }
set
{
Array.Clear(TextureName, 0, TextureName.Length);
value.Substring(0, Math.Min(value.Length, 13)).ToArray().CopyTo(TextureName, 0);
}
}
public static bool TryRead(BinaryReader reader, out Face fc)
{
fc = null;
try
{
if (reader.BaseStream.Length - reader.BaseStream.Position <= 0) return false;
Face tmp = new Face();
tmp.Index = Utility.ReadInt32(reader);
tmp.VertexCount = Utility.ReadInt32(reader);
tmp.Color = new ColorRGB(reader);
tmp.Plane = new SurfacePlane(reader);
tmp.PolyArea = Utility.ReadSingle(reader);
tmp.ShadeType = reader.ReadByte();
tmp.TextureType = reader.ReadByte();
tmp.XluscentType = reader.ReadByte();
tmp.TextureName = reader.ReadChars(13);
tmp.ParentFace = Utility.ReadInt32(reader);
tmp.TreeBranch = Utility.ReadInt32(reader) == 1;
tmp.Wireframe = new FaceNode[tmp.VertexCount];
for (int x = 0; x < tmp.Wireframe.Length; x++)
{
tmp.Wireframe[x] = new FaceNode(reader);
}
fc = tmp;
return true;
}
catch (EndOfStreamException) { }
return false;
}
public void Save(BinaryWriter writer)
{
Utility.Write(writer, Index);
Utility.Write(writer, VertexCount);
Color.Save(writer);
Plane.Save(writer);
Utility.Write(writer, PolyArea);
writer.Write(ShadeType);
writer.Write(TextureType);
writer.Write(XluscentType);
writer.Write(TextureName, 0, 13);
Utility.Write(writer, ParentFace);
Utility.Write(writer, TreeBranch ? 1 : 0);
for (int x = 0; x < Wireframe.Length; x++)
{
Wireframe[x].Save(writer);
}
}
};
public class Geo
{
public GeoHeader header;
public Vector3D[] vecs;
public Vector3D[] vecnorms;
public List<Face> faces;
public Geo(BinaryReader reader)
{
header = new GeoHeader(reader);
vecs = new Vector3D[header.NumVerts];
vecnorms = new Vector3D[header.NumVerts];
faces = new List<Face>();
for (int x = 0; x < vecs.Length; x++)
{
vecs[x] = new Vector3D(reader);
}
for (int x = 0; x < vecnorms.Length; x++)
{
vecnorms[x] = new Vector3D(reader);
}
Face fc = null;
while(Face.TryRead(reader, out fc))
{
faces.Add(fc);
}
}
public void Save(string path)
{
using (FileStream stream = File.Open(path, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
header.Save(writer);
for (int x = 0; x < vecs.Length; x++)
{
vecs[x].Save(writer);
}
for (int x = 0; x < vecnorms.Length; x++)
{
vecnorms[x].Save(writer);
}
faces.ForEach(fc =>
{
fc.Save(writer);
});
}
}
}
}
class Utility
{
public static float ReadSingle(BinaryReader reader)
{
byte[] arr = reader.ReadBytes(4);
if (arr.Length == 0) throw new EndOfStreamException();
if (BitConverter.IsLittleEndian) arr.Reverse();
return BitConverter.ToSingle(arr, 0);
}
public static Int64 ReadInt32(BinaryReader reader)
{
byte[] arr = reader.ReadBytes(4);
if (arr.Length == 0) throw new EndOfStreamException();
if (BitConverter.IsLittleEndian) arr.Reverse();
return BitConverter.ToInt32(arr, 0);
}
public static void Write(BinaryWriter writer, float val)
{
byte[] arr = BitConverter.GetBytes(val);
if (BitConverter.IsLittleEndian) arr.Reverse();
writer.Write(arr, 0, 4);
}
public static void Write(BinaryWriter writer, Int64 val)
{
byte[] arr = BitConverter.GetBytes(val);
if (BitConverter.IsLittleEndian) arr.Reverse();
writer.Write(arr, 0, 4);
}
}
}
<file_sep>/README.md
# bz1-geo-editor
Battlezone 1 (PC) GEO Editor
Version 0.0.3.1 Binary (pre compiled for Windows x86)
http://nielk1.com/Battlezone/BZ1GEOEditor/BZ1GEOEditor.0.0.3.1.7z
Version 0.0.3.0 Binary (pre compiled for Windows x86)
http://nielk1.com/Battlezone/BZ1GEOEditor/BZ1GEOEditor.0.0.3.0.7z
Version 0.0.2.0 Binary (pre compiled for Windows x86)
http://nielk1.com/Battlezone/BZ1GEOEditor/BZ1GEOEditor.0.0.2.0.7z
Version 0.0.1.1 Binary (pre compiled for Windows x86)
http://nielk1.com/Battlezone/BZ1GEOEditor/BZ1GEOEditor.0.0.1.1.7z
<file_sep>/BZ1GeoEditor/AddTextureDialog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BZ1GeoEditor
{
public partial class AddTextureDialog : Form
{
public string Value { get; private set; }
public AddTextureDialog()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Value = textBox1.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
<file_sep>/BZ1GeoEditor/SharpGLForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharpGL;
using System.IO;
using System.Drawing.Imaging;
namespace BZ1GeoEditor
{
/// <summary>
/// The main form class.
/// </summary>
public partial class SharpGLForm : Form
{
/// <summary>
/// Initializes a new instance of the <see cref="SharpGLForm"/> class.
/// </summary>
public SharpGLForm()
{
InitializeComponent();
using(Graphics g = Graphics.FromImage(DummyTexture))
{
g.FillRectangle(new SolidBrush(Color.White), 0, 0, DummyTexture.Width, DummyTexture.Height);
}
pbPallet.SizeMode = PictureBoxSizeMode.StretchImage;
//pbPallet.ha
if (!File.Exists("information.txt")) File.WriteAllText("information.txt", "Please note that given the high level of access this tool gives to GEO format headers and face data, arbitrary changes to GEO files are likely to cause crashes when loaded by the game. Do test all changes thoroughly and share what information you learn with the community.");
txtInformation.Text = File.ReadAllText("information.txt");
if (!File.Exists("notes.txt")) File.Create("notes.txt").Close();
txtNotes.Text = File.ReadAllText("notes.txt");
notesLoaded = true;
}
/// <summary>
/// Handles the OpenGLDraw event of the openGLControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RenderEventArgs"/> instance containing the event data.</param>
private void openGLControl_OpenGLDraw(object sender, RenderEventArgs e)
{
// Get the OpenGL object.
OpenGL gl = openGLControl.OpenGL;
// Clear the color and depth buffer.
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
// Load the identity matrix.
gl.LoadIdentity();
// Use the 'look at' helper function to position and aim the camera.
//gl.LookAt(0, 0, -10, 0, 0, 0, 0, 1, 0);
gl.LookAt(0, 0, -zoom, 0, 0, 0, 0, 1, 0);
// Rotate around X axis;
gl.Rotate(-pitch, 1.0f, 0.0f, 0.0f);
// Rotate around the Y axis.
gl.Rotate(rotation, 0.0f, 1.0f, 0.0f);
//gl.Translate(-transX, transY, 0);
//if (geo != null)
//{
// Draw a coloured pyramid.
//gl.Begin(OpenGL.GL_TRIANGLES);
if (geo != null)
{
float maxArea = curRenderStyle == RenderStyle.FaceArea ? geo.faces.Max(dr => dr.PolyArea) : 0.0f;
foreach (Face face in geo.faces)
{
bool HighlightColor = false;
//Color HighlightBrightness = Color.White;
if (tcTabs.SelectedTab == tpFaces && lstFaces.SelectedItem != null)
{
foreach (FaceListWrapper selectedItem in lstFaces.SelectedItems)
{
if (selectedItem.Value.Index == face.Index)
{
HighlightColor = true;
break;
}
}
}
if (tcTabs.SelectedTab == tpUV && lstFacesUV.SelectedItem != null)
{
foreach (FaceListWrapper selectedItem in lstFacesUV.SelectedItems)
{
if (selectedItem.Value.Index == face.Index)
{
HighlightColor = true;
break;
}
}
}
bool color = false;
bool frontback = false;
bool areacolor = false;
bool RENDER_NORM = cbNorms.Checked;
float DistanceMax = 0.0f;
bool RENDER_DISTANCE = false;
float treeRatio = 0.5f;
if (checkerBitmaps.ContainsKey(face.TextureName_STR))
{
gl.BindTexture(OpenGL.GL_TEXTURE_2D, checkerBitmaps[face.TextureName_STR].textureID);
}
else
{
Console.WriteLine("Failed to Bind Texture \"{0}\"", face.TextureName_STR);
}
gl.PolygonMode(OpenGL.GL_FRONT, OpenGL.GL_FILL);
gl.PolygonMode(OpenGL.GL_BACK, OpenGL.GL_LINE);
switch (curRenderStyle)
{
case RenderStyle.Special_Back_Front:
frontback = true;
break;
case RenderStyle.FaceArea:
areacolor = true;
break;
case RenderStyle.Distance:
RENDER_DISTANCE = true;
DistanceMax = geo.faces.Max(dr => dr.Plane.Distance);
break;
case RenderStyle.Wire:
gl.PolygonMode(OpenGL.GL_FRONT, OpenGL.GL_LINE);
break;
case RenderStyle.Solid:
break;
case RenderStyle.Color:
color = true;
break;
case RenderStyle.Checker:
break;
case RenderStyle.Texture:
break;
}
if (frontback)
{
//treeRatio = ((FaceBranchDict[face.Index] * 1.0f / FaceBranchMax) + 0.5f) / 2;
treeRatio = (FaceBranchDict[face.Index] + FaceBranchMax) / (FaceBranchMax * 2.0f);
}
if (HighlightColor)
{
gl.PolygonMode(OpenGL.GL_FRONT, OpenGL.GL_FILL);
//gl.Disable(OpenGL.GL_LIGHTING);
}
bool RENDER_FACE = true;
bool RENDER_WIRE = false;
bool RENDER_FLAT = false;
if (face.ShadeType == Face.GEO_WIREFRAME) { RENDER_FACE = false; RENDER_WIRE = true; }
if (face.ShadeType == Face.GEO_SOLID_WIREFRAME) { RENDER_WIRE = true; }
if (face.ShadeType == Face.GEO_CONSTANT_SHADED) { }
if (face.ShadeType == Face.GEO_FLAT_SHADED) { RENDER_FLAT = true; }
if (face.ShadeType == Face.GEO_GOUROUD_SHADED) { }
byte alpha = 0xff;
if (face.XluscentType == Face.GEO_ONE_THIRD_XLUSCENCY) alpha = 0xaa;
if (face.XluscentType == Face.GEO_TWO_THIRD_XLUSCENCY) alpha = 0x55;
if (RENDER_FACE)
{
if (RENDER_FLAT)
{
gl.ShadeModel(OpenGL.GL_FLAT);
}
if (RENDER_DISTANCE || frontback || areacolor)
{
gl.Disable(OpenGL.GL_LIGHTING);
}
gl.Begin(OpenGL.GL_TRIANGLES);
int off1 = 0;
int off2 = 1;
Vector3D v0 = geo.vecs[face.Wireframe[off1].VertexId];
Vector3D n0 = /*geo.vecnorms.Length > face.Wireframe[0] ?*/ geo.vecnorms[face.Wireframe[off1].VertexNormalId];// : DEFNORM;
float u10 = face.Wireframe[off1].u;//rootBlock.uvs.Count > face.Wireframe[0] ? rootBlock.uvs[face.Wireframe[0]] : DEFUV;
float u20 = face.Wireframe[off1].v;//rootBlock.uvs.Count > face.Wireframe[0] ? rootBlock.uvs[face.Wireframe[0]] : DEFUV;
//MSHModel.VertIndex state0 = rootBlock.vertToState[face.Wireframe[1]];
Vector3D v1 = geo.vecs[face.Wireframe[off2].VertexId];
Vector3D n1 = /*geo.vecnorms.Count > face.Wireframe[1] ?*/ geo.vecnorms[face.Wireframe[off2].VertexNormalId];// : DEFNORM;
float u11 = face.Wireframe[off2].u;//rootBlock.uvs.Count > face.Wireframe[1] ? rootBlock.uvs[face.Wireframe[1]] : DEFUV;
float u21 = face.Wireframe[off2].v;//rootBlock.uvs.Count > face.Wireframe[1] ? rootBlock.uvs[face.Wireframe[1]] : DEFUV;
//MSHModel.VertIndex state1 = rootBlock.vertToState[face.Wireframe[1]];
Color? area = null;
if (areacolor) { area = Lerp(Color.White, Color.Red, face.PolyArea / maxArea); }
Color? branch = null;
if (frontback) { branch = Lerp(Color.Red, Color.White, treeRatio); }
Color? distance = null;
if (RENDER_DISTANCE) { distance = Lerp(Color.Red, Color.White, face.Plane.Distance / DistanceMax); }
for (int vertId = 2; vertId < face.Wireframe.Length; vertId++)
{
Vector3D v2 = geo.vecs[face.Wireframe[vertId].VertexId];
Vector3D n2 = /*geo.vecnorms.Count > face.Wireframe[vertId] ?*/ geo.vecnorms[face.Wireframe[vertId].VertexNormalId];// : DEFNORM;
float u12 = face.Wireframe[vertId].u;//rootBlock.uvs.Count > face.Wireframe[vertId] ? rootBlock.uvs[face.Wireframe[vertId]];// : DEFUV;
float u22 = face.Wireframe[vertId].v;//rootBlock.uvs.Count > face.Wireframe[vertId] ? rootBlock.uvs[face.Wireframe[vertId]];// : DEFUV;
//MSHModel.VertIndex state2 = rootBlock.vertToState[face.Wireframe[vertId]];
if (area.HasValue) { gl.Color(area.Value.R, area.Value.G, area.Value.B, alpha); }
else if (distance.HasValue) { gl.Color(distance.Value.R, distance.Value.G, distance.Value.B, alpha); }
//else if (frontback) { if (face.TreeBranch == Face.FRONT) { gl.Color((byte)0xff, (byte)0x0, (byte)0x0, alpha); } else { gl.Color((byte)0x0, (byte)0x0, (byte)0xff, alpha); } }
else if (branch.HasValue) { gl.Color(branch.Value.R, branch.Value.G, branch.Value.B, alpha); }
else if (color) { gl.Color(face.Color.r, face.Color.g, face.Color.b, alpha); } else { gl.Color((byte)0xee, (byte)0xee, (byte)0xee, alpha); }
gl.TexCoord(u10, u20);
gl.Normal(n0.x, n0.y, -n0.z);
gl.Vertex(v0.x, v0.y, -v0.z);
if (area.HasValue) { gl.Color(area.Value.R, area.Value.G, area.Value.B, alpha); }
else if (distance.HasValue) { gl.Color(distance.Value.R, distance.Value.G, distance.Value.B, alpha); }
//else if (frontback) { if (face.TreeBranch == Face.FRONT) { gl.Color((byte)0xff, (byte)0x0, (byte)0x0, alpha); } else { gl.Color((byte)0x0, (byte)0x0, (byte)0xff, alpha); } }
else if (branch.HasValue) { gl.Color(branch.Value.R, branch.Value.G, branch.Value.B, alpha); }
else if (color) { gl.Color(face.Color.r, face.Color.g, face.Color.b, alpha); } else { gl.Color((byte)0xee, (byte)0xee, (byte)0xee, alpha); }
gl.TexCoord(u11, u21);
gl.Normal(n1.x, n1.y, -n1.z);
gl.Vertex(v1.x, v1.y, -v1.z);
if (area.HasValue) { gl.Color(area.Value.R, area.Value.G, area.Value.B, alpha); }
else if (distance.HasValue) { gl.Color(distance.Value.R, distance.Value.G, distance.Value.B, alpha); }
//else if (frontback) { if (face.TreeBranch == Face.FRONT) { gl.Color((byte)0xff, (byte)0x0, (byte)0x0, alpha); } else { gl.Color((byte)0x0, (byte)0x0, (byte)0xff, alpha); } }
else if (branch.HasValue) { gl.Color(branch.Value.R, branch.Value.G, branch.Value.B, alpha); }
else if (color) { gl.Color(face.Color.r, face.Color.g, face.Color.b, alpha); } else { gl.Color((byte)0xee, (byte)0xee, (byte)0xee, alpha); }
gl.TexCoord(u12, u22);
gl.Normal(n2.x, n2.y, -n2.z);
gl.Vertex(v2.x, v2.y, -v2.z);
v1 = v2;
n1 = n2;
u11 = u12;
u21 = u22;
//state1 = state2;
}
gl.End();
if (RENDER_DISTANCE || frontback || areacolor)
{
gl.Enable(OpenGL.GL_LIGHTING);
}
if (RENDER_FLAT)
{
gl.ShadeModel(OpenGL.GL_SMOOTH);
}
//if (HighlightColor)
//{
// gl.Enable(OpenGL.GL_LIGHTING);
//}
}
if (RENDER_WIRE)
{
gl.Begin(OpenGL.GL_LINES);
Vector3D lastV = geo.vecs[face.Wireframe.Last().VertexId];
Vector3D lastN = geo.vecnorms[face.Wireframe.Last().VertexNormalId];
float lastUU = face.Wireframe.Last().u;
float lastUV = face.Wireframe.Last().v;
for (int vertId = 0; vertId < face.Wireframe.Length; vertId++)
{
Vector3D curV = geo.vecs[face.Wireframe[vertId].VertexId];
Vector3D curN = geo.vecnorms[face.Wireframe[vertId].VertexNormalId];
float curUU = face.Wireframe[vertId].u;
float curUV = face.Wireframe[vertId].v;
gl.Color(face.Color.r, face.Color.g, face.Color.b);
gl.TexCoord(lastUU, lastUV);
gl.Normal(lastN.x, lastN.y, -lastN.z);
gl.Vertex(lastV.x, lastV.y, -lastV.z);
gl.TexCoord(curUU, curUV);
gl.Normal(curN.x, curN.y, -curN.z);
gl.Vertex(curV.x, curV.y, -curV.z);
lastV = curV;
lastN = curN;
lastUU = curUU;
lastUV = curUV;
}
gl.End();
}
if (RENDER_NORM)
{
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
for(int i = 0; i < face.Wireframe.Length; i++)
{
x += geo.vecs[face.Wireframe[i].VertexId].x;
y += geo.vecs[face.Wireframe[i].VertexId].y;
z += geo.vecs[face.Wireframe[i].VertexId].z;
}
x /= face.Wireframe.Length;
y /= face.Wireframe.Length;
z /= face.Wireframe.Length;
gl.LineWidth(1.0f);
gl.Disable(OpenGL.GL_TEXTURE_2D);
gl.Disable(OpenGL.GL_LIGHTING);
gl.Begin(OpenGL.GL_LINES);
gl.Color((byte)0xff, (byte)0x00, (byte)0x00, (byte)0xff);
gl.Vertex(x, y, -z);
gl.Vertex(x - face.Plane.SurfaceNormal.x * 0.5, y - face.Plane.SurfaceNormal.y * 0.5, -z + face.Plane.SurfaceNormal.z * 0.5);
gl.End();
gl.Enable(OpenGL.GL_TEXTURE_2D);
gl.Enable(OpenGL.GL_LIGHTING);
gl.LineWidth(1.0f);
}
if (HighlightColor)
{
gl.LineWidth(5.0f);
gl.Disable(OpenGL.GL_TEXTURE_2D);
gl.Disable(OpenGL.GL_LIGHTING);
gl.Begin(OpenGL.GL_LINES);
Vector3D last = geo.vecs[face.Wireframe.Last().VertexId];
for (int vertId = 0; vertId < face.Wireframe.Length; vertId++)
{
Vector3D cur = geo.vecs[face.Wireframe[vertId].VertexId];
gl.Color((byte)0xff, (byte)0x0, (byte)0x0);
gl.Vertex(last.x, last.y, -last.z);
gl.Vertex(cur.x, cur.y, -cur.z);
last = cur;
}
gl.End();
gl.LineWidth(1.0f);
gl.Enable(OpenGL.GL_TEXTURE_2D);
gl.Enable(OpenGL.GL_LIGHTING);
}
}
}
//gl.End();
}
/// <summary>
/// Handles the OpenGLInitialized event of the openGLControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void openGLControl_OpenGLInitialized(object sender, EventArgs e)
{
// TODO: Initialise OpenGL here.
// Get the OpenGL object.
OpenGL gl = openGLControl.OpenGL;
// Set the clear color.
gl.ClearColor(0.5f, 0.5f, 0.5f, 1.0f);
gl.Enable(OpenGL.GL_COLOR_MATERIAL);
gl.Enable(OpenGL.GL_TEXTURE_2D);
gl.Enable(OpenGL.GL_LIGHTING);
// alpha vertex colors
gl.Enable(OpenGL.GL_BLEND);
gl.BlendFunc(OpenGL.GL_SRC_ALPHA, OpenGL.GL_ONE_MINUS_SRC_ALPHA);
// 1 sided faces
//gl.Enable(OpenGL.GL_CULL_FACE);
gl.Enable(OpenGL.GL_LIGHT0);
gl.LightModel(OpenGL.GL_LIGHT_MODEL_AMBIENT, new float[] { 0.4f, 0.4f, 0.4f });
float[] light_position = { 0, -1, 0, 0 };
float[] light_brightness = { 1, 1, 1, 1 };
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_POSITION, light_position);
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_DIFFUSE, light_brightness);
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_SPECULAR, light_brightness);
}
/// <summary>
/// Handles the Resized event of the openGLControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void openGLControl_Resized(object sender, EventArgs e)
{
// TODO: Set the projection matrix here.
// Get the OpenGL object.
OpenGL gl = openGLControl.OpenGL;
// Set the projection matrix.
gl.MatrixMode(OpenGL.GL_PROJECTION);
// Load the identity.
gl.LoadIdentity();
// Create a perspective transformation.
gl.Perspective(60.0f, (double)openGLControl.Width / (double)openGLControl.Height, 0.01, 1000.0);
// Set the modelview matrix.
gl.MatrixMode(OpenGL.GL_MODELVIEW);
}
/// <summary>
/// The current rotation.
/// </summary>
private float rotation = 0.0f;
private float pitch = 0.0f;
private float transX = 0.0f;
private float transY = 0.0f;
private double zoom = 10;
private Geo geo;
private bool MouseLeftActive = false;
private bool MouseRightActive = false;
private int oldMouseX;
private int oldMouseY;
private Random rand = new Random();
private List<string> textureNames = new List<string>();
private Dictionary<string, TextureDataMap> checkerBitmaps = new Dictionary<string, TextureDataMap>();
//private Dictionary<string, TextureDataMap> textureBitmaps = new Dictionary<string, TextureDataMap>();
Bitmap DummyTexture = new Bitmap(256, 256);
uint[] DummyTextureID = new uint[1];
enum RenderStyle
{
Special_Back_Front,
FaceArea,
Distance,
Wire,
Solid,
Color,
Checker,
Texture
};
RenderStyle curRenderStyle = RenderStyle.Texture;
AboutBox1 aboutDialog = new AboutBox1();
bool DisableEvents = false;
bool notesLoaded = false;
Dictionary<long, int> FaceBranchDict = new Dictionary<long, int>();
int FaceBranchMax = 0;
private string path;
private class TextureDataMap
{
public Bitmap checker;
public uint[] _textureID;
public uint textureID { get { return _textureID[0]; } }
public MapFile map;
public Color[] pallet;
public TextureDataMap() { _textureID = new uint[1]; }
}
private class FaceListWrapper
{
private Face dr;
private string lineItem;
public Face Value { get { return dr; } }
public FaceListWrapper(Face dr, string lineItem)
{
this.dr = dr;
this.lineItem = lineItem;
}
public bool AddLine(int pos)
{
StringBuilder sb = new StringBuilder(lineItem);
if (sb[pos] == ' ')
{
sb[pos] = '│';
lineItem = sb.ToString();
return true;
}
else if (sb[pos] == '└')
{
sb[pos] = '├';
lineItem = sb.ToString();
return true;
}
return false;
}
public override string ToString()
{
return lineItem;
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
if (!e.Cancel)
{
saveFileDialog1.InitialDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
saveFileDialog1.FileName = Path.GetFileName(openFileDialog1.FileName);
saveFileDialog2.InitialDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
saveFileDialog2.FileName = Path.ChangeExtension(Path.GetFileName(openFileDialog1.FileName), "obj");
processFile(openFileDialog1.FileName);
}
}
private void processFile(string filename)
{
path = Path.GetDirectoryName(filename);
using (FileStream _FileStream = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream))
{
geo = new Geo(_BinaryReader);
//OpenGL gl = openGLControl.OpenGL;
//textures.ToList().ForEach(dr => gl.DeleteTextures(1, dr.Value._textureID));
//textures.Clear();
if (geo != null)
{
DisableEvents = true;
OpenGL gl = openGLControl.OpenGL;
checkerBitmaps.ToList().ForEach(dr => gl.DeleteTextures(1, dr.Value._textureID));
checkerBitmaps.Clear();
//textureBitmaps.ToList().ForEach(dr => gl.DeleteTextures(1, dr.Value._textureID));
//textureBitmaps.Clear();
float holdX = 0;
float holdY = 0;
float holdZ = 0;
for (int x = 0; x < geo.vecs.Length; x++)
{
holdX = Math.Max(holdX, Math.Abs(geo.vecs[x].x));
holdY = Math.Max(holdY, Math.Abs(geo.vecs[x].y));
holdZ = Math.Max(holdZ, Math.Abs(geo.vecs[x].z));
}
zoom = 2.0f * Math.Sqrt((holdX * holdX) + (holdY * holdY) + (holdZ * holdZ));
//if (DummyTexture == null)
//{
// DummyTexture = new TextureData() { checker = new Bitmap(256, 256) };
// //gl.BindTexture(OpenGL.GL_TEXTURE_2D, DummyTexture.textureID);
//}
textureNames.Clear();
geo.faces.ForEach(face =>
{
if (!textureNames.Contains(face.TextureName_STR)) textureNames.Add(face.TextureName_STR);
});
loadMAPToolStripMenuItem.DropDownItems.Clear();
clearMAPToolStripMenuItem.DropDownItems.Clear();
loadACTToolStripMenuItem.DropDownItems.Clear();
clearACTToolStripMenuItem.DropDownItems.Clear();
cbTexture.Items.Clear();
lbTextures.Items.Clear();
bool first = true;
textureNames.ForEach(name =>
{
AddTexture(name, !first);
first = false;
});
lbTextures.Enabled = true;
btnAddTexture.Enabled = true;
if (cbRender.SelectedIndex == -1)
{
cbRender.SelectedItem = "Texture";
curRenderStyle = RenderStyle.Texture;
}
cbRender.Enabled = true;
cbNorms.Enabled = true;
txtName.Text = geo.header.Name_STR;
txtName.Enabled = true;
FaceBranchDict.Clear();
FaceBranchMax = 0;
lstFaces.Items.Clear();
lstFacesUV.Items.Clear();
lstFaces.BeginUpdate();
lstFacesUV.BeginUpdate();
Stack<long> FaceIDs = new Stack<long>();
FaceIDs.Push(-1);
int index = 0;
geo.faces.ForEach(dr =>
{
while (FaceIDs.Peek() != dr.ParentFace) FaceIDs.Pop();
if (dr.ParentFace == -1)
{
FaceBranchDict[dr.Index] = 0;
}
else
{
int BranchVal = FaceBranchDict.ContainsKey(FaceIDs.Peek()) ? FaceBranchDict[FaceIDs.Peek()] : 0;
if (dr.TreeBranch) { FaceBranchDict[dr.Index] = BranchVal + 1; } else { FaceBranchDict[dr.Index] = BranchVal - 1; }
}
FaceIDs.Push(dr.Index);
int Depth = FaceIDs.Count() - 2;
string lineItem = string.Empty;
if (Depth > 1) lineItem += new string(' ', Depth - 1);
if (Depth > 0) lineItem += '└';
switch (dr.VertexCount)
{
case 3: lineItem += "TRI"; break;
case 4: lineItem += "QUAD"; break;
case 5: lineItem += "PENT"; break;
case 6: lineItem += "HEX"; break;
default: lineItem += dr.VertexCount.ToString(); break;
}
lineItem += string.Format(" ({0})", dr.Index);
if (lstFaces.Items.Count > 0)
{
if(Depth > 0)
{
int LineHunt = index - 1;
while (LineHunt > -1)
{
FaceListWrapper item = (FaceListWrapper)lstFaces.Items[LineHunt];
if (item.AddLine(Depth - 1))
{
lstFaces.Items[LineHunt] = item;
LineHunt--;
}else{
LineHunt = -1;
}
}
}
}
lstFaces.Items.Add(new FaceListWrapper(dr, lineItem));
index++;
});
lstFacesUV.Items.AddRange(lstFaces.Items);
lstFaces.EndUpdate();
lstFacesUV.EndUpdate();
lstFaces.Enabled = true;
lstFacesUV.Enabled = true;
FaceBranchMax = FaceBranchDict.Max(dr => Math.Abs(dr.Value));
/*{
treeView1.Nodes.Clear();
Dictionary<long, Tuple<TreeNode, Face>> FaceNodeList = new Dictionary<long, Tuple<TreeNode, Face>>();
geo.faces.ForEach(dr =>
{
TreeNode node = new TreeNode(dr.Index.ToString());
FaceNodeList.Add(dr.Index, new Tuple<TreeNode, Face>(node, dr));
});
FaceNodeList.ToList().ForEach(dr =>
{
if (dr.Value.Item2.ParentFace == -1)
{
treeView1.Nodes.Add(dr.Value.Item1);
}
else
{
FaceNodeList[dr.Value.Item2.ParentFace].Item1.Nodes.Add(dr.Value.Item1);
}
});
treeView1.ExpandAll();
treeView1.Enabled = true;
}*/
UpdateOGLTextureData();
DisableEvents = false;
setHeaderCheckboxes();
}
}
}
}
private void OpenMap_Click(object sender, EventArgs e)
{
openFileDialog2.FileName = ((ToolStripItem)sender).Text + ".map";
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
if (File.Exists(openFileDialog2.FileName))
{
TextureDataMap dat = checkerBitmaps[((ToolStripItem)sender).Text];
dat.map = MapFile.FromFile(openFileDialog2.FileName);
UpdateOGLTextureData();
}
}
}
private void ClearMap_Click(object sender, EventArgs e)
{
TextureDataMap dat = checkerBitmaps[((ToolStripItem)sender).Text];
dat.map = null;
UpdateOGLTextureData();
}
private void OpenAct_Click(object sender, EventArgs e)
{
openFileDialog3.FileName = "objects.act";
if (openFileDialog3.ShowDialog() == DialogResult.OK)
{
if (File.Exists(openFileDialog3.FileName))
{
TextureDataMap dat = checkerBitmaps[((ToolStripItem)sender).Text];
dat.pallet = MapFile.PalletFromFile(openFileDialog3.FileName);
UpdateOGLTextureData();
}
}
}
private void ClearAct_Click(object sender, EventArgs e)
{
TextureDataMap dat = checkerBitmaps[((ToolStripItem)sender).Text];
dat.pallet = null;
UpdateOGLTextureData();
}
private void UpdateOGLTextureData()
{
OpenGL gl = openGLControl.OpenGL;
//checkerBitmaps.ToList().ForEach(dr =>
//{
// //dr.Value.checker.UnlockBits();
// gl.DeleteTextures(1, dr.Value._textureID);
//});
checkerBitmaps.ToList().ForEach(dr =>
{
gl.GenTextures(1, dr.Value._textureID);
Bitmap datBitmap = null;
switch((string)cbRender.SelectedItem)
{
//case "Wire":
// break;
//case "Solid":
// break;
//case "Color":
// break;
case "Checker":
datBitmap = (Bitmap)dr.Value.checker.Clone();
break;
case "Texture":
if (dr.Value.map != null)
{
if (dr.Value.pallet != null && dr.Value.map.IsPalletized)
{
datBitmap = dr.Value.map.GetBitmap(dr.Value.pallet);
}
else
{
datBitmap = dr.Value.map.GetBitmap();
}
}
else
{
datBitmap = (Bitmap)DummyTexture.Clone();
}
break;
default:
datBitmap = (Bitmap)DummyTexture.Clone();
break;
}
gl.BindTexture(OpenGL.GL_TEXTURE_2D, dr.Value.textureID);
gl.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, /*OpenGL.GL_RGB16*/3, datBitmap.Width, datBitmap.Height, 0, OpenGL.GL_BGR, OpenGL.GL_UNSIGNED_BYTE,
datBitmap.LockBits(new System.Drawing.Rectangle(0, 0, datBitmap.Width, datBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb).Scan0);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
});
}
private Bitmap CreateCheckerBitmap(bool random = false)
{
const int colWidth = 16;
const int rowHeight = 16;
System.Drawing.Bitmap checks = new System.Drawing.Bitmap(
colWidth * 16, rowHeight * 16);
// The checkerboard consists of 10 rows and 10 columns.
// Each square in the checkerboard is 10 x 10 pixels.
// The nested for loops are used to calculate the position
// of each square on the bitmap surface, and to set the
// pixels to black or white.
// The two outer loops iterate through
// each square in the bitmap surface.
System.Drawing.Color B = System.Drawing.Color.Black;
System.Drawing.Color A = System.Drawing.Color.White;
if(random) B = System.Drawing.Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255));
for (int columns = 0; columns < 16; columns++)
{
for (int rows = 0; rows < 16; rows++)
{
// Determine whether the current sqaure
// should be black or white.
System.Drawing.Color color;
if (columns % 2 == 0)
color = rows % 2 == 0 ? B : A;
else
color = rows % 2 == 0 ? A : B;
// The two inner loops iterate through
// each pixel in an individual square.
for (int j = columns * colWidth; j < (columns * colWidth) +
colWidth; j++)
{
for (int k = rows * rowHeight; k < (rows * rowHeight) +
rowHeight; k++)
{
// Set the pixel to the correct color.
checks.SetPixel(j, k, color);
}
}
}
}
return checks;
}
private void openGLControl_MouseWheel(object sender, MouseEventArgs e)
{
zoom += (e.Delta * -0.005);
zoom = Math.Min(1000.0d, Math.Max(zoom, 0.00001d));
}
private void openGLControl_MouseMove(object sender, MouseEventArgs e)
{
if (MouseLeftActive)
{
if (e.Button == MouseButtons.Left)
{
rotation += ((e.X - oldMouseX) / (float)openGLControl.Width * 250f);
oldMouseX = e.X;
pitch += ((e.Y - oldMouseY) / (float)openGLControl.Height * 250f);
oldMouseY = e.Y;
}
else
{
MouseLeftActive = false;
}
}
if (MouseRightActive)
{
if (e.Button == MouseButtons.Right)
{
transX += ((e.X - oldMouseX) / (float)openGLControl.Width * 25f);
oldMouseX = e.X;
transY += ((e.Y - oldMouseY) / (float)openGLControl.Height * 25f);
oldMouseY = e.Y;
}
else
{
MouseRightActive = false;
}
}
}
private void openGLControl_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
oldMouseX = e.X;
oldMouseY = e.Y;
MouseLeftActive = true;
}
if (e.Button == MouseButtons.Right)
{
oldMouseX = e.X;
oldMouseY = e.Y;
MouseRightActive = true;
}
}
private void openGLControl_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
MouseLeftActive = false;
}
if (e.Button == MouseButtons.Right)
{
MouseRightActive = false;
}
}
private void btnBackgroundColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
// Get the OpenGL object.
OpenGL gl = openGLControl.OpenGL;
// Set the clear color.
gl.ClearColor(colorDialog1.Color.R / 255.0f, colorDialog1.Color.G / 255.0f, colorDialog1.Color.B / 255.0f, colorDialog1.Color.A / 255.0f);
btnBackgroundColor.BackColor = colorDialog1.Color;
}
}
private void cbRender_SelectedIndexChanged(object sender, EventArgs e)
{
switch ((string)cbRender.SelectedItem)
{
case "Special: TreeBranch":
curRenderStyle = RenderStyle.Special_Back_Front;
break;
case "Special: Area":
curRenderStyle = RenderStyle.FaceArea;
break;
case "Special: Distance":
curRenderStyle = RenderStyle.Distance;
break;
case "Wire":
curRenderStyle = RenderStyle.Wire;
break;
case "Solid":
curRenderStyle = RenderStyle.Solid;
break;
case "Color":
curRenderStyle = RenderStyle.Color;
break;
case "Checker":
curRenderStyle = RenderStyle.Checker;
break;
case "Texture":
curRenderStyle = RenderStyle.Texture;
break;
}
UpdateOGLTextureData();
}
private void txtName_TextChanged(object sender, EventArgs e)
{
if (geo != null)
{
geo.header.Name_STR = txtName.Text;
}
}
private Color Lerp(Color color1, Color color2, float amount)
{
const float bitmask = 65536.0f;
uint n = (uint)(Math.Round(Math.Max(Math.Min((amount * bitmask), bitmask), 0.0f)));
int r = ((int)(color1.R) + ((((int)(color2.R) - (int)(color1.R)) * (int)(n)) >> 16));
int g = ((int)(color1.G) + ((((int)(color2.G) - (int)(color1.G)) * (int)(n)) >> 16));
int b = ((int)(color1.B) + ((((int)(color2.B) - (int)(color1.B)) * (int)(n)) >> 16));
//int a = ((int)(color1.A) + ((((int)(color2.A) - (int)(color1.A)) * (int)(n)) >> 16));
return Color.FromArgb(/*a,*/ r, g, b);
}
private void lstFaces_SelectedIndexChanged(object sender, EventArgs e)
{
lblFaceCount.Text = lstFaces.SelectedItems.Count.ToString();
if (geo != null && lstFaces.SelectedIndex > -1)
{
DisableEvents = true;
Face face = ((FaceListWrapper)lstFaces.SelectedItem).Value;
byte? r = face.Color.r;
byte? g = face.Color.g;
byte? b = face.Color.b;
byte? ShadeType = face.ShadeType;
byte? XluscentType = face.XluscentType;
bool? TextureType_TRUE_PERSPECTIVE = face.TextureType_TRUE_PERSPECTIVE;
bool? TextureType_TILED_TEXTUREMAP = face.TextureType_TILED_TEXTUREMAP;
bool? TextureType_XPARENT_TEXTMAP = face.TextureType_XPARENT_TEXTMAP;
string TextureName = face.TextureName_STR;
foreach(FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
if (r.HasValue && r != faceWrapper.Value.Color.r) r = null;
if (r.HasValue && g != faceWrapper.Value.Color.g) g = null;
if (r.HasValue && b != faceWrapper.Value.Color.b) b = null;
if (ShadeType .HasValue && ShadeType != faceWrapper.Value.ShadeType ) ShadeType = null;
if (XluscentType.HasValue && XluscentType != faceWrapper.Value.XluscentType) XluscentType = null;
if (TextureType_TRUE_PERSPECTIVE.HasValue && TextureType_TRUE_PERSPECTIVE != faceWrapper.Value.TextureType_TRUE_PERSPECTIVE) TextureType_TRUE_PERSPECTIVE = null;
if (TextureType_TILED_TEXTUREMAP.HasValue && TextureType_TILED_TEXTUREMAP != faceWrapper.Value.TextureType_TILED_TEXTUREMAP) TextureType_TILED_TEXTUREMAP = null;
if (TextureType_XPARENT_TEXTMAP .HasValue && TextureType_XPARENT_TEXTMAP != faceWrapper.Value.TextureType_XPARENT_TEXTMAP ) TextureType_XPARENT_TEXTMAP = null;
if (TextureName != null && TextureName != faceWrapper.Value.TextureName_STR) TextureName = null;
}
cbPerspectiveSW.CheckState = CheckState.Unchecked;
cbTiled.CheckState = CheckState.Unchecked;
cbTextTransp.CheckState = CheckState.Unchecked;
if (r.HasValue && g.HasValue && b.HasValue) { btnFaceColor.BackColor = colorDialog1.Color = Color.FromArgb(r.Value, g.Value, b.Value); } else { btnFaceColor.BackColor = SystemColors.Control; colorDialog1.Color = Color.White; }
if (ShadeType.HasValue) { cbShadeType.SelectedIndex = ShadeType.Value - 1; } else { cbShadeType.SelectedIndex = -1; }
if (XluscentType.HasValue) { cbTransparent.SelectedIndex = XluscentType.Value; } else { cbTransparent.SelectedIndex = -1; }
if (TextureType_TRUE_PERSPECTIVE.HasValue) { cbPerspectiveSW.Checked = TextureType_TRUE_PERSPECTIVE.Value; } else { cbPerspectiveSW.CheckState = CheckState.Indeterminate; }
if (TextureType_TILED_TEXTUREMAP.HasValue) { cbTiled.Checked = TextureType_TILED_TEXTUREMAP.Value; } else { cbTiled.CheckState = CheckState.Indeterminate; }
if (TextureType_XPARENT_TEXTMAP.HasValue) { cbTextTransp.Checked = TextureType_XPARENT_TEXTMAP.Value; } else { cbTextTransp.CheckState = CheckState.Indeterminate; }
if (TextureName != null) { cbTexture.SelectedItem = TextureName; } else { cbTexture.SelectedIndex = -1; }
btnFaceColor.Enabled = true;
cbShadeType.Enabled = true;
cbTransparent.Enabled = true;
cbPerspectiveSW.Enabled = true;
cbTiled.Enabled = true;
cbTextTransp.Enabled = true;
cbTexture.Enabled = true;
DisableEvents = false;
}
else
{
DisableEvents = true;
btnFaceColor.Enabled = false;
cbShadeType.Enabled = false;
cbTransparent.Enabled = false;
cbPerspectiveSW.Enabled = false;
cbTiled.Enabled = false;
cbTextTransp.Enabled = false;
cbTexture.Enabled = false;
btnFaceColor.BackColor = SystemColors.Control;
colorDialog1.Color = Color.White;
cbShadeType.SelectedIndex = -1;
cbTransparent.SelectedIndex = -1;
cbPerspectiveSW.CheckState = CheckState.Indeterminate;
cbTiled.CheckState = CheckState.Indeterminate;
cbTextTransp.CheckState = CheckState.Indeterminate;
cbTexture.SelectedIndex = -1;
DisableEvents = false;
}
}
private void btnFaceColor_Click(object sender, EventArgs e)
{
if (geo != null && lstFaces.SelectedIndex > -1)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.Color.r = colorDialog1.Color.R;
face.Color.g = colorDialog1.Color.G;
face.Color.b = colorDialog1.Color.B;
}
btnFaceColor.BackColor = colorDialog1.Color;
}
}
}
private void cbShadeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.ShadeType = (byte)(cbShadeType.SelectedIndex + 1);
}
}
}
private void cbTransparent_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.XluscentType = (byte)cbTransparent.SelectedIndex;
}
}
}
private void cbTexture_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.TextureName_STR = (string)cbTexture.SelectedItem;
}
}
}
private void cbPerspectiveSW_CheckedChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.TextureType_TRUE_PERSPECTIVE = cbPerspectiveSW.Checked;
}
}
}
private void cbTiled_CheckedChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.TextureType_TILED_TEXTUREMAP = cbTiled.Checked;
}
}
}
private void cbTextTransp_CheckedChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lstFaces.SelectedIndex > -1)
{
foreach (FaceListWrapper faceWrapper in lstFaces.SelectedItems)
{
Face face = faceWrapper.Value;
face.TextureType_XPARENT_TEXTMAP = cbTextTransp.Checked;
}
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
aboutDialog.ShowDialog();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(geo != null)
{
saveFileDialog1.ShowDialog();
}
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
if (geo != null)
{
geo.Save(saveFileDialog1.FileName);
}
}
private void cbHeaderFlag_Check(object sender, EventArgs e)
{
if (!DisableEvents)
{
if (geo != null)
{
if (sender == cbHeaderFlag1) geo.header.Flags_GOURAUD_SHADED = cbHeaderFlag1.Checked;
if (sender == cbHeaderFlag2) geo.header.Flags_TILED_BITMAP = cbHeaderFlag2.Checked;
if (sender == cbHeaderFlag3) geo.header.Flags_TEXTURE_MAP = cbHeaderFlag3.Checked;
if (sender == cbHeaderFlag4) geo.header.Flags_PARALLEL = cbHeaderFlag4.Checked;
if (sender == cbHeaderFlag5) geo.header.Flags_TRUE_PERSPECTIVE = cbHeaderFlag5.Checked;
if (sender == cbHeaderFlag6) geo.header.Flags_WIRE_FRAME = cbHeaderFlag6.Checked;
if (sender == cbHeaderFlag7) geo.header.Flags_TRANSPARENT_PIXELS = cbHeaderFlag7.Checked;
if (sender == cbHeaderFlag8) geo.header.Flags_ONE_THIRD_TRANSLUCENT_PIXELS = cbHeaderFlag8.Checked;
if (sender == cbHeaderFlag9) geo.header.Flags_PROJECT_POLYGON_ONLY = cbHeaderFlag9.Checked;
if (sender == cbHeaderFlag10) geo.header.Flags_Composit_ALPHA_BLEND = cbHeaderFlag10.Checked;
if (sender == cbHeaderFlag11) geo.header.Flags_Composit_TWO_THIRD_TRANSLUCENT_PIXELS = cbHeaderFlag11.Checked;
if (sender == cbHeaderFlag12) geo.header.Flags_Composit_FLAT_PERSPECTIVE_MAP = cbHeaderFlag12.Checked;
if (sender == cbHeaderFlag13) geo.header.Flags_Composit_FLAT_TILED_PERSPECTIVE_MAP = cbHeaderFlag13.Checked;
if (sender == cbHeaderFlag14) geo.header.Flags_Composit_HALLOW_WIRE_FRAME = cbHeaderFlag14.Checked;
}
setHeaderCheckboxes();
}
}
private void setHeaderCheckboxes()
{
DisableEvents = true;
if (geo != null)
{
cbHeaderFlag1.CheckState = CheckState.Unchecked;
cbHeaderFlag2.CheckState = CheckState.Unchecked;
cbHeaderFlag3.CheckState = CheckState.Unchecked;
cbHeaderFlag4.CheckState = CheckState.Unchecked;
cbHeaderFlag5.CheckState = CheckState.Unchecked;
cbHeaderFlag6.CheckState = CheckState.Unchecked;
cbHeaderFlag7.CheckState = CheckState.Unchecked;
cbHeaderFlag8.CheckState = CheckState.Unchecked;
cbHeaderFlag9.CheckState = CheckState.Unchecked;
cbHeaderFlag10.CheckState = CheckState.Unchecked;
cbHeaderFlag11.CheckState = CheckState.Unchecked;
cbHeaderFlag12.CheckState = CheckState.Unchecked;
cbHeaderFlag13.CheckState = CheckState.Unchecked;
cbHeaderFlag14.CheckState = CheckState.Unchecked;
cbHeaderFlag1.Checked = geo.header.Flags_GOURAUD_SHADED;
cbHeaderFlag2.Checked = geo.header.Flags_TILED_BITMAP;
cbHeaderFlag3.Checked = geo.header.Flags_TEXTURE_MAP;
cbHeaderFlag4.Checked = geo.header.Flags_PARALLEL;
cbHeaderFlag5.Checked = geo.header.Flags_TRUE_PERSPECTIVE;
cbHeaderFlag6.Checked = geo.header.Flags_WIRE_FRAME;
cbHeaderFlag7.Checked = geo.header.Flags_TRANSPARENT_PIXELS;
cbHeaderFlag8.Checked = geo.header.Flags_ONE_THIRD_TRANSLUCENT_PIXELS;
cbHeaderFlag9.Checked = geo.header.Flags_PROJECT_POLYGON_ONLY;
cbHeaderFlag10.Checked = geo.header.Flags_Composit_ALPHA_BLEND;
cbHeaderFlag11.Checked = geo.header.Flags_Composit_TWO_THIRD_TRANSLUCENT_PIXELS;
cbHeaderFlag12.Checked = geo.header.Flags_Composit_FLAT_PERSPECTIVE_MAP;
cbHeaderFlag13.Checked = geo.header.Flags_Composit_FLAT_TILED_PERSPECTIVE_MAP;
cbHeaderFlag14.Checked = geo.header.Flags_Composit_HALLOW_WIRE_FRAME;
cbHeaderFlag1.Enabled = true;
cbHeaderFlag2.Enabled = true;
cbHeaderFlag3.Enabled = true;
cbHeaderFlag4.Enabled = true;
cbHeaderFlag5.Enabled = true;
cbHeaderFlag6.Enabled = true;
cbHeaderFlag7.Enabled = true;
cbHeaderFlag8.Enabled = true;
cbHeaderFlag9.Enabled = true;
cbHeaderFlag10.Enabled = true;
cbHeaderFlag11.Enabled = true;
cbHeaderFlag12.Enabled = true;
cbHeaderFlag13.Enabled = true;
cbHeaderFlag14.Enabled = true;
}
else
{
cbHeaderFlag1.Enabled = false;
cbHeaderFlag2.Enabled = false;
cbHeaderFlag3.Enabled = false;
cbHeaderFlag4.Enabled = false;
cbHeaderFlag5.Enabled = false;
cbHeaderFlag6.Enabled = false;
cbHeaderFlag7.Enabled = false;
cbHeaderFlag8.Enabled = false;
cbHeaderFlag9.Enabled = false;
cbHeaderFlag10.Enabled = false;
cbHeaderFlag11.Enabled = false;
cbHeaderFlag12.Enabled = false;
cbHeaderFlag13.Enabled = false;
cbHeaderFlag14.Enabled = false;
cbHeaderFlag1.CheckState = CheckState.Indeterminate;
cbHeaderFlag2.CheckState = CheckState.Indeterminate;
cbHeaderFlag3.CheckState = CheckState.Indeterminate;
cbHeaderFlag4.CheckState = CheckState.Indeterminate;
cbHeaderFlag5.CheckState = CheckState.Indeterminate;
cbHeaderFlag6.CheckState = CheckState.Indeterminate;
cbHeaderFlag7.CheckState = CheckState.Indeterminate;
cbHeaderFlag8.CheckState = CheckState.Indeterminate;
cbHeaderFlag9.CheckState = CheckState.Indeterminate;
cbHeaderFlag10.CheckState = CheckState.Indeterminate;
cbHeaderFlag11.CheckState = CheckState.Indeterminate;
cbHeaderFlag12.CheckState = CheckState.Indeterminate;
cbHeaderFlag13.CheckState = CheckState.Indeterminate;
cbHeaderFlag14.CheckState = CheckState.Indeterminate;
}
DisableEvents = false;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
// Get the OpenGL object.
OpenGL gl = openGLControl.OpenGL;
float val = trackBar1.Value / 10.0f;
gl.LightModel(OpenGL.GL_LIGHT_MODEL_AMBIENT, new float[] { val, val, val });
}
private void tvFaces_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
e.Cancel = true;
}
private void tmrNotes_Tick(object sender, EventArgs e)
{
tmrNotes.Stop();
using(FileStream stream = File.Open("notes.txt", FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(txtNotes.Text);
}
}
}
private void txtNotes_TextChanged(object sender, EventArgs e)
{
if (notesLoaded)
{
tmrNotes.Stop();
tmrNotes.Start();
}
}
private void lbTextures_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DisableEvents && geo != null && lbTextures.SelectedIndex > -1 && checkerBitmaps.ContainsKey((string)lbTextures.SelectedItem))
{
TextureDataMap text = checkerBitmaps[(string)lbTextures.SelectedItem];
if (text.map != null)
{
if (text.map.IsPalletized && text.pallet != null)
{
pbTexture.Image = text.map.GetBitmap(text.pallet);
}
else
{
pbTexture.Image = text.map.GetBitmap();
}
pbTexture.Size = pbTexture.Image.Size;
}
else
{
pbTexture.Image = null;
pbTexture.Height = 0;
pbTexture.Width = 0;
}
if (text.pallet != null && text.pallet.Length > 0)
{
Bitmap act = new Bitmap(text.pallet.Length, 1);
for (int x = 0; x < text.pallet.Length; x++)
{
act.SetPixel(x, 0, text.pallet[x]);
}
pbPallet.Image = act;
}
else
{
pbPallet.Image = null;
}
if (lbTextures.Items.Count > 1)
{
btnRemoveTexture.Enabled = true;
}
else
{
btnRemoveTexture.Enabled = false;
}
}
else
{
pbTexture.Image = null;
pbTexture.Height = 0;
pbTexture.Width = 0;
pbPallet.Image = null;
btnRemoveTexture.Enabled = false;
}
}
private void btnAddTexture_Click(object sender, EventArgs e)
{
AddTextureDialog dlg = new AddTextureDialog();
if(dlg.ShowDialog() == DialogResult.OK)
{
if(AddTexture(dlg.Value))
{
UpdateOGLTextureData();
}
}
}
private bool AddTexture(string name, bool randomTexture = false)
{
name = name.Trim();
name = name.Substring(0, Math.Min(13, name.Length));
if (checkerBitmaps.ContainsKey(name)) return false;
OpenGL gl = openGLControl.OpenGL;
////////////////////////////////////////////////////////////////////////////////
TextureDataMap tmpTD = new TextureDataMap() { checker = CreateCheckerBitmap(randomTexture) };
gl.GenTextures(1, tmpTD._textureID);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, tmpTD.textureID);
checkerBitmaps.Add(name, tmpTD);
loadMAPToolStripMenuItem.DropDownItems.Add(name, null, OpenMap_Click);
clearMAPToolStripMenuItem.DropDownItems.Add(name, null, ClearMap_Click);
loadACTToolStripMenuItem.DropDownItems.Add(name, null, OpenAct_Click);
clearACTToolStripMenuItem.DropDownItems.Add(name, null, ClearAct_Click);
cbTexture.Items.Add(name);
lbTextures.Items.Add(name);
////////////////////////////////////////////////////////////////////////////////
string MAPFILE = path + Path.DirectorySeparatorChar + name + ".map";
if (File.Exists(MAPFILE))
{
tmpTD.map = MapFile.FromFile(MAPFILE);
}
string ACTFILE = path + Path.DirectorySeparatorChar + "objects.act";
if (File.Exists(ACTFILE))
{
tmpTD.pallet = MapFile.PalletFromFile(ACTFILE);
}
else
{
ACTFILE = "objects.act";
if (File.Exists(ACTFILE))
{
tmpTD.pallet = MapFile.PalletFromFile(ACTFILE);
}
}
return true;
}
private bool RemoveTexture(string name)
{
name = name.Trim();
name = name.Substring(0, Math.Min(13, name.Length));
if (!checkerBitmaps.ContainsKey(name)) return false;
geo.faces.ForEach(face =>
{
if (face.TextureName_STR == name) face.TextureName_STR = checkerBitmaps.Keys.Where(dr => dr != name).First();
});
TextureDataMap tmpTD = checkerBitmaps[name];
checkerBitmaps.Remove(name);
OpenGL gl = openGLControl.OpenGL;
gl.DeleteTextures(1, tmpTD._textureID);
{ ToolStripItem itm_Remove = null; foreach (ToolStripItem itm in loadMAPToolStripMenuItem.DropDownItems) { if (itm.Text == name) { itm_Remove = itm; break; } } loadMAPToolStripMenuItem.DropDownItems.Remove(itm_Remove); }
{ ToolStripItem itm_Remove = null; foreach (ToolStripItem itm in clearMAPToolStripMenuItem.DropDownItems) { if (itm.Text == name) { itm_Remove = itm; break; } } clearMAPToolStripMenuItem.DropDownItems.Remove(itm_Remove); }
{ ToolStripItem itm_Remove = null; foreach (ToolStripItem itm in loadACTToolStripMenuItem.DropDownItems) { if (itm.Text == name) { itm_Remove = itm; break; } } loadACTToolStripMenuItem.DropDownItems.Remove(itm_Remove); }
{ ToolStripItem itm_Remove = null; foreach (ToolStripItem itm in clearACTToolStripMenuItem.DropDownItems) { if (itm.Text == name) { itm_Remove = itm; break; } } clearACTToolStripMenuItem.DropDownItems.Remove(itm_Remove); }
cbTexture.Items.Remove(name);
lbTextures.Items.Remove(name);
UpdateOGLTextureData();
return true;
}
private void btnRemoveTexture_Click(object sender, EventArgs e)
{
if (lbTextures.SelectedIndex > -1)
{
RemoveTexture((string)lbTextures.SelectedItem);
}
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void lstFacesUV_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateUVGraphics();
}
private void UpdateUVGraphics(float? dx = null, float? dy = null)
{
if (lstFacesUV.SelectedIndex > -1)
{
string TextureName = ((FaceListWrapper)(lstFacesUV.SelectedItems[0])).Value.TextureName_STR;
foreach (FaceListWrapper wrapper in lstFacesUV.SelectedItems)
{
if (TextureName != wrapper.Value.TextureName_STR)
{
TextureName = null;
break;
}
}
if (TextureName != null && checkerBitmaps.ContainsKey(TextureName))
{
TextureDataMap dat = checkerBitmaps[TextureName];
Image tmpImg = null;
if (dat.map != null)
{
if (dat.map.IsPalletized && dat.pallet != null)
{
tmpImg = dat.map.GetBitmap(dat.pallet);
}
else
{
tmpImg = dat.map.GetBitmap();
}
}
else
{
tmpImg = CreateCheckerBitmap();
}
nudZoom.Enabled = true;
nudZoom.Maximum = Math.Max(1, (int)(512 / Math.Max(tmpImg.Width, tmpImg.Height)));
int scaleFactor = (int)nudZoom.Value;
Image tmpImg2 = (Image)new Bitmap(tmpImg.Width * scaleFactor, tmpImg.Height * scaleFactor);
using (Graphics g = Graphics.FromImage(tmpImg2))
{
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(tmpImg, 0, 0, tmpImg.Width * scaleFactor, tmpImg.Height * scaleFactor);
}
tmpImg.Dispose();
tmpImg = tmpImg2;
pbTextureUV.Image = new Bitmap(tmpImg.Width * 3, tmpImg.Height * 3);
using (Graphics g = Graphics.FromImage(pbTextureUV.Image))
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
g.DrawImageUnscaled(tmpImg, x * tmpImg.Width, y * tmpImg.Height);
if (x != 1 || y != 1)
{
g.FillRectangle(new SolidBrush(Color.FromArgb(128, 0, 0, 0)), x * tmpImg.Width, y * tmpImg.Height, tmpImg.Width, tmpImg.Height);
}
}
}
g.DrawLines(new Pen(Color.FromArgb(128, 0, 0, 255)), new Point[] {
new Point(tmpImg.Width - 1, tmpImg.Height - 1),
new Point(tmpImg.Width + tmpImg.Width, tmpImg.Height - 1),
new Point(tmpImg.Width + tmpImg.Width, tmpImg.Height + tmpImg.Height),
new Point(tmpImg.Width - 1, tmpImg.Height + tmpImg.Height),
new Point(tmpImg.Width - 1, tmpImg.Height - 1)
});
List<Rectangle> rects = new List<Rectangle>();
List<Rectangle> rects2 = new List<Rectangle>();
List<List<Point>> points = new List<List<Point>>();
foreach (FaceListWrapper wrapper in lstFacesUV.SelectedItems)
{
Face f = wrapper.Value;
List<Point> subpoints = new List<Point>();
points.Add(subpoints);
subpoints.Add(new Point((int)(f.Wireframe[f.VertexCount - 1].u * tmpImg.Width) + tmpImg.Width, (int)(f.Wireframe[f.VertexCount - 1].v * tmpImg.Height) + tmpImg.Height));
for (int v = 0; v < f.VertexCount; v++)
{
FaceNode node = f.Wireframe[v];
if (SelectedUVs.Contains(node))
{
if (dx.HasValue && dy.HasValue)
{
rects2.Add(new Rectangle((int)((node.u + dx.Value) * tmpImg.Width) - 2 + tmpImg.Width, (int)((node.v + dy.Value) * tmpImg.Height) - 2 + tmpImg.Height, 5, 5));
}
else
{
rects2.Add(new Rectangle((int)(node.u * tmpImg.Width) - 2 + tmpImg.Width, (int)(node.v * tmpImg.Height) - 2 + tmpImg.Height, 5, 5));
}
}
else
{
rects.Add(new Rectangle((int)(node.u * tmpImg.Width) - 2 + tmpImg.Width, (int)(node.v * tmpImg.Height) - 2 + tmpImg.Height, 5, 5));
}
subpoints.Add(new Point((int)(node.u * tmpImg.Width) + tmpImg.Width, (int)(node.v * tmpImg.Height) + tmpImg.Height));
}
}
if (rects.Count > 0) { g.DrawRectangles(new Pen(Color.Blue), rects.ToArray()); }
if (rects2.Count > 0) { g.DrawRectangles(new Pen(Color.Red), rects2.ToArray()); }
points.ForEach(subpoints =>
{
if (subpoints.Count > 0) { g.DrawLines(new Pen(Color.LightGreen), subpoints.ToArray()); }
});
}
tmpImg.Dispose();
pbTextureUV.Size = pbTextureUV.Image.Size;
}
else
{
pbTextureUV.Image = null;
pbTextureUV.Height = 0;
pbTextureUV.Width = 0;
}
}
else
{
pbTextureUV.Image = null;
pbTextureUV.Height = 0;
pbTextureUV.Width = 0;
nudZoom.Enabled = true;
nudZoom.Maximum = 1;
}
}
private List<FaceNode> SelectedUVs = new List<FaceNode>();
float UVStartX = 0.0f;
float UVStartY = 0.0f;
bool DraggingUV = false;
private void pbTextureUV_MouseDown(object sender, MouseEventArgs e)
{
SelectedUVs.Clear();
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
{
if (lstFacesUV.SelectedIndex > -1)
{
UVdX = 0;
UVdY = 0;
if (pbTextureUV.Image != null)
{
int w = pbTextureUV.Image.Width / 3;
int h = pbTextureUV.Image.Height / 3;
UVStartX = (e.X - w) * 1.0f / w;
UVStartY = (e.Y - h) * 1.0f / h;
foreach (FaceListWrapper wrapper in lstFacesUV.SelectedItems)
{
//foreach(FaceNode node in wrapper.Value.Wireframe)
for (int z = 0; z < wrapper.Value.VertexCount; z++)
{
FaceNode node = wrapper.Value.Wireframe[z];
if (Math.Abs(node.u - UVStartX) < 0.02f && Math.Abs(node.v - UVStartY) < 0.02f)
{
//Console.WriteLine("{0},{1}", node.u, node.v);
SelectedUVs.Add(node);
}
}
}
if (e.Button == MouseButtons.Middle && SelectedUVs.Count > 0)
{
SelectedUVs = new List<FaceNode>() { SelectedUVs.OrderBy(node => Math.Abs(node.u - UVStartX) + Math.Abs(node.v - UVStartY)).First() };
}
DraggingUV = true;
tmrUV.Start();
}
}
UpdateUVGraphics();
}else if(e.Button == MouseButtons.Right)
{
SelectedUVs.Clear();
UpdateUVGraphics();
DraggingUV = false;
}
}
private void pbTextureUV_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
{
if (SelectedUVs.Count > 0)
{
if (lstFacesUV.SelectedIndex > -1)
{
if (pbTextureUV.Image != null)
{
int w = pbTextureUV.Image.Width / 3;
int h = pbTextureUV.Image.Height / 3;
float x = (e.X - w) * 1.0f / w;
float y = (e.Y - h) * 1.0f / h;
float dX = x - UVStartX;
float dY = y - UVStartY;
foreach (FaceListWrapper wrapper in lstFacesUV.SelectedItems)
{
for (int z = 0; z < wrapper.Value.VertexCount; z++)
{
if (SelectedUVs.Contains(wrapper.Value.Wireframe[z]))
{
wrapper.Value.Wireframe[z].u += dX;
wrapper.Value.Wireframe[z].v += dY;
}
}
}
tmrUV.Start();
DraggingUV = false;
}
}
SelectedUVs.Clear();
UpdateUVGraphics();
}
}
}
float UVdX = 0.0f;
float UVdY = 0.0f;
private void pbTextureUV_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
{
if (SelectedUVs.Count > 0)
{
if (lstFacesUV.SelectedIndex > -1)
{
if (pbTextureUV.Image != null)
{
int w = pbTextureUV.Image.Width / 3;
int h = pbTextureUV.Image.Height / 3;
float x = (e.X - w) * 1.0f / w;
float y = (e.Y - h) * 1.0f / h;
UVdX = x - UVStartX;
UVdY = y - UVStartY;
if (!tmrUV.Enabled) tmrUV.Start();
}
else { tmrUV.Stop(); }
}
else { tmrUV.Stop(); }
}
else { tmrUV.Stop(); }
}
else { tmrUV.Stop(); }
}
private void tmrUV_Tick(object sender, EventArgs e)
{
if (SelectedUVs.Count > 0)
{
if (lstFacesUV.SelectedIndex > -1)
{
if (pbTextureUV.Image != null)
{
UpdateUVGraphics(UVdX, UVdY);
}
}
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (DraggingUV)
{
switch (keyData)
{
case Keys.W:
Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y - 1);
break;
case Keys.D:
Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y);
break;
case Keys.S:
Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y + 1);
break;
case Keys.A:
Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y);
break;
case Keys.Control:
break;
default:
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void nudZoom_ValueChanged(object sender, EventArgs e)
{
UpdateUVGraphics();
}
private void exportOBJToolStripMenuItem_Click(object sender, EventArgs e)
{
if(geo != null)
{
if(saveFileDialog2.ShowDialog() == DialogResult.OK)
{
using (FileStream fstream = File.Open(Path.ChangeExtension(saveFileDialog2.FileName,"mtl"), FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fstream))
{
textureNames.ForEach(text =>
{
writer.WriteLine("newmtl {0}", text);
writer.WriteLine("Ka 1.000000 1.000000 1.000000");
writer.WriteLine("Kd 1.000000 1.000000 1.000000");
writer.WriteLine("Ks 0.000000 0.000000 0.000000");
writer.WriteLine("Tr 1.000000");
writer.WriteLine("illum 1");
writer.WriteLine("Ns 0.000000");
writer.WriteLine("map_Kd {0}.bmp", text);
writer.WriteLine();
});
}
}
using (FileStream fstream = File.Open(saveFileDialog2.FileName, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fstream))
{
writer.WriteLine("mtllib {0}", Path.ChangeExtension(Path.GetFileName(saveFileDialog2.FileName), "mtl"));
writer.WriteLine();
foreach(Vector3D vect in geo.vecs)
{
writer.WriteLine("v {0} {1} {2}", -vect.x, -vect.z, vect.y);
}
writer.WriteLine();
geo.faces.ForEach(face =>
{
foreach (FaceNode node in face.Wireframe)
{
writer.WriteLine("vt {0} {1}", node.u, 1 - node.v);
}
});
writer.WriteLine();
foreach(Vector3D vect in geo.vecnorms)
{
writer.WriteLine("vn {0} {1} {2}", -vect.x, -vect.z, vect.y);
}
writer.WriteLine();
int uvcounter = 1;
geo.faces.ForEach(face =>
{
writer.WriteLine("usemtl {0}", face.TextureName_STR);
writer.Write("f");
foreach(FaceNode node in face.Wireframe)
{
writer.Write(" {0}/{1}/{2}", node.VertexId + 1, uvcounter++, node.VertexNormalId + 1);
}
writer.WriteLine();
});
}
}
}
}
}
}
}
|
db7edb6a1f2cc2780977636686dc40f89b4a07e1
|
[
"Markdown",
"C#"
] | 4
|
C#
|
Nielk1/bz1-geo-editor
|
bac27dc080e1b43e2a26b7a12bf68afbe2777a1e
|
3789901485843a45b5b293ac20fa3e10c011859c
|
refs/heads/master
|
<repo_name>LoginRadius/html5-sdk<file_sep>/demo/assets/js/profile.js
var stringVariable = window.location.href;
domainName = stringVariable.substring(0, stringVariable.lastIndexOf('/'));
$(function () {
handleChangePassword();
createCustomObjects();
getCustomObjects();
updateCustomObjects();
deleteCustomObjects();
});
function handleChangePassword() {
$('#btn-user-changepassword').on('click', function () {
$("#user-changepassword-errorMsg").text("");
$("#user-changepassword-successMsg").text("");
if ($('#user-changepassword-oldpassword').val().trim() == '' || $('#user-changepassword-newpassword').val().trim() == '') {
$("#user-changepassword-errorMsg").text("The password field is required.");
return;
} else if ($('#user-changepassword-newpassword').val().trim().length < '6') {
$("#user-changepassword-errorMsg").text("The New Password field must be at least 6 characters in length.");
return;
}
$("#lr-loading").show();
var accessToken = LoginRadiusSDK.getToken();
LoginRadiusSDK.authenticationApi.changePassword(accessToken, $("#user-changepassword-newpassword").val(), $("#user-changepassword-oldpassword").val(), function(error, data){
$("#lr-loading").hide();
if (error) {
$("#user-changepassword-errorMsg").text(error.Message);
return;
}
if (data) {
$("#user-changepassword-oldpassword").val("");
$("#user-changepassword-newpassword").val("");
$("#user-changepassword-successMsg").text('Password has been changed');
}
});
});
}
function createCustomObjects() {
$('#btn-user-createcustomobj').on('click', function () {
$("#user-createcustomobj-successMsg").text("");
$("#user-createcustomobj-errorMsg").text("");
var input = $("#user-createcustomobj-data").val();
if ($('#user-createcustomobj-objectname').val().trim() == '') {
$("#user-createcustomobj-errorMsg").text("The Object Name field is required.");
return;
} else if ($('#user-createcustomobj-data').val().trim() == '') {
$("#user-createcustomobj-errorMsg").text("The Data field is required.");
return;
} else if (!IsJsonString(input)) {
$("#user-createcustomobj-errorMsg").text("Invalid json in Data field.");
return;
}
var accessToken = LoginRadiusSDK.getToken();
var objectName = $("#user-createcustomobj-objectname").val();
var payload = JSON.parse($("#user-createcustomobj-data").val());
$("#lr-loading").show();
LoginRadiusSDK.customObjectApi.createCustomObjectByToken(accessToken, objectName, payload, function(error, data){
$("#lr-loading").hide();
console.log(error);
if (error) {
$("#user-createcustomobj-errorMsg").html(error.Message);
return;
}
if (data) {
$("#user-createcustomobj-objectname").val("");
$("#user-createcustomobj-data").val("");
$("#user-createcustomobj-successMsg").text("Custom object created successfully.");
}
});
});
}
function getCustomObjects() {
$('#btn-user-getcustomobj').on('click', function () {
$("#user-getcustomobj-errorMsg").text("");
$("#user-getcustomobj-successMsg").text("");
if ($("#user-getcustomobj-objectname").val().trim() == ''){
$("#user-getcustomobj-errorMsg").text("The Object Name field is required.");
return;
}
$("#lr-loading").show();
var accessToken = LoginRadiusSDK.getToken();
var objectName = $("#user-getcustomobj-objectname").val();
LoginRadiusSDK.customObjectApi.getCustomObjectByToken(accessToken, objectName, function(error, response){
$("#lr-loading").hide();
$("#user-getcustomobj-errorMsg").text("");
if (error) {
$("#user-getcustomobj-errorMsg").text(error.Message);
$('#customobj-table').html('');
return;
}
if (response) {
$("#user-getcustomobj-objectname").val("");
$('#customobj-table').html('');
$('#customobj-table').append('<tr><th>Object ID</th><th>Custom Object</th></tr>');
for (var i = 0; i < response.data.length; i++) {
var id = response.data[i].Id;
var custobj = response.data[i].CustomObject;
$('#customobj-table').append('<tr><td>' + id + '</td><td>' + JSON.stringify(custobj) + '</td></tr>');
}
}
})
});
}
function updateCustomObjects() {
$('#btn-user-updatecustomobj').on('click', function () {
$("#user-updatecustomobj-errorMsg").text("");
$("#user-updatecustomobj-successMsg").text("");
var input = $("#user-updatecustomobj-data").val();
if ($('#user-updatecustomobj-objectname').val().trim() == '') {
$("#user-updatecustomobj-errorMsg").text("The Object Name field is required.");
return;
} else if ($('#user-updatecustomobj-objectrecordid').val().trim() == '') {
$("#user-updatecustomobj-errorMsg").text("The Object Record Id field is required.");
return;
}else if ($('#user-updatecustomobj-data').val().trim() == '') {
$("#user-updatecustomobj-errorMsg").text("The Data field is required.");
return;
} else if (!IsJsonString(input)) {
$("#user-updatecustomobj-errorMsg").text("Invalid json in Data field");
return;
}
$("#lr-loading").show();
var accessToken = LoginRadiusSDK.getToken();
var objectName= $("#user-updatecustomobj-objectname").val()
var objectRecordId = $("#user-updatecustomobj-objectrecordid").val();
var payload = JSON.parse($("#user-updatecustomobj-data").val());
var updateType = "";
LoginRadiusSDK.customObjectApi.updateCustomObjectByToken(accessToken, objectName,
objectRecordId, payload, updateType, function(error, data){
$("#lr-loading").hide();
if (error) {
$("#user-updatecustomobj-errorMsg").text(error.Message);
return;
}
if (data) {
$("#user-updatecustomobj-objectname").val("");
$("#user-updatecustomobj-objectrecordid").val("");
$("#user-updatecustomobj-data").val("");
$("#user-updatecustomobj-successMsg").text("Custom object has been updated.");
}
});
});
}
function deleteCustomObjects() {
$('#btn-user-deletecustomobj').on('click', function () {
$("#user-deletecustomobj-errorMsg").text("");
$("#user-deletecustomobj-successMsg").text("");
if ($('#user-deletecustomobj-objectname').val().trim() == '') {
$("#user-deletecustomobj-errorMsg").text("The Object Name field is required.");
return;
} else if ($('#user-deletecustomobj-objectrecordid').val().trim() == '') {
$("#user-deletecustomobj-errorMsg").text("The Object Record Id is required.");
return;
}
$("#lr-loading").show();
var accessToken = LoginRadiusSDK.getToken();
var objectName = $('#user-deletecustomobj-objectname').val();
var objectRecordId = $('#user-deletecustomobj-objectrecordid').val();
LoginRadiusSDK.customObjectApi.deleteCustomObjectByToken(accessToken, objectName, objectRecordId, function(error, data){
$("#lr-loading").hide();
if (error) {
$("#user-deletecustomobj-errorMsg").text(error.Message);
return;
}
if (data) {
$("#user-deletecustomobj-objectname").val("");
$("#user-deletecustomobj-objectrecordid").val("");
$("#user-deletecustomobj-successMsg").text("Custom object has been deleted");
}
})
});
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}<file_sep>/demo/assets/js/emailverification.js
var stringVariable = window.location.href;
domainName = stringVariable.substring(0, stringVariable.lastIndexOf('/'));
$(function() {
if (getUrlParameter("vtype") == "oneclicksignin") {
$("#lr-loading").show();
$("#emailverification-message").text("");
var verificationToken = getUrlParameter('vtoken');
var fields = "";
var welcomeEmailTemplate = "";
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginVerification(verificationToken, fields, welcomeEmailTemplate, function(error, data){
$("#lr-loading").hide();
if(error){
$("#emailverification-message").attr('style', 'color:red');
$("#emailverification-message").text(error.Message);
}
if (data) {
getProfile(data.access_token, data.Profile.Uid);
}
});
} else if (getUrlParameter("vtype") == "emailverification") {
$("#lr-loading").show();
$("#emailverification-message").text("");
var fields = '';
var url = window.location.href;
var welcomeEmailTemplate = '';
var verificationToken = getUrlParameter('vtoken');
LoginRadiusSDK.authenticationApi.verifyEmail(verificationToken, fields, url, welcomeEmailTemplate,function (error, data) {
$("#lr-loading").hide();
if (error) {
$("#emailverification-message").attr('style', 'color:red');
$("#emailverification-message").text(error.Message);
}
if (data.IsPosted) {
$("#emailverification-message").attr('style', 'color:green');
$("#emailverification-message").text('Your email has been verified successfully.');
}
});
}
});
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
}<file_sep>/CHANGELOG.md
# LoginRadius HTML5 SDK Change Log
# Version 11.2.0
Release on **September 15, 2021**
## Enhancements
- Updated Jquery with latest version(3.6.0) in SDK Demo
## Added new multiple APIs for better user experience
- MFAEmailOtpByAccessToken
- MFAValidateEmailOtpByAccessToken
- MFAResetEmailOtpAuthenticatorByAccessToken
- MFASecurityQuestionAnswerByAccessToken
- MFAResetSecurityQuestionAuthenticatorByAccessToken
- MFAEmailOTP
- MFAValidateEmailOtp
- MFASecurityQuestionAnswer
- MFASecurityQuestionAnswerVerification
- ReAuthValidateEmailOtp
- ReAuthSendEmailOtp
- ReAuthBySecurityQuestion
## Removed APIs:
- GetSocialUserProfile
Added `EmailTemplate2FA` parameter in the following API
- MFALoginByEmail
- MFALoginByUserName
- MFALoginByPhone
Added `RbaBrowserEmailTemplate`, `RbaCityEmailTemplate` ,`RbaCountryEmailTemplate` , `RbaIpEmailTemplate` parameter in the following API
- MFAValidateOTPByPhone
- MFAValidateGoogleAuthCode
- MFAValidateBackupCode
Added `emailTemplate`, `verificationUrl` ,`welcomeEmailTemplate` parameter in the following API
- GetProfileByAccessToken
# Version 11.1.1
Released on **June 11, 2021**
## Bug Fixed
- fixed API Key Validation issue
# Version 11.1.0
Released on **March 30, 2021**
## Enhancements:
- Added X-Origin-IP header support.
- Added 429 error code handling for "Too Many Request in a particular time frame".
- Fixed Delete API issue
## Added new multiple APIs for better user experience:
- Get Profile By Ping.
- Passwordless Login Verification By Email And OTP.
- Passwordless Login Verification By User Name And OTP.
# Version 11.0.0
Released on **July 28, 2020**
## Enhancements:
- Added a parameter isWeb in "RefreshAccessToken" API.
- Added a parameter SocialAppName in "getAccessTokenByFacebookAccessToken, getAccessTokenByTwitterAccessToken,
getAccessTokenByGoogleAccessToken, getAccessTokenByLinkedinAccessToken, getAccessTokenByAppleIdCode,
getAccessTokenByGoogleAuthCode" Native Social login APIs.
## Added new multiple APIs for better user experience:
- Added linkSocialIdentites(POST) API.
- Added linkSocialIdentitiesByPing(POST) API.
- Added getAccessTokenByAppleIdCode API.
- Added getAccessTokenByWeChatCode API.
## Removed APIs:
- linkSocialIdentity API(PUT)
- getSocialIdentity API(GET)
# Version 10.0.0
Released on **Dec 20, 2019**
## Enhancements
This full version release includes major changes with several improvements and optimizations
- Enhanced the coding standards of SDK to follow industry programming styles and best practices.
- Enhanced security standards of SDK.
- Added internal parameter validations in the API function.
- Improved the naming conventions of API functions for better readability.
- Better Error and Exception Handling for LoginRadius API Response in SDK.
- Revamped complete SDK and restructured it with latest API function names and parameters.
- Added detailed description to API functions and parameters for better understanding.
- Updated the demo according to latest SDK changes.
- Added PIN Authentication feature APIs.
- Added Consent Management feature APIs.
## Added new multiple APIs for better user experience
- MFA Resend OTP
- User Registration By Captcha
- Get Access Token via Linkedin Token
- Get Access Token By Foursquare Access Token
- MFA Re-authentication by PIN
- PIN Login
- Forgot PIN By Email
- Forgot PIN By UserName
- Reset PIN By ResetToken
- Reset PIN By SecurityAnswer And Email
- Reset PIN By SecurityAnswer And Username
- Reset PIN By SecurityAnswer And Phone
- Forgot PIN By Phone
- Change PIN By Token
- Reset PIN by Phone and OTP
- Reset PIN by Email and OTP
- Reset PIN by Username and OTP
- Set PIN By PinAuthToken
- Invalidate PIN Session Token
- Submit Consent By ConsentToken
- Get Consent Logs
- Submit Consent By AccessToken
- Verify Consent By AccessToken
- Update Consent Profile By AccessToken
- Album With Cursor
- Audio With Cursor
- Check In With Cursor
- Event With Cursor
- Following With Cursor
- Group With Cursor
- Like With Cursor
# Version 4.5.0
# 1.1.1
## Enhancements
Released on **September 19, 2018**
- Added Access Token required check for functions that call API Endpoints that consume an Access Token.
- Added API Key required check for all SDK functions.
<file_sep>/README.md
# LoginRadius HTML5 SDK
Customer Identity public repo for the HTML5 SDK, based on LoginRadius V2 APIs.

## Introduction ##
LoginRadius HTML 5 Customer Registration wrapper provides access to LoginRadius Identity Platform API.
LoginRadius is an Identity Management Platform that simplifies user registration while securing data. LoginRadius Platform simplifies and secures your user registration process, increases conversion with Social Login that combines 30 major social platforms, and offers a full solution with Traditional Customer Registration. You can gather a wealth of user profile data from Social Login or Traditional Customer Registration. This SDK includes support for the LoginRadius Authentication APIs, Custom Object Management APIs and Social APIs.
LoginRadius centralizes it all in one place, making it easy to manage and access. Easily integrate LoginRadius with all of your third-party applications, like MailChimp, Google Analytics, Livefyre and many more, making it easy to utilize the data you are capturing.
LoginRadius helps businesses boost user engagement on their web/mobile platform, manage online identities, utilize social media for marketing, capture accurate consumer data, and get unique social insight into their customer base.
Please visit [here](http://www.loginradius.com/) for more information.
## Documentation
-----
HTML5 SDK provides an approach to access LoginRadius service with only HTML and Javascript Get a Full Demo
>Disclaimer
This library is meant to help you with a quick implementation of the LoginRadius platform and also to serve as a reference point for the LoginRadius API. Keep in mind that it is an open source library, which means you are free to download and customize the library functions based on your specific application needs.
## Installation
In order to utilize the HTML5/JS SDK, you will need to initialize the SDK with your API Key:
```
var sdkoptions = {
"apiKey": "{{YOUR API KEY}}"
}
LoginRadiusSDK.initSDK(sdkoptions);
```
### X-Origin-IP
LoginRadius allows you to add X-Origin-IP in your headers and it determines the IP address of the client's request,this can also be useful to overcome analytics discrepancies where the analytics depend on header data.
```
var sdkoptions = {
"originIp": "{{CLIENT IP}}"
}
```
## Importing Required Libraries
- Download the SDK from [Github](https://github.com/LoginRadius/HTML5-SDK).
- Include the SDK javascript file on your website.
## HTML
```
<script src="LoginRadiusV2SDK.11.2.0.js" type="text/javascript"></script>
```
## Getting the Access Token
The Access Token will be automatically retrieved from logins performed via our LoginRadiusV2.js interface.
While it is required for many of the API Calls in our Authentication API, You can simple pass it.
However, if you need to manually retrieve the token, it can be done using ```LoginRadiusSDK.getToken()```
>Note
please make sure that all the API functions, are asynchronous.
## APIs
With the api key initialized and the access token, once a user has logged in, we can invoke any of these functions to grab data. However, this is dependent on the provider and permissions for each.
Note: All of the listed arguments must be passed for each function if you do not want
to pass a value simply pass an empty string `""`
When jsObject is listed as an argument you must pass in an Object as required for the specific API Call in our documentation.
### Authentication API
List of APIs in this Section:<br>
* PUT : [Auth Update Profile by Token](#UpdateProfileByAccessToken-put-)<br>
* PUT : [Auth Unlock Account by Access Token](#UnlockAccountByToken-put-)<br>
* PUT : [Auth Verify Email By OTP](#VerifyEmailByOTP-put-)<br>
* PUT : [Auth Reset Password by Security Answer and Email](#ResetPasswordBySecurityAnswerAndEmail-put-)<br>
* PUT : [Auth Reset Password by Security Answer and Phone](#ResetPasswordBySecurityAnswerAndPhone-put-)<br>
* PUT : [Auth Reset Password by Security Answer and UserName](#ResetPasswordBySecurityAnswerAndUserName-put-)<br>
* PUT : [Auth Reset Password by Reset Token](#ResetPasswordByResetToken-put-)<br>
* PUT : [Auth Reset Password by OTP](#ResetPasswordByEmailOTP-put-)<br>
* PUT : [Auth Reset Password by OTP and UserName](#ResetPasswordByOTPAndUserName-put-)<br>
* PUT : [Auth Change Password](#ChangePassword-put-)<br>
* PUT : [Auth Set or Change UserName](#SetOrChangeUserName-put-)<br>
* PUT : [Auth Resend Email Verification](#AuthResendEmailVerification-put-)<br>
* POST : [Auth Add Email](#AddEmail-post-)<br>
* POST : [Auth Login by Email](#LoginByEmail-post-)<br>
* POST : [Auth Login by Username](#LoginByUserName-post-)<br>
* POST : [Auth Forgot Password](#ForgotPassword-post-)<br>
* POST : [Auth Link Social Identities](#LinkSocialIdentities-post-)<br>
* POST : [Auth Link Social Identities By Ping](#LinkSocialIdentitiesByPing-post-)<br>
* POST : [Auth User Registration by Email](#UserRegistrationByEmail-post-)<br>
* POST : [Auth User Registration By Captcha](#UserRegistrationByCaptcha-post-)<br>
* GET : [Get Security Questions By Email](#GetSecurityQuestionsByEmail-get-)<br>
* GET : [Get Security Questions By UserName](#GetSecurityQuestionsByUserName-get-)<br>
* GET : [Get Security Questions By Phone](#GetSecurityQuestionsByPhone-get-)<br>
* GET : [Get Security Questions By Access Token](#GetSecurityQuestionsByAccessToken-get-)<br>
* GET : [Auth Validate Access token](#AuthValidateAccessToken-get-)<br>
* GET : [Access Token Invalidate](#AuthInValidateAccessToken-get-)<br>
* GET : [Access Token Info](#GetAccessTokenInfo-get-)<br>
* GET : [Auth Read all Profiles by Token](#GetProfileByAccessToken-get-)<br>
* GET : [Auth Send Welcome Email](#SendWelcomeEmail-get-)<br>
* GET : [Auth Delete Account](#DeleteAccountByDeleteToken-get-)<br>
* GET : [Get Profile By Ping](#GetProfileByPing-get-)<br>
* GET : [Auth Check Email Availability](#CheckEmailAvailability-get-)<br>
* GET : [Auth Verify Email](#VerifyEmail-get-)<br>
* GET : [Auth Check UserName Availability](#CheckUserNameAvailability-get-)<br>
* GET : [Auth Privacy Policy Accept](#AcceptPrivacyPolicy-get-)<br>
* GET : [Auth Privacy Policy History By Access Token](#GetPrivacyPolicyHistoryByAccessToken-get-)<br>
* DELETE : [Auth Delete Account with Email Confirmation](#DeleteAccountWithEmailConfirmation-delete-)<br>
* DELETE : [Auth Remove Email](#RemoveEmail-delete-)<br>
* DELETE : [Auth Unlink Social Identities](#UnlinkSocialIdentities-delete-)<br>
<h6 id="UpdateProfileByAccessToken-put-"> Auth Update Profile by Token (PUT)</h6>
This API is used to update the user's profile by passing the access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-update-profile-by-token/)
```
var accessToken = "<accessToken>"; //Required
var userProfileUpdateModel ={
"firstName" : "<firstName>",
"lastName" : "<lastName>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var nullSupport = true; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.authenticationApi.updateProfileByAccessToken(accessToken, userProfileUpdateModel, emailTemplate, fields, nullSupport, smsTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UnlockAccountByToken-put-"> Auth Unlock Account by Access Token (PUT)</h6>
This API is used to allow a customer with a valid access token to unlock their account provided that they successfully pass the prompted Bot Protection challenges. The Block or Suspend block types are not applicable for this API. For additional details see our Auth Security Configuration documentation.You are only required to pass the Post Parameters that correspond to the prompted challenges. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-unlock-account-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var unlockProfileModel ={
"g-recaptcha-response" : "<g-recaptcha-response>"
}; //Required
LoginRadiusSDK.authenticationApi.unlockAccountByToken(accessToken, unlockProfileModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="VerifyEmailByOTP-put-"> Auth Verify Email By OTP (PUT)</h6>
This API is used to verify the email of user when the OTP Email verification flow is enabled, please note that you must contact LoginRadius to have this feature enabled. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-verify-email-by-otp/)
```
var emailVerificationByOtpModel ={
"email" : "<email>",
"otp" : "<otp>"
}; //Required
var fields = null; //Optional
var url = "<url>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.verifyEmailByOTP(emailVerificationByOtpModel, fields, url, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordBySecurityAnswerAndEmail-put-"> Auth Reset Password by Security Answer and Email (PUT)</h6>
This API is used to reset password for the specified account by security question [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-email)
```
var resetPasswordBySecurityAnswerAndEmailModel ={
"email" : "<email>",
"password" : "<<PASSWORD>>",
"securityAnswer" : {"QuestionID":"Answer"}
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordBySecurityAnswerAndEmail(resetPasswordBySecurityAnswerAndEmailModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordBySecurityAnswerAndPhone-put-"> Auth Reset Password by Security Answer and Phone (PUT)</h6>
This API is used to reset password for the specified account by security question [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-phone)
```
var resetPasswordBySecurityAnswerAndPhoneModel ={
"password" : "<<PASSWORD>>",
"phone" : "<phone>",
"securityAnswer" : {"QuestionID":"Answer"}
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordBySecurityAnswerAndPhone(resetPasswordBySecurityAnswerAndPhoneModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordBySecurityAnswerAndUserName-put-"> Auth Reset Password by Security Answer and UserName (PUT)</h6>
This API is used to reset password for the specified account by security question [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-username)
```
var resetPasswordBySecurityAnswerAndUserNameModel ={
"password" : "<<PASSWORD>>",
"securityAnswer" : {"QuestionID":"Answer"},
"userName" : "<userName>"
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordBySecurityAnswerAndUserName(resetPasswordBySecurityAnswerAndUserNameModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordByResetToken-put-"> Auth Reset Password by Reset Token (PUT)</h6>
This API is used to set a new password for the specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-reset-token)
```
var resetPasswordByResetTokenModel ={
"password" : "<<PASSWORD>>",
"resetToken" : "<resetToken>"
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordByResetToken(resetPasswordByResetTokenModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordByEmailOTP-put-"> Auth Reset Password by OTP (PUT)</h6>
This API is used to set a new password for the specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-otp)
```
var resetPasswordByEmailAndOtpModel ={
"email" : "<email>",
"otp" : "<otp>",
"password" : "<<PASSWORD>>"
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordByEmailOTP(resetPasswordByEmailAndOtpModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPasswordByOTPAndUserName-put-"> Auth Reset Password by OTP and UserName (PUT)</h6>
This API is used to set a new password for the specified account if you are using the username as the unique identifier in your workflow [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-reset-password-by-otp-and-username/)
```
var resetPasswordByUserNameModel ={
"otp" : "<otp>",
"password" : "<<PASSWORD>>",
"userName" : "<userName>"
}; //Required
LoginRadiusSDK.authenticationApi.resetPasswordByOTPAndUserName(resetPasswordByUserNameModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ChangePassword-put-"> Auth Change Password (PUT)</h6>
This API is used to change the accounts password based on the previous password [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-change-password)
```
var accessToken = "<accessToken>"; //Required
var newPassword = "<<PASSWORD>>"; //Required
var oldPassword = "<<PASSWORD>>"; //Required
LoginRadiusSDK.authenticationApi.changePassword(accessToken, newPassword, oldPassword, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SetOrChangeUserName-put-"> Auth Set or Change UserName (PUT)</h6>
This API is used to set or change UserName by access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-set-or-change-user-name/)
```
var accessToken = "<accessToken>"; //Required
var username = "<username>"; //Required
LoginRadiusSDK.authenticationApi.setOrChangeUserName(accessToken, username, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AuthResendEmailVerification-put-"> Auth Resend Email Verification (PUT)</h6>
This API resends the verification email to the user. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-resend-email-verification/)
```
var email = "<email>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.authenticationApi.authResendEmailVerification(email, emailTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AddEmail-post-"> Auth Add Email (POST)</h6>
This API is used to add additional emails to a user's account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-add-email)
```
var accessToken = "<accessToken>"; //Required
var email = "<email>"; //Required
var type = "<type>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.authenticationApi.addEmail(accessToken, email, type, emailTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="LoginByEmail-post-"> Auth Login by Email (POST)</h6>
This API retrieves a copy of the user data based on the Email [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-login-by-email)
```
var emailAuthenticationModel ={
"email" : "<email>",
"password" : "<<PASSWORD>>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.authenticationApi.loginByEmail(emailAuthenticationModel, emailTemplate, fields, loginUrl, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="LoginByUserName-post-"> Auth Login by Username (POST)</h6>
This API retrieves a copy of the user data based on the Username [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-login-by-username)
```
var userNameAuthenticationModel ={
"password" : "<<PASSWORD>>",
"username" : "<username>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.authenticationApi.loginByUserName(userNameAuthenticationModel, emailTemplate, fields, loginUrl, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ForgotPassword-post-"> Auth Forgot Password (POST)</h6>
This API is used to send the reset password url to a specified account. Note: If you have the UserName workflow enabled, you may replace the 'email' parameter with 'username' [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-forgot-password)
```
var email = "<email>"; //Required
var resetPasswordUrl = "<resetPasswordUrl>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.forgotPassword(email, resetPasswordUrl, emailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="LinkSocialIdentities-post-"> Auth Link Social Identities (POST)</h6>
This API is used to link up a social provider account with an existing LoginRadius account on the basis of access token and the social providers user access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-link-social-identities)
```
var accessToken = "<accessToken>"; //Required
var candidateToken = "<candidateToken>"; //Required
LoginRadiusSDK.authenticationApi.linkSocialIdentities(accessToken, candidateToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="LinkSocialIdentitiesByPing-post-"> Auth Link Social Identities By Ping (POST)</h6>
This API is used to link up a social provider account with an existing LoginRadius account on the basis of ping and the social providers user access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-link-social-identities-by-ping)
```
var accessToken = "<accessToken>"; //Required
var clientGuid = "<clientGuid>"; //Required
LoginRadiusSDK.authenticationApi.linkSocialIdentitiesByPing(accessToken, clientGuid, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UserRegistrationByEmail-post-"> Auth User Registration by Email (POST)</h6>
This API creates a user in the database as well as sends a verification email to the user. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-user-registration-by-email)
```
var authUserRegistrationModel ={
"email" : [ {
"type" : "<type>" ,
"value" : "<value>"
} ] ,
"firstName" : "<firstName>",
"lastName" : "<lastName>",
"password" : "<<PASSWORD>>"
}; //Required
var sott = "<sott>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var options = "<options>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.userRegistrationByEmail(authUserRegistrationModel, sott, emailTemplate, fields, options, verificationUrl, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UserRegistrationByCaptcha-post-"> Auth User Registration By Captcha (POST)</h6>
This API creates a user in the database as well as sends a verification email to the user. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-user-registration-by-recaptcha)
```
var authUserRegistrationModelWithCaptcha ={
"email" : [ {
"type" : "<type>" ,
"value" : "<value>"
} ] ,
"firstName" : "<firstName>",
"g-recaptcha-response" : "<g-recaptcha-response>",
"lastName" : "<lastName>",
"password" : "<<PASSWORD>>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var options = "<options>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.userRegistrationByCaptcha(authUserRegistrationModelWithCaptcha, emailTemplate, fields, options, smsTemplate, verificationUrl, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetSecurityQuestionsByEmail-get-"> Get Security Questions By Email (GET)</h6>
This API is used to retrieve the list of questions that are configured on the respective LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/security-questions-by-email/)
```
var email = "<email>"; //Required
LoginRadiusSDK.authenticationApi.getSecurityQuestionsByEmail(email, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetSecurityQuestionsByUserName-get-"> Get Security Questions By UserName (GET)</h6>
This API is used to retrieve the list of questions that are configured on the respective LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/security-questions-by-user-name/)
```
var userName = "<userName>"; //Required
LoginRadiusSDK.authenticationApi.getSecurityQuestionsByUserName(userName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetSecurityQuestionsByPhone-get-"> Get Security Questions By Phone (GET)</h6>
This API is used to retrieve the list of questions that are configured on the respective LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/security-questions-by-phone/)
```
var phone = "<phone>"; //Required
LoginRadiusSDK.authenticationApi.getSecurityQuestionsByPhone(phone, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetSecurityQuestionsByAccessToken-get-"> Get Security Questions By Access Token (GET)</h6>
This API is used to retrieve the list of questions that are configured on the respective LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/security-questions-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.authenticationApi.getSecurityQuestionsByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AuthValidateAccessToken-get-"> Auth Validate Access token (GET)</h6>
This api validates access token, if valid then returns a response with its expiry otherwise error. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-validate-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.authenticationApi.authValidateAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AuthInValidateAccessToken-get-"> Access Token Invalidate (GET)</h6>
This api call invalidates the active access token or expires an access token's validity. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-invalidate-access-token/)
```
var accessToken = "<accessToken>"; //Required
var preventRefresh = true; //Optional
LoginRadiusSDK.authenticationApi.authInValidateAccessToken(accessToken, preventRefresh, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenInfo-get-"> Access Token Info (GET)</h6>
This api call provide the active access token Information [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-access-token-info/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.authenticationApi.getAccessTokenInfo(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetProfileByAccessToken-get-"> Auth Read all Profiles by Token (GET)</h6>
This API retrieves a copy of the user data based on the access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-read-profiles-by-token/)
```
var accessToken = "<accessToken>"; //Required
var fields = null; //Optional
var emailTemplate = "<emailTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.getProfileByAccessToken(accessToken, fields,emailTemplate, verificationUrl, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SendWelcomeEmail-get-"> Auth Send Welcome Email (GET)</h6>
This API sends a welcome email [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-send-welcome-email/)
```
var accessToken = "<accessToken>"; //Required
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.sendWelcomeEmail(accessToken, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="DeleteAccountByDeleteToken-get-"> Auth Delete Account (GET)</h6>
This API is used to delete an account by passing it a delete token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-delete-account/)
```
var deletetoken = "<deletetoken>"; //Required
LoginRadiusSDK.authenticationApi.deleteAccountByDeleteToken(deletetoken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetProfileByPing-get-">Get Profile By Ping (GET)</h6>
This API is used to get a user's profile using the clientGuid parameter if no callback feature enabled. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/social-login-by-ping/)
```
var clientGuid = "<clientGuid>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.getProfileByPing(clientGuid, emailTemplate, fields, verificationUrl, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="CheckEmailAvailability-get-"> Auth Check Email Availability (GET)</h6>
This API is used to check the email exists or not on your site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-email-availability/)
```
var email = "<email>"; //Required
LoginRadiusSDK.authenticationApi.checkEmailAvailability(email, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="VerifyEmail-get-"> Auth Verify Email (GET)</h6>
This API is used to verify the email of user. Note: This API will only return the full profile if you have 'Enable auto login after email verification' set in your LoginRadius Admin Console's Email Workflow settings under 'Verification Email'. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-verify-email/)
```
var verificationToken = "<verificationToken>"; //Required
var fields = null; //Optional
var url = "<url>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.verifyEmail(verificationToken, fields, url, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="CheckUserNameAvailability-get-"> Auth Check UserName Availability (GET)</h6>
This API is used to check the UserName exists or not on your site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-username-availability/)
```
var username = "<username>"; //Required
LoginRadiusSDK.authenticationApi.checkUserNameAvailability(username, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AcceptPrivacyPolicy-get-"> Auth Privacy Policy Accept (GET)</h6>
This API is used to update the privacy policy stored in the user's profile by providing the access token of the user accepting the privacy policy [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-privacy-policy-accept)
```
var accessToken = "<accessToken>"; //Required
var fields = null; //Optional
LoginRadiusSDK.authenticationApi.acceptPrivacyPolicy(accessToken, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetPrivacyPolicyHistoryByAccessToken-get-"> Auth Privacy Policy History By Access Token (GET)</h6>
This API will return all the accepted privacy policies for the user by providing the access token of that user. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/privacy-policy-history-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.authenticationApi.getPrivacyPolicyHistoryByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="DeleteAccountWithEmailConfirmation-delete-"> Auth Delete Account with Email Confirmation (DELETE)</h6>
This API will send a confirmation email for account deletion to the customer's email when passed the customer's access token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-delete-account-with-email-confirmation/)
```
var accessToken = "<accessToken>"; //Required
var deleteUrl = "<deleteUrl>"; //Optional
var emailTemplate = "<emailTemplate>"; //Optional
LoginRadiusSDK.authenticationApi.deleteAccountWithEmailConfirmation(accessToken, deleteUrl, emailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="RemoveEmail-delete-"> Auth Remove Email (DELETE)</h6>
This API is used to remove additional emails from a user's account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-remove-email)
```
var accessToken = "<accessToken>"; //Required
var email = "<email>"; //Required
LoginRadiusSDK.authenticationApi.removeEmail(accessToken, email, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UnlinkSocialIdentities-delete-"> Auth Unlink Social Identities (DELETE)</h6>
This API is used to unlink up a social provider account with the specified account based on the access token and the social providers user access token. The unlinked account will automatically get removed from your database. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-unlink-social-identities)
```
var accessToken = "<accessToken>"; //Required
var provider = "<provider>"; //Required
var providerId = "<providerId>"; //Required
LoginRadiusSDK.authenticationApi.unlinkSocialIdentities(accessToken, provider, providerId, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### Social API
List of APIs in this Section:<br>
* POST : [Post Message API](#PostMessage-post-)<br>
* POST : [Status Posting ](#StatusPosting-post-)<br>
* POST : [Trackable Status Posting](#TrackableStatusPosting-post-)<br>
* GET : [Album](#GetAlbums-get-)<br>
* GET : [Get Albums with cursor](#GetAlbumsWithCursor-get-)<br>
* GET : [Audio](#GetAudios-get-)<br>
* GET : [Get Audio With Cursor](#GetAudiosWithCursor-get-)<br>
* GET : [Check In](#GetCheckIns-get-)<br>
* GET : [Get CheckIns With Cursor](#GetCheckInsWithCursor-get-)<br>
* GET : [Contact](#GetContacts-get-)<br>
* GET : [Event](#GetEvents-get-)<br>
* GET : [Get Events With Cursor](#GetEventsWithCursor-get-)<br>
* GET : [Following](#GetFollowings-get-)<br>
* GET : [Get Followings With Cursor](#GetFollowingsWithCursor-get-)<br>
* GET : [Group](#GetGroups-get-)<br>
* GET : [Get Groups With Cursor](#GetGroupsWithCursor-get-)<br>
* GET : [Like](#GetLikes-get-)<br>
* GET : [Get Likes With Cursor](#GetLikesWithCursor-get-)<br>
* GET : [Mention](#GetMentions-get-)<br>
* GET : [Page](#GetPage-get-)<br>
* GET : [Photo](#GetPhotos-get-)<br>
* GET : [Get Post](#GetPosts-get-)<br>
* GET : [Get Trackable Status Stats](#GetTrackableStatusStats-get-)<br>
* GET : [Refresh User Profile](#GetRefreshedSocialUserProfile-get-)<br>
* GET : [Video](#GetVideos-get-)<br>
<h6 id="PostMessage-post-"> Post Message API (POST)</h6>
Post Message API is used to post messages to the user's contacts.<br><br><b>Supported Providers:</b> Twitter, LinkedIn <br><br>The Message API is used to post messages to the user?s contacts. This is one of the APIs that makes up the LoginRadius Friend Invite System. After using the Contact API, you can send messages to the retrieved contacts. This API requires setting permissions in your LoginRadius Dashboard.<br><br>GET & POST Message API work the same way except the API method is different [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/post-message-api)
```
var accessToken = "<accessToken>"; //Required
var message = "<message>"; //Required
var subject = "<subject>"; //Required
var to = "<to>"; //Required
LoginRadiusSDK.socialApi.postMessage(accessToken, message, subject, to, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="StatusPosting-post-"> Status Posting (POST)</h6>
The Status API is used to update the status on the user's wall.<br><br><b>Supported Providers:</b> Facebook, Twitter, LinkedIn [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/status-posting/)
```
var accessToken = "<accessToken>"; //Required
var caption = "<caption>"; //Required
var description = "<description>"; //Required
var imageurl = "<imageurl>"; //Required
var status = "<status>"; //Required
var title = "<title>"; //Required
var url = "<url>"; //Required
var shorturl = "<shorturl>"; //Optional
LoginRadiusSDK.socialApi.statusPosting(accessToken, caption, description, imageurl, status, title, url, shorturl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="TrackableStatusPosting-post-"> Trackable Status Posting (POST)</h6>
The Trackable status API works very similar to the Status API but it returns a Post id that you can use to track the stats(shares, likes, comments) for a specific share/post/status update. This API requires setting permissions in your LoginRadius Dashboard.<br><br> The Trackable Status API is used to update the status on the user's wall and return an Post ID value. It is commonly referred to as Permission based sharing or Push notifications.<br><br> POST Input Parameter Format: application/x-www-form-urlencoded [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/trackable-status-posting/)
```
var accessToken = "<accessToken>"; //Required
var statusModel ={
"caption" : "<caption>",
"description" : "<description>",
"imageurl" : "<imageurl>",
"status" : "<status>",
"title" : "<title>",
"url" : "<url>"
}; //Required
LoginRadiusSDK.socialApi.trackableStatusPosting(accessToken, statusModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAlbums-get-"> Album (GET)</h6>
<b>Supported Providers:</b> Facebook, Google, Live, Vkontakte.<br><br> This API returns the photo albums associated with the passed in access tokens Social Profile. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/album/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getAlbums(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAlbumsWithCursor-get-"> Get Albums with cursor (GET)</h6>
<b>Supported Providers:</b> Facebook, Google, Live, Vkontakte.<br><br> This API returns the photo albums associated with the passed in access tokens Social Profile. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/album/)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getAlbumsWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAudios-get-"> Audio (GET)</h6>
The Audio API is used to get audio files data from the user's social account.<br><br><b>Supported Providers:</b> Live, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/audio)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getAudios(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAudiosWithCursor-get-"> Get Audio With Cursor (GET)</h6>
The Audio API is used to get audio files data from the user's social account.<br><br><b>Supported Providers:</b> Live, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/audio)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getAudiosWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetCheckIns-get-"> Check In (GET)</h6>
The Check In API is used to get check Ins data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Foursquare, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/check-in)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getCheckIns(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetCheckInsWithCursor-get-"> Get CheckIns With Cursor (GET)</h6>
The Check In API is used to get check Ins data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Foursquare, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/check-in)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getCheckInsWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetContacts-get-"> Contact (GET)</h6>
The Contact API is used to get contacts/friends/connections data from the user's social account.This is one of the APIs that makes up the LoginRadius Friend Invite System. The data will normalized into LoginRadius' standard data format. This API requires setting permissions in your LoginRadius Dashboard. <br><br><b>Note:</b> Facebook restricts access to the list of friends that is returned. When using the Contacts API with Facebook you will only receive friends that have accepted some permissions with your app. <br><br><b>Supported Providers:</b> Facebook, Foursquare, Google, LinkedIn, Live, Twitter, Vkontakte, Yahoo [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/contact)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Optional
LoginRadiusSDK.socialApi.getContacts(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetEvents-get-"> Event (GET)</h6>
The Event API is used to get the event data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Live [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/event)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getEvents(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetEventsWithCursor-get-"> Get Events With Cursor (GET)</h6>
The Event API is used to get the event data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Live [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/event)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getEventsWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetFollowings-get-"> Following (GET)</h6>
Get the following user list from the user's social account.<br><br><b>Supported Providers:</b> Twitter [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/following)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getFollowings(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetFollowingsWithCursor-get-"> Get Followings With Cursor (GET)</h6>
Get the following user list from the user's social account.<br><br><b>Supported Providers:</b> Twitter [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/following)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getFollowingsWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetGroups-get-"> Group (GET)</h6>
The Group API is used to get group data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/group)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getGroups(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetGroupsWithCursor-get-"> Get Groups With Cursor (GET)</h6>
The Group API is used to get group data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/group)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getGroupsWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetLikes-get-"> Like (GET)</h6>
The Like API is used to get likes data from the user's social account.<br><br><b>Supported Providers:</b> Facebook [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/like)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getLikes(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetLikesWithCursor-get-"> Get Likes With Cursor (GET)</h6>
The Like API is used to get likes data from the user's social account.<br><br><b>Supported Providers:</b> Facebook [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/like)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getLikesWithCursor(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetMentions-get-"> Mention (GET)</h6>
The Mention API is used to get mentions data from the user's social account.<br><br><b>Supported Providers:</b> Twitter [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/mention)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getMentions(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetPage-get-"> Page (GET)</h6>
The Page API is used to get the page data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, LinkedIn [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/page)
```
var accessToken = "<accessToken>"; //Required
var pageName = "<pageName>"; //Required
LoginRadiusSDK.socialApi.getPage(accessToken, pageName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetPhotos-get-"> Photo (GET)</h6>
The Photo API is used to get photo data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Foursquare, Google, Live, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/photo)
```
var accessToken = "<accessToken>"; //Required
var albumId = "<albumId>"; //Required
LoginRadiusSDK.socialApi.getPhotos(accessToken, albumId, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetPosts-get-"> Get Post (GET)</h6>
The Post API is used to get post message data from the user's social account.<br><br><b>Supported Providers:</b> Facebook [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/post)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.socialApi.getPosts(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetTrackableStatusStats-get-"> Get Trackable Status Stats (GET)</h6>
The Trackable status API works very similar to the Status API but it returns a Post id that you can use to track the stats(shares, likes, comments) for a specific share/post/status update. This API requires setting permissions in your LoginRadius Dashboard.<br><br> The Trackable Status API is used to update the status on the user's wall and return an Post ID value. It is commonly referred to as Permission based sharing or Push notifications. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/get-trackable-status-stats/)
```
var accessToken = "<accessToken>"; //Required
var caption = "<caption>"; //Required
var description = "<description>"; //Required
var imageurl = "<imageurl>"; //Required
var status = "<status>"; //Required
var title = "<title>"; //Required
var url = "<url>"; //Required
LoginRadiusSDK.socialApi.getTrackableStatusStats(accessToken, caption, description, imageurl, status, title, url, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetRefreshedSocialUserProfile-get-"> Refresh User Profile (GET)</h6>
The User Profile API is used to get the latest updated social profile data from the user's social account after authentication. The social profile will be retrieved via oAuth and OpenID protocols. The data is normalized into LoginRadius' standard data format. This API should be called using the access token retrieved from the refresh access token API. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/refresh-token/refresh-user-profile)
```
var accessToken = "<accessToken>"; //Required
var fields = null; //Optional
LoginRadiusSDK.socialApi.getRefreshedSocialUserProfile(accessToken, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetVideos-get-"> Video (GET)</h6>
The Video API is used to get video files data from the user's social account.<br><br><b>Supported Providers:</b> Facebook, Google, Live, Vkontakte [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/advanced-social-api/video)
```
var accessToken = "<accessToken>"; //Required
var nextCursor = "<nextCursor>"; //Required
LoginRadiusSDK.socialApi.getVideos(accessToken, nextCursor, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### CustomObject API
List of APIs in this Section:<br>
* PUT : [Custom Object Update by Access Token](#UpdateCustomObjectByToken-put-)<br>
* POST : [Create Custom Object by Token](#CreateCustomObjectByToken-post-)<br>
* GET : [Custom Object by Token](#GetCustomObjectByToken-get-)<br>
* GET : [Custom Object by ObjectRecordId and Token](#GetCustomObjectByRecordIDAndToken-get-)<br>
* DELETE : [Custom Object Delete by Record Id And Token](#DeleteCustomObjectByToken-delete-)<br>
<h6 id="UpdateCustomObjectByToken-put-"> Custom Object Update by Access Token (PUT)</h6>
This API is used to update the specified custom object data of the specified account. If the value of updatetype is 'replace' then it will fully replace custom object with the new custom object and if the value of updatetype is 'partialreplace' then it will perform an upsert type operation [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-object/custom-object-update-by-objectrecordid-and-token)
```
var accessToken = "<accessToken>"; //Required
var objectName = "<objectName>"; //Required
var objectRecordId = "<objectRecordId>"; //Required
var object = { "customdata1": "Store my customdata1 value" }; //Required
var updateType = "<updateType>"; //Optional
LoginRadiusSDK.customObjectApi.updateCustomObjectByToken(accessToken, objectName, objectRecordId, object, updateType, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="CreateCustomObjectByToken-post-"> Create Custom Object by Token (POST)</h6>
This API is used to write information in JSON format to the custom object for the specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-object/create-custom-object-by-token)
```
var accessToken = "<accessToken>"; //Required
var objectName = "<objectName>"; //Required
var object = { "customdata1": "Store my customdata1 value" }; //Required
LoginRadiusSDK.customObjectApi.createCustomObjectByToken(accessToken, objectName, object, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetCustomObjectByToken-get-"> Custom Object by Token (GET)</h6>
This API is used to retrieve the specified Custom Object data for the specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-object/custom-object-by-token)
```
var accessToken = "<accessToken>"; //Required
var objectName = "<objectName>"; //Required
LoginRadiusSDK.customObjectApi.getCustomObjectByToken(accessToken, objectName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetCustomObjectByRecordIDAndToken-get-"> Custom Object by ObjectRecordId and Token (GET)</h6>
This API is used to retrieve the Custom Object data for the specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-object/custom-object-by-objectrecordid-and-token)
```
var accessToken = "<accessToken>"; //Required
var objectName = "<objectName>"; //Required
var objectRecordId = "<objectRecordId>"; //Required
LoginRadiusSDK.customObjectApi.getCustomObjectByRecordIDAndToken(accessToken, objectName, objectRecordId, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="DeleteCustomObjectByToken-delete-"> Custom Object Delete by Record Id And Token (DELETE)</h6>
This API is used to remove the specified Custom Object data using ObjectRecordId of a specified account. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-object/custom-object-delete-by-objectrecordid-and-token)
```
var accessToken = "<accessToken>"; //Required
var objectName = "<objectName>"; //Required
var objectRecordId = "<objectRecordId>"; //Required
LoginRadiusSDK.customObjectApi.deleteCustomObjectByToken(accessToken, objectName, objectRecordId, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### PhoneAuthentication API
List of APIs in this Section:<br>
* PUT : [Phone Reset Password by OTP](#ResetPasswordByPhoneOTP-put-)<br>
* PUT : [Phone Verification OTP](#PhoneVerificationByOTP-put-)<br>
* PUT : [Phone Verification OTP by Token](#PhoneVerificationOTPByAccessToken-put-)<br>
* PUT : [Phone Number Update](#UpdatePhoneNumber-put-)<br>
* POST : [Phone Login](#LoginByPhone-post-)<br>
* POST : [Phone Forgot Password by OTP](#ForgotPasswordByPhoneOTP-post-)<br>
* POST : [Phone Resend Verification OTP](#PhoneResendVerificationOTP-post-)<br>
* POST : [Phone Resend Verification OTP By Token](#PhoneResendVerificationOTPByToken-post-)<br>
* POST : [Phone User Registration by SMS](#UserRegistrationByPhone-post-)<br>
* GET : [Phone Number Availability](#CheckPhoneNumberAvailability-get-)<br>
* DELETE : [Remove Phone ID by Access Token](#RemovePhoneIDByAccessToken-delete-)<br>
<h6 id="ResetPasswordByPhoneOTP-put-"> Phone Reset Password by OTP (PUT)</h6>
This API is used to reset the password [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-reset-password-by-otp)
```
var resetPasswordByOTPModel ={
"otp" : "<otp>",
"password" : "<<PASSWORD>>",
"phone" : "<phone>"
}; //Required
LoginRadiusSDK.phoneAuthenticationApi.resetPasswordByPhoneOTP(resetPasswordByOTPModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PhoneVerificationByOTP-put-"> Phone Verification OTP (PUT)</h6>
This API is used to validate the verification code sent to verify a user's phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-verify-otp)
```
var otp = "<otp>"; //Required
var phone = "<phone>"; //Required
var fields = null; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.phoneVerificationByOTP(otp, phone, fields, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PhoneVerificationOTPByAccessToken-put-"> Phone Verification OTP by Token (PUT)</h6>
This API is used to consume the verification code sent to verify a user's phone number. Use this call for front-end purposes in cases where the user is already logged in by passing the user's access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-verify-otp-by-token)
```
var accessToken = "<accessToken>"; //Required
var otp = "<otp>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.phoneVerificationOTPByAccessToken(accessToken, otp, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UpdatePhoneNumber-put-"> Phone Number Update (PUT)</h6>
This API is used to update the login Phone Number of users [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-number-update)
```
var accessToken = "<accessToken>"; //Required
var phone = "<phone>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.updatePhoneNumber(accessToken, phone, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="LoginByPhone-post-"> Phone Login (POST)</h6>
This API retrieves a copy of the user data based on the Phone [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-login)
```
var phoneAuthenticationModel ={
"password" : "<<PASSWORD>>",
"phone" : "<phone>"
}; //Required
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.loginByPhone(phoneAuthenticationModel, fields, loginUrl, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ForgotPasswordByPhoneOTP-post-"> Phone Forgot Password by OTP (POST)</h6>
This API is used to send the OTP to reset the account password. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-forgot-password-by-otp)
```
var phone = "<phone>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.forgotPasswordByPhoneOTP(phone, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PhoneResendVerificationOTP-post-"> Phone Resend Verification OTP (POST)</h6>
This API is used to resend a verification OTP to verify a user's Phone Number. The user will receive a verification code that they will need to input [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-resend-otp)
```
var phone = "<phone>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.phoneResendVerificationOTP(phone, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PhoneResendVerificationOTPByToken-post-"> Phone Resend Verification OTP By Token (POST)</h6>
This API is used to resend a verification OTP to verify a user's Phone Number in cases in which an active token already exists [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-resend-otp-by-token)
```
var accessToken = "<accessToken>"; //Required
var phone = "<phone>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.phoneResendVerificationOTPByToken(accessToken, phone, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="UserRegistrationByPhone-post-"> Phone User Registration by SMS (POST)</h6>
This API registers the new users into your Cloud Storage and triggers the phone verification process. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-user-registration-by-sms)
```
var authUserRegistrationModel ={
"firstName" : "<firstName>",
"lastName" : "<lastName>",
"password" : "<<PASSWORD>>",
"phoneId" : "<phoneId>"
}; //Required
var sott = "<sott>"; //Required
var fields = null; //Optional
var options = "<options>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.phoneAuthenticationApi.userRegistrationByPhone(authUserRegistrationModel, sott, fields, options, smsTemplate, verificationUrl, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="CheckPhoneNumberAvailability-get-"> Phone Number Availability (GET)</h6>
This API is used to check the Phone Number exists or not on your site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-number-availability)
```
var phone = "<phone>"; //Required
LoginRadiusSDK.phoneAuthenticationApi.checkPhoneNumberAvailability(phone, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="RemovePhoneIDByAccessToken-delete-"> Remove Phone ID by Access Token (DELETE)</h6>
This API is used to delete the Phone ID on a user's account via the access token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/remove-phone-id-by-access-token)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.phoneAuthenticationApi.removePhoneIDByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### MultiFactorAuthentication API
List of APIs in this Section:<br>
* PUT : [Update MFA Setting](#MFAUpdateSetting-put-)<br>
* PUT : [Update MFA by Access Token](#MFAUpdateByAccessToken-put-)<br>
* PUT : [MFA Update Phone Number by Token](#MFAUpdatePhoneNumberByToken-put-)<br>
* PUT : [Verify MFA Email OTP by Access Token](#MFAValidateEmailOtpByAccessToken-put-)<br>
* PUT : [Update MFA Security Question by Access Token](#MFASecurityQuestionAnswerByAccessToken-put-)<br>
* PUT : [MFA Validate OTP](#MFAValidateOTPByPhone-put-)<br>
* PUT : [MFA Validate Google Auth Code](#MFAValidateGoogleAuthCode-put-)<br>
* PUT : [MFA Validate Backup code](#MFAValidateBackupCode-put-)<br>
* PUT : [MFA Update Phone Number](#MFAUpdatePhoneNumber-put-)<br>
* PUT : [Verify MFA Email OTP by MFA Token](#MFAValidateEmailOtp-put-)<br>
* PUT : [Update MFA Security Question by MFA Token](#MFASecurityQuestionAnswer-put-)<br>
* POST : [MFA Email Login](#MFALoginByEmail-post-)<br>
* POST : [MFA UserName Login](#MFALoginByUserName-post-)<br>
* POST : [MFA Phone Login](#MFALoginByPhone-post-)<br>
* POST : [Send MFA Email OTP by MFA Token](#MFAEmailOTP-post-)<br>
* POST : [Verify MFA Security Question by MFA Token](#MFASecurityQuestionAnswerVerification-post-)<br>
* GET : [MFA Validate Access Token](#MFAConfigureByAccessToken-get-)<br>
* GET : [MFA Backup Code by Access Token](#MFABackupCodeByAccessToken-get-)<br>
* GET : [Reset Backup Code by Access Token](#MFAResetBackupCodeByAccessToken-get-)<br>
* GET : [Send MFA Email OTP by Access Token](#MFAEmailOtpByAccessToken-get-)<br>
* GET : [MFA Resend Otp](#MFAResendOTP-get-)<br>
* DELETE : [MFA Reset Google Authenticator by Token](#MFAResetGoogleAuthByToken-delete-)<br>
* DELETE : [MFA Reset SMS Authenticator by Token](#MFAResetSMSAuthByToken-delete-)<br>
* DELETE : [Reset MFA Email OTP Authenticator By Access Token](#MFAResetEmailOtpAuthenticatorByAccessToken-delete-)<br>
* DELETE : [MFA Reset Security Question Authenticator By Access Token](#MFAResetSecurityQuestionAuthenticatorByAccessToken-delete-)<br>
<h6 id="MFAUpdateSetting-put-"> Update MFA Setting (PUT)</h6>
This API is used to trigger the Multi-factor authentication settings after login for secure actions [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/sms-authenticator/update-mfa-setting/)
```
var accessToken = "<accessToken>"; //Required
var multiFactorAuthModelWithLockout ={
"otp" : "<otp>"
}; //Required
var fields = null; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaUpdateSetting(accessToken, multiFactorAuthModelWithLockout, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAUpdateByAccessToken-put-"> Update MFA by Access Token (PUT)</h6>
This API is used to Enable Multi-factor authentication by access token on user login [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/google-authenticator/update-mfa-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var multiFactorAuthModelByGoogleAuthenticatorCode ={
"googleAuthenticatorCode" : "<googleAuthenticatorCode>"
}; //Required
var fields = null; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaUpdateByAccessToken(accessToken, multiFactorAuthModelByGoogleAuthenticatorCode, fields, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAUpdatePhoneNumberByToken-put-"> MFA Update Phone Number by Token (PUT)</h6>
This API is used to update the Multi-factor authentication phone number by sending the verification OTP to the provided phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/sms-authenticator/mfa-update-phone-number-by-token/)
```
var accessToken = "<accessToken>"; //Required
var phoneNo2FA = "<phoneNo2FA>"; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaUpdatePhoneNumberByToken(accessToken, phoneNo2FA, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAValidateEmailOtpByAccessToken-put-"> Verify MFA Email OTP by Access Token (PUT)</h6>
This API is used to set up MFA Email OTP authenticator on profile after login. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/verify-mfa-otp-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var multiFactorAuthModelByEmailOtpWithLockout ={
"EmailId":"emailId",
"Otp":"otp"
}; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaValidateEmailOtpByAccessToken(accessToken, multiFactorAuthModelByEmailOtpWithLockout, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFASecurityQuestionAnswerByAccessToken-put-"> Update MFA Security Question by Access Token (PUT)</h6>
This API is used to set up MFA Security Question authenticator on profile after login. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/update-mfa-security-question-by-access-token)
```
var accessToken = "<accessToken>"; //Required
var securityQuestionAnswerModelByAccessToken ={
"securityquestionanswer": [
{
"QuestionId": "db7****8a73e4******bd9****8c20",
"Answer": "<answer>"
}
],
"ReplaceSecurityQuestionAnswer":true
}; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaSecurityQuestionAnswerByAccessToken(accessToken, securityQuestionAnswerModelByAccessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAValidateOTPByPhone-put-"> MFA Validate OTP (PUT)</h6>
This API is used to login via Multi-factor authentication by passing the One Time Password received via SMS [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/sms-authenticator/mfa-validate-otp/)
```
var multiFactorAuthModelWithLockout ={
"otp" : "<otp>"
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var fields = null; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaValidateOTPByPhone(multiFactorAuthModelWithLockout, secondFactorAuthenticationToken, fields, rbaBrowserEmailTemplate, rbaCityEmailTemplate, rbaCountryEmailTemplate, rbaIpEmailTemplate, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAValidateGoogleAuthCode-put-"> MFA Validate Google Auth Code (PUT)</h6>
This API is used to login via Multi-factor-authentication by passing the google authenticator code. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/google-authenticator/mfa-validate-google-auth-code/)
```
var googleAuthenticatorCode = "<googleAuthenticatorCode>"; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var fields = null; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaValidateGoogleAuthCode(googleAuthenticatorCode, secondFactorAuthenticationToken, fields, rbaBrowserEmailTemplate, rbaCityEmailTemplate, rbaCountryEmailTemplate, rbaIpEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAValidateBackupCode-put-"> MFA Validate Backup code (PUT)</h6>
This API is used to validate the backup code provided by the user and if valid, we return an access token allowing the user to login incases where Multi-factor authentication (MFA) is enabled and the secondary factor is unavailable. When a user initially downloads the Backup codes, We generate 10 codes, each code can only be consumed once. if any user attempts to go over the number of invalid login attempts configured in the Dashboard then the account gets blocked automatically [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/backup-codes/mfa-validate-backup-code/)
```
var multiFactorAuthModelByBackupCode ={
"backupCode" : "<backupCode>"
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var fields = null; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaValidateBackupCode(multiFactorAuthModelByBackupCode, secondFactorAuthenticationToken, fields, rbaBrowserEmailTemplate, rbaCityEmailTemplate, rbaCountryEmailTemplate, rbaIpEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAUpdatePhoneNumber-put-"> MFA Update Phone Number (PUT)</h6>
This API is used to update (if configured) the phone number used for Multi-factor authentication by sending the verification OTP to the provided phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/sms-authenticator/mfa-update-phone-number/)
```
var phoneNo2FA = "<phoneNo2FA>"; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaUpdatePhoneNumber(phoneNo2FA, secondFactorAuthenticationToken, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAValidateEmailOtp-put-"> Verify MFA Email OTP by MFA Token (PUT)</h6>
This API is used to Verify MFA Email OTP by MFA Token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/verify-mfa-email-otp-by-mfa-token/)
```
var multiFactorAuthModelByEmailOtp ={
"EmailId":"emailId",
"Otp":"otp"
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaValidateEmailOtp(multiFactorAuthModelByEmailOtp, secondFactorAuthenticationToken, rbaBrowserEmailTemplate, rbaCityEmailTemplate, rbaCountryEmailTemplate, rbaIpEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFASecurityQuestionAnswer-put-"> Update MFA Security Question by MFA Token (PUT)</h6>
This API is used to set the security questions on the profile with the MFA token when MFA flow is required. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/update-mfa-security-question-by-mfa-token/)
```
var securityQuestionAnswerUpdateModel ={
"securityquestionanswer": [
{
"QuestionId": "db7****8a73e4******bd9****8c20",
"Answer": "<answer>"
}
]
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaSecurityQuestionAnswer(securityQuestionAnswerUpdateModel, secondFactorAuthenticationToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFALoginByEmail-post-"> MFA Email Login (POST)</h6>
This API can be used to login by emailid on a Multi-factor authentication enabled LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/mfa-email-login)
```
var email = "<email>"; //Required
var password = "<<PASSWORD>>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaLoginByEmail(email, password, emailTemplate, fields, loginUrl, smsTemplate, smsTemplate2FA, verificationUrl,emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFALoginByUserName-post-"> MFA UserName Login (POST)</h6>
This API can be used to login by username on a Multi-factor authentication enabled LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/mfa-user-name-login)
```
var password = "<<PASSWORD>>"; //Required
var username = "<username>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaLoginByUserName(password, username, emailTemplate, fields, loginUrl, smsTemplate, smsTemplate2FA, verificationUrl,emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFALoginByPhone-post-"> MFA Phone Login (POST)</h6>
This API can be used to login by Phone on a Multi-factor authentication enabled LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/mfa-phone-login)
```
var password = "<<PASSWORD>>"; //Required
var phone = "<phone>"; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaLoginByPhone(password, phone, emailTemplate, fields, loginUrl, smsTemplate, smsTemplate2FA, verificationUrl,emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAEmailOTP-post-"> Send MFA Email OTP by MFA Token (POST)</h6>
An API designed to send the MFA Email OTP to the email. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/send-mfa-email-otp-by-mfa-token/)
```
var emailIdModel ={
"EmailId":"email"
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaEmailOTP(emailIdModel, secondFactorAuthenticationToken, emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFASecurityQuestionAnswerVerification-post-"> Verify MFA Security Question by MFA Token (POST)</h6>
This API is used to resending the verification OTP to the provided phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/verify-mfa-security-question-by-mfa-token/)
```
var securityQuestionAnswerUpdateModel ={
"securityquestionanswer": [
{
"QuestionId": "db7****8a73e4******bd9****8c20",
"Answer": "<answer>"
}
]
}; //Required
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaSecurityQuestionAnswerVerification(securityQuestionAnswerUpdateModel, secondFactorAuthenticationToken, rbaBrowserEmailTemplate, rbaCityEmailTemplate, rbaCountryEmailTemplate, rbaIpEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAConfigureByAccessToken-get-"> MFA Validate Access Token (GET)</h6>
This API is used to configure the Multi-factor authentication after login by using the access token when MFA is set as optional on the LoginRadius site. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/mfa-validate-access-token/)
```
var accessToken = "<accessToken>"; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaConfigureByAccessToken(accessToken, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFABackupCodeByAccessToken-get-"> MFA Backup Code by Access Token (GET)</h6>
This API is used to get a set of backup codes via access token to allow the user login on a site that has Multi-factor Authentication enabled in the event that the user does not have a secondary factor available. We generate 10 codes, each code can only be consumed once. If any user attempts to go over the number of invalid login attempts configured in the Dashboard then the account gets blocked automatically [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/backup-codes/mfa-backup-code-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaBackupCodeByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResetBackupCodeByAccessToken-get-"> Reset Backup Code by Access Token (GET)</h6>
API is used to reset the backup codes on a given account via the access token. This API call will generate 10 new codes, each code can only be consumed once [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/backup-codes/mfa-reset-backup-code-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResetBackupCodeByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAEmailOtpByAccessToken-get-"> Send MFA Email OTP by Access Token (GET)</h6>
This API is created to send the OTP to the email if email OTP authenticator is enabled in app's MFA configuration. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/send-mfa-email-otp-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var emailId = "<emailId>"; //Required
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaEmailOtpByAccessToken(accessToken, emailId, emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResendOTP-get-"> MFA Resend Otp (GET)</h6>
This API is used to resending the verification OTP to the provided phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/resend-twofactorauthentication-otp/)
```
var secondFactorAuthenticationToken = "<secondFactorAuthenticationToken>"; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResendOTP(secondFactorAuthenticationToken, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResetGoogleAuthByToken-delete-"> MFA Reset Google Authenticator by Token (DELETE)</h6>
This API Resets the Google Authenticator configurations on a given account via the access token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/google-authenticator/mfa-reset-google-authenticator-by-token/)
```
var accessToken = "<accessToken>"; //Required
var googleauthenticator = true; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResetGoogleAuthByToken(accessToken, googleauthenticator, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResetSMSAuthByToken-delete-"> MFA Reset SMS Authenticator by Token (DELETE)</h6>
This API resets the SMS Authenticator configurations on a given account via the access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/sms-authenticator/mfa-reset-sms-authenticator-by-token/)
```
var accessToken = "<accessToken>"; //Required
var otpauthenticator = true; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResetSMSAuthByToken(accessToken, otpauthenticator, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResetEmailOtpAuthenticatorByAccessToken-delete-"> Reset MFA Email OTP Authenticator By Access Token (DELETE)</h6>
This API is used to reset the Email OTP Authenticator settings for an MFA-enabled user [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/reset-mfa-email-otp-authenticator-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResetEmailOtpAuthenticatorByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAResetSecurityQuestionAuthenticatorByAccessToken-delete-"> MFA Reset Security Question Authenticator By Access Token (DELETE)</h6>
This API is used to Reset MFA Security Question Authenticator By Access Token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/reset-mfa-security-question-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.multiFactorAuthenticationApi.mfaResetSecurityQuestionAuthenticatorByAccessToken(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### PINAuthentication API
List of APIs in this Section:<br>
* PUT : [Reset PIN By ResetToken](#ResetPINByResetToken-put-)<br>
* PUT : [Reset PIN By SecurityAnswer And Email](#ResetPINByEmailAndSecurityAnswer-put-)<br>
* PUT : [Reset PIN By SecurityAnswer And Username](#ResetPINByUsernameAndSecurityAnswer-put-)<br>
* PUT : [Reset PIN By SecurityAnswer And Phone](#ResetPINByPhoneAndSecurityAnswer-put-)<br>
* PUT : [Change PIN By Token](#ChangePINByAccessToken-put-)<br>
* PUT : [Reset PIN by Phone and OTP](#ResetPINByPhoneAndOtp-put-)<br>
* PUT : [Reset PIN by Email and OTP](#ResetPINByEmailAndOtp-put-)<br>
* PUT : [Reset PIN by Username and OTP](#ResetPINByUsernameAndOtp-put-)<br>
* POST : [PIN Login](#PINLogin-post-)<br>
* POST : [Forgot PIN By Email](#SendForgotPINEmailByEmail-post-)<br>
* POST : [Forgot PIN By UserName](#SendForgotPINEmailByUsername-post-)<br>
* POST : [Forgot PIN By Phone](#SendForgotPINSMSByPhone-post-)<br>
* POST : [Set PIN By PinAuthToken](#SetPINByPinAuthToken-post-)<br>
* GET : [Invalidate PIN Session Token](#InValidatePinSessionToken-get-)<br>
<h6 id="ResetPINByResetToken-put-"> Reset PIN By ResetToken (PUT)</h6>
This API is used to reset pin using reset token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-resettoken/)
```
var resetPINByResetToken ={
"pin" : "<pin>",
"resetToken" : "<resetToken>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByResetToken(resetPINByResetToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByEmailAndSecurityAnswer-put-"> Reset PIN By SecurityAnswer And Email (PUT)</h6>
This API is used to reset pin using security question answer and email. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-securityanswer-and-email/)
```
var resetPINBySecurityQuestionAnswerAndEmailModel ={
"email" : "<email>",
"pin" : "<pin>",
"securityAnswer" : {"QuestionID":"Answer"}
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByEmailAndSecurityAnswer(resetPINBySecurityQuestionAnswerAndEmailModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByUsernameAndSecurityAnswer-put-"> Reset PIN By SecurityAnswer And Username (PUT)</h6>
This API is used to reset pin using security question answer and username. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-securityanswer-and-username/)
```
var resetPINBySecurityQuestionAnswerAndUsernameModel ={
"pin" : "<pin>",
"securityAnswer" : {"QuestionID":"Answer"},
"username" : "<username>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByUsernameAndSecurityAnswer(resetPINBySecurityQuestionAnswerAndUsernameModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByPhoneAndSecurityAnswer-put-"> Reset PIN By SecurityAnswer And Phone (PUT)</h6>
This API is used to reset pin using security question answer and phone. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-securityanswer-and-phone/)
```
var resetPINBySecurityQuestionAnswerAndPhoneModel ={
"phone" : "<phone>",
"pin" : "<pin>",
"securityAnswer" : {"QuestionID":"Answer"}
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByPhoneAndSecurityAnswer(resetPINBySecurityQuestionAnswerAndPhoneModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ChangePINByAccessToken-put-"> Change PIN By Token (PUT)</h6>
This API is used to change a user's PIN using access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/change-pin-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var changePINModel ={
"newPIN" : "<newPIN>",
"oldPIN" : "<oldPIN>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.changePINByAccessToken(accessToken, changePINModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByPhoneAndOtp-put-"> Reset PIN by Phone and OTP (PUT)</h6>
This API is used to reset pin using phoneId and OTP. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-phone-and-otp/)
```
var resetPINByPhoneAndOTPModel ={
"otp" : "<otp>",
"phone" : "<phone>",
"pin" : "<pin>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByPhoneAndOtp(resetPINByPhoneAndOTPModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByEmailAndOtp-put-"> Reset PIN by Email and OTP (PUT)</h6>
This API is used to reset pin using email and OTP. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-email-and-otp/)
```
var resetPINByEmailAndOtpModel ={
"email" : "<email>",
"otp" : "<otp>",
"pin" : "<pin>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByEmailAndOtp(resetPINByEmailAndOtpModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ResetPINByUsernameAndOtp-put-"> Reset PIN by Username and OTP (PUT)</h6>
This API is used to reset pin using username and OTP. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/reset-pin-by-username-and-otp/)
```
var resetPINByUsernameAndOtpModel ={
"otp" : "<otp>",
"pin" : "<pin>",
"username" : "<username>"
}; //Required
LoginRadiusSDK.pinAuthenticationApi.resetPINByUsernameAndOtp(resetPINByUsernameAndOtpModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PINLogin-post-"> PIN Login (POST)</h6>
This API is used to login a user by pin and session token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/login-by-pin/)
```
var loginByPINModel ={
"pin" : "<pin>"
}; //Required
var sessionToken = "<sessionToken>"; //Required
LoginRadiusSDK.pinAuthenticationApi.pinLogin(loginByPINModel, sessionToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SendForgotPINEmailByEmail-post-"> Forgot PIN By Email (POST)</h6>
This API sends the reset pin email to specified email address. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/forgot-pin-by-email/)
```
var forgotPINLinkByEmailModel ={
"email" : "<email>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var resetPINUrl = "<resetPINUrl>"; //Optional
LoginRadiusSDK.pinAuthenticationApi.sendForgotPINEmailByEmail(forgotPINLinkByEmailModel, emailTemplate, resetPINUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SendForgotPINEmailByUsername-post-"> Forgot PIN By UserName (POST)</h6>
This API sends the reset pin email using username. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/forgot-pin-by-username/)
```
var forgotPINLinkByUserNameModel ={
"userName" : "<userName>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var resetPINUrl = "<resetPINUrl>"; //Optional
LoginRadiusSDK.pinAuthenticationApi.sendForgotPINEmailByUsername(forgotPINLinkByUserNameModel, emailTemplate, resetPINUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SendForgotPINSMSByPhone-post-"> Forgot PIN By Phone (POST)</h6>
This API sends the OTP to specified phone number [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/forgot-pin-by-phone/)
```
var forgotPINOtpByPhoneModel ={
"phone" : "<phone>"
}; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.pinAuthenticationApi.sendForgotPINSMSByPhone(forgotPINOtpByPhoneModel, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SetPINByPinAuthToken-post-"> Set PIN By PinAuthToken (POST)</h6>
This API is used to change a user's PIN using Pin Auth token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/set-pin-by-pinauthtoken/)
```
var pinRequiredModel ={
"pin" : "<pin>"
}; //Required
var pinAuthToken = "<pinAuthToken>"; //Required
LoginRadiusSDK.pinAuthenticationApi.setPINByPinAuthToken(pinRequiredModel, pinAuthToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="InValidatePinSessionToken-get-"> Invalidate PIN Session Token (GET)</h6>
This API is used to invalidate pin session token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/pin-authentication/invalidate-pin-session-token/)
```
var sessionToken = "<sessionToken>"; //Required
LoginRadiusSDK.pinAuthenticationApi.inValidatePinSessionToken(sessionToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### ReAuthentication API
List of APIs in this Section:<br>
* PUT : [Validate MFA by OTP](#MFAReAuthenticateByOTP-put-)<br>
* PUT : [Validate MFA by Backup Code](#MFAReAuthenticateByBackupCode-put-)<br>
* PUT : [Validate MFA by Google Authenticator Code](#MFAReAuthenticateByGoogleAuth-put-)<br>
* PUT : [Validate MFA by Password](#MFAReAuthenticateByPassword-put-)<br>
* PUT : [MFA Re-authentication by PIN](#VerifyPINAuthentication-put-)<br>
* PUT : [MFA Re-authentication by Email OTP](#ReAuthValidateEmailOtp-put-)<br>
* POST : [MFA Re-authentication by Security Question](#ReAuthBySecurityQuestion-post-)<br>
* GET : [Multi Factor Re-Authenticate](#MFAReAuthenticate-get-)<br>
* GET : [Send MFA Re-auth Email OTP by Access Token](#ReAuthSendEmailOtp-get-)<br>
<h6 id="MFAReAuthenticateByOTP-put-"> Validate MFA by OTP (PUT)</h6>
This API is used to re-authenticate via Multi-factor authentication by passing the One Time Password received via SMS [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/re-authentication/mfa/re-auth-by-otp/)
```
var accessToken = "<accessToken>"; //Required
var reauthByOtpModel ={
"otp" : "<otp>"
}; //Required
LoginRadiusSDK.reAuthenticationApi.mfaReAuthenticateByOTP(accessToken, reauthByOtpModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAReAuthenticateByBackupCode-put-"> Validate MFA by Backup Code (PUT)</h6>
This API is used to re-authenticate by set of backup codes via access token on the site that has Multi-factor authentication enabled in re-authentication for the user that does not have the device [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/re-authentication/mfa/re-auth-by-backup-code/)
```
var accessToken = "<accessToken>"; //Required
var reauthByBackupCodeModel ={
"backupCode" : "<backupCode>"
}; //Required
LoginRadiusSDK.reAuthenticationApi.mfaReAuthenticateByBackupCode(accessToken, reauthByBackupCodeModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAReAuthenticateByGoogleAuth-put-"> Validate MFA by Google Authenticator Code (PUT)</h6>
This API is used to re-authenticate via Multi-factor-authentication by passing the google authenticator code [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/re-auth-by-google-authenticator-code)
```
var accessToken = "<accessToken>"; //Required
var reauthByGoogleAuthenticatorCodeModel ={
"googleAuthenticatorCode" : "<googleAuthenticatorCode>"
}; //Required
LoginRadiusSDK.reAuthenticationApi.mfaReAuthenticateByGoogleAuth(accessToken, reauthByGoogleAuthenticatorCodeModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAReAuthenticateByPassword-put-"> Validate MFA by Password (PUT)</h6>
This API is used to re-authenticate via Multi-factor-authentication by passing the password [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/re-auth-by-password)
```
var accessToken = "<accessToken>"; //Required
var passwordEventBasedAuthModelWithLockout ={
"password" : "<<PASSWORD>>"
}; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.reAuthenticationApi.mfaReAuthenticateByPassword(accessToken, passwordEventBasedAuthModelWithLockout, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="VerifyPINAuthentication-put-"> MFA Re-authentication by PIN (PUT)</h6>
This API is used to validate the triggered MFA authentication flow with a password. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/re-authentication/pin/re-auth-by-pin/)
```
var accessToken = "<accessToken>"; //Required
var pinAuthEventBasedAuthModelWithLockout ={
"pin" : "<pin>"
}; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.reAuthenticationApi.verifyPINAuthentication(accessToken, pinAuthEventBasedAuthModelWithLockout, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ReAuthValidateEmailOtp-put-"> MFA Re-authentication by Email OTP (PUT)</h6>
This API is used to validate the triggered MFA authentication flow with an Email OTP. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/mfa-re-auth-by-email-otp/)
```
var accessToken = "<accessToken>"; //Required
var reauthByEmailOtpModel ={
"EmailId":"email",
"otp": "otp"
}; //Required
LoginRadiusSDK.reAuthenticationApi.reAuthValidateEmailOtp(accessToken, reauthByEmailOtpModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ReAuthBySecurityQuestion-post-"> MFA Re-authentication by Security Question (POST)</h6>
This API is used to validate the triggered MFA re-authentication flow with security questions answers. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/mfa-re-authentication-by-security-question/)
```
var accessToken = "<accessToken>"; //Required
var securityQuestionAnswerUpdateModel ={
"securityquestionanswer": [
{
"QuestionId": "db7****8a73e4******bd9****8c20",
"Answer": "<answer>"
}
]
}; //Required
LoginRadiusSDK.reAuthenticationApi.reAuthBySecurityQuestion(accessToken, securityQuestionAnswerUpdateModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="MFAReAuthenticate-get-"> Multi Factor Re-Authenticate (GET)</h6>
This API is used to trigger the Multi-Factor Autentication workflow for the provided access token [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/re-auth-trigger/)
```
var accessToken = "<accessToken>"; //Required
var smsTemplate2FA = "<smsTemplate2FA>"; //Optional
LoginRadiusSDK.reAuthenticationApi.mfaReAuthenticate(accessToken, smsTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="ReAuthSendEmailOtp-get-"> Send MFA Re-auth Email OTP by Access Token (GET)</h6>
This API is used to send the MFA Email OTP to the email for Re-authentication [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/multi-factor-authentication/re-authentication/send-mfa-re-auth-email-otp-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var emailId = "<emailId>"; //Required
var emailTemplate2FA = "<emailTemplate2FA>"; //Optional
LoginRadiusSDK.reAuthenticationApi.reAuthSendEmailOtp(accessToken, emailId, emailTemplate2FA, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### ConsentManagement API
List of APIs in this Section:<br>
* PUT : [Update Consent By Access Token](#UpdateConsentProfileByAccessToken-put-)<br>
* POST : [Consent By ConsentToken](#SubmitConsentByConsentToken-post-)<br>
* POST : [Post Consent By Access Token](#SubmitConsentByAccessToken-post-)<br>
* GET : [Get Consent Log by Access Token](#GetConsentLogs-get-)<br>
* GET : [Get Verify Consent By Access Token](#VerifyConsentByAccessToken-get-)<br>
<h6 id="UpdateConsentProfileByAccessToken-put-"> Update Consent By Access Token (PUT)</h6>
This API is to update consents using access token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/consent-management/update-consent-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var consentUpdateModel ={
"consents" : [ {
"consentOptionId" : "<consentOptionId>" ,
"isAccepted" : true
} ]
}; //Required
LoginRadiusSDK.consentManagementApi.updateConsentProfileByAccessToken(accessToken, consentUpdateModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SubmitConsentByConsentToken-post-"> Consent By ConsentToken (POST)</h6>
This API is to submit consent form using consent token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/consent-management/consent-by-consent-token/)
```
var consentToken = "<consentToken>"; //Required
var consentSubmitModel ={
"data" : [ {
"consentOptionId" : "<consentOptionId>" ,
"isAccepted" : true
} ] ,
"events" : [ {
"event" : "<event>" ,
"isCustom" : true
} ]
}; //Required
LoginRadiusSDK.consentManagementApi.submitConsentByConsentToken(consentToken, consentSubmitModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SubmitConsentByAccessToken-post-"> Post Consent By Access Token (POST)</h6>
API to provide a way to end user to submit a consent form for particular event type. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/consent-management/consent-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var consentSubmitModel ={
"data" : [ {
"consentOptionId" : "<consentOptionId>" ,
"isAccepted" : true
} ] ,
"events" : [ {
"event" : "<event>" ,
"isCustom" : true
} ]
}; //Required
LoginRadiusSDK.consentManagementApi.submitConsentByAccessToken(accessToken, consentSubmitModel, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetConsentLogs-get-"> Get Consent Log by Access Token (GET)</h6>
This API is used to fetch consent logs. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/consent-management/consent-log-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
LoginRadiusSDK.consentManagementApi.getConsentLogs(accessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="VerifyConsentByAccessToken-get-"> Get Verify Consent By Access Token (GET)</h6>
This API is used to check if consent is submitted for a particular event or not. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/consent-management/verify-consent-by-access-token/)
```
var accessToken = "<accessToken>"; //Required
var event = "<event>"; //Required
var isCustom = true; //Required
LoginRadiusSDK.consentManagementApi.verifyConsentByAccessToken(accessToken, event, isCustom, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### SmartLogin API
List of APIs in this Section:<br>
* GET : [Smart Login Verify Token](#SmartLoginTokenVerification-get-)<br>
* GET : [Smart Login By Email](#SmartLoginByEmail-get-)<br>
* GET : [Smart Login By Username](#SmartLoginByUserName-get-)<br>
* GET : [Smart Login Ping](#SmartLoginPing-get-)<br>
<h6 id="SmartLoginTokenVerification-get-"> Smart Login Verify Token (GET)</h6>
This API verifies the provided token for Smart Login [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/smart-login/smart-login-verify-token/)
```
var verificationToken = "<verificationToken>"; //Required
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.smartLoginApi.smartLoginTokenVerification(verificationToken, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SmartLoginByEmail-get-"> Smart Login By Email (GET)</h6>
This API sends a Smart Login link to the user's Email Id. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/smart-login/smart-login-by-email)
```
var clientGuid = "<clientGuid>"; //Required
var email = "<email>"; //Required
var redirectUrl = "<redirectUrl>"; //Optional
var smartLoginEmailTemplate = "<smartLoginEmailTemplate>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.smartLoginApi.smartLoginByEmail(clientGuid, email, redirectUrl, smartLoginEmailTemplate, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SmartLoginByUserName-get-"> Smart Login By Username (GET)</h6>
This API sends a Smart Login link to the user's Email Id. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/smart-login/smart-login-by-username)
```
var clientGuid = "<clientGuid>"; //Required
var username = "<username>"; //Required
var redirectUrl = "<redirectUrl>"; //Optional
var smartLoginEmailTemplate = "<smartLoginEmailTemplate>"; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.smartLoginApi.smartLoginByUserName(clientGuid, username, redirectUrl, smartLoginEmailTemplate, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="SmartLoginPing-get-"> Smart Login Ping (GET)</h6>
This API is used to check if the Smart Login link has been clicked or not [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/smart-login/smart-login-ping)
```
var clientGuid = "<clientGuid>"; //Required
var fields = null; //Optional
LoginRadiusSDK.smartLoginApi.smartLoginPing(clientGuid, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### OneTouchLogin API
List of APIs in this Section:<br>
* PUT : [One Touch OTP Verification](#OneTouchLoginOTPVerification-put-)<br>
* POST : [One Touch Login by Email](#OneTouchLoginByEmail-post-)<br>
* POST : [One Touch Login by Phone](#OneTouchLoginByPhone-post-)<br>
* GET : [One Touch Email Verification](#OneTouchEmailVerification-get-)<br>
* GET : [One Touch Login Ping](#OneTouchLoginPing-get-)<br>
<h6 id="OneTouchLoginOTPVerification-put-"> One Touch OTP Verification (PUT)</h6>
This API is used to verify the otp for One Touch Login. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/one-touch-login/one-touch-otp-verification/)
```
var otp = "<otp>"; //Required
var phone = "<phone>"; //Required
var fields = null; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.oneTouchLoginApi.oneTouchLoginOTPVerification(otp, phone, fields, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="OneTouchLoginByEmail-post-"> One Touch Login by Email (POST)</h6>
This API is used to send a link to a specified email for a frictionless login/registration [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/one-touch-login/one-touch-login-by-email-captcha/)
```
var oneTouchLoginByEmailModel ={
"clientguid" : "<clientguid>",
"email" : "<email>",
"g-recaptcha-response" : "<g-recaptcha-response>"
}; //Required
var oneTouchLoginEmailTemplate = "<oneTouchLoginEmailTemplate>"; //Optional
var redirecturl = "<redirecturl>"; //Optional
var welcomeemailtemplate = "<welcomeemailtemplate>"; //Optional
LoginRadiusSDK.oneTouchLoginApi.oneTouchLoginByEmail(oneTouchLoginByEmailModel, oneTouchLoginEmailTemplate, redirecturl, welcomeemailtemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="OneTouchLoginByPhone-post-"> One Touch Login by Phone (POST)</h6>
This API is used to send one time password to a given phone number for a frictionless login/registration. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/one-touch-login/one-touch-login-by-phone-captcha/)
```
var oneTouchLoginByPhoneModel ={
"g-recaptcha-response" : "<g-recaptcha-response>",
"phone" : "<phone>"
}; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.oneTouchLoginApi.oneTouchLoginByPhone(oneTouchLoginByPhoneModel, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="OneTouchEmailVerification-get-"> One Touch Email Verification (GET)</h6>
This API verifies the provided token for One Touch Login [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/one-touch-login/one-touch-email-verification)
```
var verificationToken = "<verificationToken>"; //Required
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.oneTouchLoginApi.oneTouchEmailVerification(verificationToken, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="OneTouchLoginPing-get-"> One Touch Login Ping (GET)</h6>
This API is used to check if the One Touch Login link has been clicked or not. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/one-touch-login/one-touch-login-ping/)
```
var clientGuid = "<clientGuid>"; //Required
var fields = null; //Optional
LoginRadiusSDK.oneTouchLoginApi.oneTouchLoginPing(clientGuid, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### PasswordLessLogin API
List of APIs in this Section:<br>
* PUT : [Passwordless Login Phone Verification](#PasswordlessLoginPhoneVerification-put-)<br>
* POST : [Passwordless Login Verification By Email And OTP](#PasswordlessLoginVerificationByEmailAndOTP-post-)<br>
* POST : [Passwordless Login Verification By User Name And OTP](#PasswordlessLoginVerificationByUserNameAndOTP-post-)<br>
* GET : [Passwordless Login by Phone](#PasswordlessLoginByPhone-get-)<br>
* GET : [Passwordless Login By Email](#PasswordlessLoginByEmail-get-)<br>
* GET : [Passwordless Login By UserName](#PasswordlessLoginByUserName-get-)<br>
* GET : [Passwordless Login Verification](#PasswordlessLoginVerification-get-)<br>
<h6 id="PasswordlessLoginPhoneVerification-put-"> Passwordless Login Phone Verification (PUT)</h6>
This API verifies an account by OTP and allows the customer to login. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-phone-verification)
```
var passwordLessLoginOtpModel ={
"otp" : "<otp>",
"phone" : "<phone>"
}; //Required
var fields = null; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginPhoneVerification(passwordLessLoginOtpModel, fields, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginVerificationByEmailAndOTP-post-">Passwordless Login Verification By Email And OTP (POST)</h6>
This API is used to verify the otp sent to the email when doing a passwordless login. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-verify-by-email-and-otp/)
```
var passwordLessLoginByEmailAndOtpModel ={
"email": "<email>",
"otp": "<otp>",
"welcomeemailtemplate": "<welcome_email_template>"
}; //Required
var fields = null; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginVerificationByEmailAndOTP(passwordLessLoginByEmailAndOtpModel, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginVerificationByUserNameAndOTP-post-">Passwordless Login Verification By User Name And OTP (POST)</h6>
This API is used to verify the otp sent to the email when doing a passwordless [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-verify-by-username-and-otp/)
```
var passwordLessLoginByUserNameAndOtpModel ={
"username": "<email>",
"otp": "<otp>",
"welcomeemailtemplate": "<welcome_email_template>"
}; //Required
var fields = null; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginVerificationByUserNameAndOTP(passwordLessLoginByUserNameAndOtpModel, fields, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginByPhone-get-"> Passwordless Login by Phone (GET)</h6>
API can be used to send a One-time Passcode (OTP) provided that the account has a verified PhoneID [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-by-phone)
```
var phone = "<phone>"; //Required
var smsTemplate = "<smsTemplate>"; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginByPhone(phone, smsTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginByEmail-get-"> Passwordless Login By Email (GET)</h6>
This API is used to send a Passwordless Login verification link to the provided Email ID [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-by-email)
```
var email = "<email>"; //Required
var passwordLessLoginTemplate = "<passwordLessLoginTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginByEmail(email, passwordLessLoginTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginByUserName-get-"> Passwordless Login By UserName (GET)</h6>
This API is used to send a Passwordless Login Verification Link to a customer by providing their UserName [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-by-username)
```
var username = "<username>"; //Required
var passwordLessLoginTemplate = "<passwordLessLoginTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginByUserName(username, passwordLessLoginTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="PasswordlessLoginVerification-get-"> Passwordless Login Verification (GET)</h6>
This API is used to verify the Passwordless Login verification link. Note: If you are using Passwordless Login by Phone you will need to use the Passwordless Login Phone Verification API [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/passwordless-login/passwordless-login-verification)
```
var verificationToken = "<verificationToken>"; //Required
var fields = null; //Optional
var welcomeEmailTemplate = "<welcomeEmailTemplate>"; //Optional
LoginRadiusSDK.passwordLessLoginApi.passwordlessLoginVerification(verificationToken, fields, welcomeEmailTemplate, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### Configuration API
List of APIs in this Section:<br>
* GET : [Get Server Time](#GetServerInfo-get-)<br>
* GET : [Get Configurations](#getConfigurations-get-)<br>
<h6 id="GetServerInfo-get-"> Get Server Time (GET)</h6>
This API allows you to query your LoginRadius account for basic server information and server time information which is useful when generating an SOTT token. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/configuration/get-server-time/)
```
var timeDifference = 0; //Optional
LoginRadiusSDK.configurationApi.getServerInfo(timeDifference, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="getConfigurations-get-"> Get Configuration (GET)</h6>
This API is used to get the configurations which are set in the LoginRadius Admin Console for a particular LoginRadius site/environment. [More info](https://www.loginradius.com/docs/api/v2/customer-identity-api/configuration/get-configurations)
```
LoginRadiusSDK.configurationApi.getConfigurations(function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### CustomRegistrationData API
List of APIs in this Section:<br>
* POST : [Validate secret code](#ValidateRegistrationDataCode-post-)<br>
* GET : [Auth Get Registration Data Server](#AuthGetRegistrationData-get-)<br>
<h6 id="ValidateRegistrationDataCode-post-"> Validate secret code (POST)</h6>
This API allows you to validate code for a particular dropdown member. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-registration-data/validate-code)
```
var code = "<code>"; //Required
var recordId = "<recordId>"; //Required
LoginRadiusSDK.customRegistrationDataApi.validateRegistrationDataCode(code, recordId, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="AuthGetRegistrationData-get-"> Auth Get Registration Data Server (GET)</h6>
This API is used to retrieve dropdown data. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/custom-registration-data/auth-get-registration-data)
```
var type = "<type>"; //Required
var limit = 0; //Optional
var parentId = "<parentId>"; //Optional
var skip = 0; //Optional
LoginRadiusSDK.customRegistrationDataApi.authGetRegistrationData(type, limit, parentId, skip, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### RiskBasedAuthentication API
List of APIs in this Section:<br>
* POST : [Risk Based Authentication Login by Email](#RBALoginByEmail-post-)<br>
* POST : [Risk Based Authentication Login by Username](#RBALoginByUserName-post-)<br>
* POST : [Risk Based Authentication Phone Login](#RBALoginByPhone-post-)<br>
<h6 id="RBALoginByEmail-post-"> Risk Based Authentication Login by Email (POST)</h6>
This API retrieves a copy of the user data based on the Email [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-login-by-email)
```
var emailAuthenticationModel ={
"email" : "<email>",
"password" : "<<PASSWORD>>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var passwordDelegation = true; //Optional
var passwordDelegationApp = "<passwordDelegationApp>"; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaBrowserSmsTemplate = "<rbaBrowserSmsTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCitySmsTemplate = "<rbaCitySmsTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaCountrySmsTemplate = "<rbaCountrySmsTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
var rbaIpSmsTemplate = "<rbaIpSmsTemplate>"; //Optional
var rbaOneclickEmailTemplate = "<rbaOneclickEmailTemplate>"; //Optional
var rbaOTPSmsTemplate = "<rbaOTPSmsTemplate>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.riskBasedAuthenticationApi.rbaLoginByEmail(emailAuthenticationModel, emailTemplate, fields, loginUrl, passwordDelegation, passwordDelegationApp, rbaBrowserEmailTemplate, rbaBrowserSmsTemplate, rbaCityEmailTemplate, rbaCitySmsTemplate, rbaCountryEmailTemplate, rbaCountrySmsTemplate, rbaIpEmailTemplate, rbaIpSmsTemplate, rbaOneclickEmailTemplate, rbaOTPSmsTemplate, smsTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="RBALoginByUserName-post-"> Risk Based Authentication Login by Username (POST)</h6>
This API retrieves a copy of the user data based on the Username [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/authentication/auth-login-by-username)
```
var userNameAuthenticationModel ={
"password" : "<<PASSWORD>>",
"username" : "<username>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var passwordDelegation = true; //Optional
var passwordDelegationApp = "<passwordDelegationApp>"; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaBrowserSmsTemplate = "<rbaBrowserSmsTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCitySmsTemplate = "<rbaCitySmsTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaCountrySmsTemplate = "<rbaCountrySmsTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
var rbaIpSmsTemplate = "<rbaIpSmsTemplate>"; //Optional
var rbaOneclickEmailTemplate = "<rbaOneclickEmailTemplate>"; //Optional
var rbaOTPSmsTemplate = "<rbaOTPSmsTemplate>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.riskBasedAuthenticationApi.rbaLoginByUserName(userNameAuthenticationModel, emailTemplate, fields, loginUrl, passwordDelegation, passwordDelegationApp, rbaBrowserEmailTemplate, rbaBrowserSmsTemplate, rbaCityEmailTemplate, rbaCitySmsTemplate, rbaCountryEmailTemplate, rbaCountrySmsTemplate, rbaIpEmailTemplate, rbaIpSmsTemplate, rbaOneclickEmailTemplate, rbaOTPSmsTemplate, smsTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="RBALoginByPhone-post-"> Risk Based Authentication Phone Login (POST)</h6>
This API retrieves a copy of the user data based on the Phone [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/phone-authentication/phone-login)
```
var phoneAuthenticationModel ={
"password" : "<<PASSWORD>>",
"phone" : "<phone>"
}; //Required
var emailTemplate = "<emailTemplate>"; //Optional
var fields = null; //Optional
var loginUrl = "<loginUrl>"; //Optional
var passwordDelegation = true; //Optional
var passwordDelegationApp = "<passwordDelegationApp>"; //Optional
var rbaBrowserEmailTemplate = "<rbaBrowserEmailTemplate>"; //Optional
var rbaBrowserSmsTemplate = "<rbaBrowserSmsTemplate>"; //Optional
var rbaCityEmailTemplate = "<rbaCityEmailTemplate>"; //Optional
var rbaCitySmsTemplate = "<rbaCitySmsTemplate>"; //Optional
var rbaCountryEmailTemplate = "<rbaCountryEmailTemplate>"; //Optional
var rbaCountrySmsTemplate = "<rbaCountrySmsTemplate>"; //Optional
var rbaIpEmailTemplate = "<rbaIpEmailTemplate>"; //Optional
var rbaIpSmsTemplate = "<rbaIpSmsTemplate>"; //Optional
var rbaOneclickEmailTemplate = "<rbaOneclickEmailTemplate>"; //Optional
var rbaOTPSmsTemplate = "<rbaOTPSmsTemplate>"; //Optional
var smsTemplate = "<smsTemplate>"; //Optional
var verificationUrl = "<verificationUrl>"; //Optional
LoginRadiusSDK.riskBasedAuthenticationApi.rbaLoginByPhone(phoneAuthenticationModel, emailTemplate, fields, loginUrl, passwordDelegation, passwordDelegationApp, rbaBrowserEmailTemplate, rbaBrowserSmsTemplate, rbaCityEmailTemplate, rbaCitySmsTemplate, rbaCountryEmailTemplate, rbaCountrySmsTemplate, rbaIpEmailTemplate, rbaIpSmsTemplate, rbaOneclickEmailTemplate, rbaOTPSmsTemplate, smsTemplate, verificationUrl, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### NativeSocial API
List of APIs in this Section:<br>
* GET : [Access Token via Facebook Token](#GetAccessTokenByFacebookAccessToken-get-)<br>
* GET : [Access Token via Twitter Token](#GetAccessTokenByTwitterAccessToken-get-)<br>
* GET : [Access Token via Google Token](#GetAccessTokenByGoogleAccessToken-get-)<br>
* GET : [Access Token using google JWT token for Native Mobile Login](#GetAccessTokenByGoogleJWTAccessToken-get-)<br>
* GET : [Access Token via Linkedin Token](#GetAccessTokenByLinkedinAccessToken-get-)<br>
* GET : [Get Access Token By Foursquare Access Token](#GetAccessTokenByFoursquareAccessToken-get-)<br>
* GET : [Access Token via Apple Id Code](#GetAccessTokenByAppleIdCode-get-)<br>
* GET : [Access Token via WeChat Code](#GetAccessTokenByWeChatCode-get-)<br>
* GET : [Access Token via Vkontakte Token](#GetAccessTokenByVkontakteAccessToken-get-)<br>
* GET : [Access Token via Google AuthCode](#GetAccessTokenByGoogleAuthCode-get-)<br>
<h6 id="GetAccessTokenByFacebookAccessToken-get-"> Access Token via Facebook Token (GET)</h6>
The API is used to get LoginRadius access token by sending Facebook's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-facebook-token/)
```
var fbAccessToken = "<fbAccessToken>"; //Required
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByFacebookAccessToken(fbAccessToken, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByTwitterAccessToken-get-"> Access Token via Twitter Token (GET)</h6>
The API is used to get LoginRadius access token by sending Twitter's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-twitter-token)
```
var twAccessToken = "<twAccessToken>"; //Required
var twTokenSecret = "<twTokenSecret>"; //Required
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByTwitterAccessToken(twAccessToken, twTokenSecret, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByGoogleAccessToken-get-"> Access Token via Google Token (GET)</h6>
The API is used to get LoginRadius access token by sending Google's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-google-token)
```
var googleAccessToken = "<googleAccessToken>"; //Required
var clientId = "<clientId>"; //Optional
var refreshToken = "<refreshToken>"; //Optional
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByGoogleAccessToken(googleAccessToken, clientId, refreshToken, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByGoogleJWTAccessToken-get-"> Access Token using google JWT token for Native Mobile Login (GET)</h6>
This API is used to Get LoginRadius Access Token using google jwt id token for google native mobile login/registration. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-googlejwt)
```
var idToken = "<idToken>"; //Required
LoginRadiusSDK.nativeSocialApi.getAccessTokenByGoogleJWTAccessToken(idToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByLinkedinAccessToken-get-"> Access Token via Linkedin Token (GET)</h6>
The API is used to get LoginRadius access token by sending Linkedin's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-linkedin-token/)
```
var lnAccessToken = "<lnAccessToken>"; //Required
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByLinkedinAccessToken(lnAccessToken, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByFoursquareAccessToken-get-"> Get Access Token By Foursquare Access Token (GET)</h6>
The API is used to get LoginRadius access token by sending Foursquare's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-foursquare-token/)
```
var fsAccessToken = "<fsAccessToken>"; //Required
LoginRadiusSDK.nativeSocialApi.getAccessTokenByFoursquareAccessToken(fsAccessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByAppleIdCode-get-"> Access Token via Apple Id Code (GET)</h6>
The API is used to get LoginRadius access token by sending a valid Apple ID OAuth Code. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-apple-id-code)
```
var code = "<code>"; //Required
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByAppleIdCode(code, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByWeChatCode-get-"> Access Token via WeChat Code (GET)</h6>
This API is used to retrieve a LoginRadius access token by passing in a valid WeChat OAuth Code. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-wechat-code)
```
var code = "<code>"; //Required
LoginRadiusSDK.nativeSocialApi.getAccessTokenByWeChatCode(code, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByVkontakteAccessToken-get-"> Access Token via Vkontakte Token (GET)</h6>
The API is used to get LoginRadius access token by sending Vkontakte's access token. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-vkontakte-token)
```
var vkAccessToken = "<vkAccessToken>"; //Required
LoginRadiusSDK.nativeSocialApi.getAccessTokenByVkontakteAccessToken(vkAccessToken, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
<h6 id="GetAccessTokenByGoogleAuthCode-get-"> Access Token via Google AuthCode (GET)</h6>
The API is used to get LoginRadius access token by sending Google's AuthCode. It will be valid for the specific duration of time specified in the response. [More Info](https://www.loginradius.com/docs/api/v2/customer-identity-api/social-login/native-social-login-api/access-token-via-google-auth-code)
```
var googleAuthcode = "<googleAuthcode>"; //Required
var socialAppName = "<socialAppName>"; //Optional
LoginRadiusSDK.nativeSocialApi.getAccessTokenByGoogleAuthCode(googleAuthcode, socialAppName, function(error, data){
if(error){
console.log(error);
return;
}
console.log(data);
});
```
### Demo <br/>
We have a demo web application using the HTML 5 SDK, which includes the following features:
* Traditional email login
* Multi-Factor login
* Passwordless login
* Social login
* Register
* Email verification
* Forgot password
* Reset password
* Change password
* Update account
* Account Linking
* Custom object management <br/>
You can get a copy of our demo project at [Github](https://github.com/LoginRadius/html5-sdk) .
### Demo Configuration
1. Set your LoginRadius ApiKey & other credential in `demo/assets/js/options.js`
<file_sep>/demo/assets/js/account.js
var stringVariable = window.location.href;
domainName = stringVariable.substring(0, stringVariable.lastIndexOf('/'));
$(function () {
getProfileByUid();
handleUpdateAccount();
});
function getProfileByUid() {
$("#lr-loading").show();
var token = LoginRadiusSDK.getToken();
LoginRadiusSDK.authenticationApi.getProfileByAccessToken(token, null,
null, null, null, function (error, data) {
$("#lr-loading").hide();
if(error){
console.log(error);
return;
}
if (typeof (data.FirstName) != "undefined" && data.FirstName !== null) {
$("#user-updateaccount-firstname").val(data.FirstName);
localStorage.setItem('UserName', data.FullName);
}
if (typeof (data.LastName) != "undefined" && data.LastName !== null) {
$("#user-updateaccount-lastname").val(data.LastName);
localStorage.setItem('UserName', data.FullName);
}
if (typeof (data.About) != "undefined" && data.About !== null) {
$("#user-updateaccount-about").val(data.About);
}
})
}
function handleUpdateAccount() {
$('#btn-user-updateaccount').on('click', function () {
$("#user-updateaccount-errorMsg").text("");
$("#user-updateaccount-successMsg").text("");
$("#lr-loading").show();
var userProfileUpdateModel = {
firstname: $("#user-updateaccount-firstname").val(),
lastname: $("#user-updateaccount-lastname").val(),
about: $("#user-updateaccount-about").val()
};
var emailTemplate = "";
var fields = "";
var nullSupport = "";
var smsTemplate = "";
var verificationUrl = "";
var lrToken = LoginRadiusSDK.getToken();
LoginRadiusSDK.authenticationApi.updateProfileByAccessToken(lrToken,userProfileUpdateModel,
emailTemplate, fields, nullSupport, smsTemplate, verificationUrl, function (error, data) {
$("#lr-loading").hide();
if(error){
console.log(error);
$("#user-updateaccount-errorMsg").text("Something went wrong.");
return;
}
if (typeof (data.Data.FullName) != "undefined" && data.Data.FullName !== null) {
localStorage.setItem('UserName', data.Data.FullName);
}else{
localStorage.setItem('UserName', '');
}
$("#user-updateaccount-successMsg").html("Account has been updated.");
})
});
}
|
c3d31cc2e29670c124543b0d1f542685e17c604c
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
LoginRadius/html5-sdk
|
762f5bed31d0bd7ed8376dbeb4a65188893c9ce2
|
7001f6b70521a0a4dd5e32b6af1bd1f8c1ae9911
|
refs/heads/master
|
<file_sep>package org.irods.jargon.core.pub;
import java.util.List;
import org.irods.jargon.core.exception.DataNotFoundException;
import org.irods.jargon.core.exception.DuplicateDataException;
import org.irods.jargon.core.exception.InvalidUserException;
import org.irods.jargon.core.exception.JargonException;
import org.irods.jargon.core.pub.domain.AvuData;
import org.irods.jargon.core.pub.domain.User;
/**
* Interface for an object to interact with user data in IRODS.
*
* @author <NAME>, DICE (www.irods.org)
*
*/
public interface UserAO extends IRODSAccessObject {
/**
* Add the given user to iRODS
*
* @param user
* {@link org.irods.jargon.core.pub.domain.User} with information
* on the user to be added.
* @return {@link User} that is the result for updates
* @throws JargonException
* @throws DuplicateDataException
* thrown if the user already exists.
*/
User addUser(User user) throws JargonException, DuplicateDataException;
/**
* List all users.
*
* @return {@code List} of
* {@link org.irods.jargon.core.pub.domain.User}
* @throws JargonException
*/
List<User> findAll() throws JargonException;
/**
* Query users and return the {@code User} object with the given user
* name. Note that user names may be given in user#zone format, and that
* federated user registered on the current zone will be returned.
* <p>
* For example, if I have zone1 and zone2, and zone1 has registered
* user1#zone2 as a user in zone1, then this method will get the information
* that zone1 has on the user name user#zone2.
* <p>
* This is distinct from going to zone2, and asking for information on the
* user user1#zone2.
*
* @param name
* {@code String} with the name of the user to query.
* @return {@link org.irods.jargon.core.pub.domain.User} that is the result
* of the query
* @throws JargonException
* @throws DataNotFoundException
* if user does not exist.
*/
User findByName(String name) throws JargonException, DataNotFoundException;
/**
* Query users by the unique id assigned by iRODS (database unique key).
* This will default to searching the current zone
*
* @param userId
* {@code String} with the unique database key for the user.
* @return {@link org.irods.jargon.core.pub.domain.User}
* @throws JargonException
* @throws DataNotFoundException
* if the user does not exist
*/
User findById(final String userId) throws JargonException,
DataNotFoundException;
/**
* Query users by the unique id assigned by iRODS (database unique key) in a
* zone.
* <p>
* This will, if the given zone is not the same as the current zone,
* initiate a cross-zone query and retrieve the information from the given
* zone name.
*
* @param userId
* {@code String} with the unique database key for the user.
* @return {@link org.irods.jargon.core.pub.domain.User}
* @throws JargonException
* @throws DataNotFoundException
* if the user does not exist
*/
User findByIdInZone(String userId, String zone) throws JargonException,
DataNotFoundException;
/**
* Query the AVU metadata associated with the given user by Id.
*
* @param userId
* {@code String} with the unique database key for the user.
* @return {@code List} of
* {@link org.irods.jargon.core.pub.domain.AvuData} with query
* results.
* @throws JargonException
*/
List<AvuData> listUserMetadataForUserId(String userId)
throws JargonException;
/**
* Query the AVU metadata associated with the given user by user name.
*
* @param userName
* {@code String} with the user name for the user.
* @return {@code List} of
* {@link org.irods.jargon.core.pub.domain.AvuData} with query
* results.
* @throws JargonException
*/
List<AvuData> listUserMetadataForUserName(String userName)
throws JargonException;
/**
* Remove the user from iRODS.
*
* @param userName
* {@code String} with the iRODS user name to be removed.
* @throws InvalidUserException
* if the user is not in iRODS
* @throws JargonException
*/
void deleteUser(String userName) throws InvalidUserException,
JargonException;
/**
* Update the user data. Note that this method only updates certain
* accessible fields. The method will compare the provided user data with
* the current data within iRODS, and will update the deltas.
*
* @param user
* {@link org.irods.jargon.core.pub.domain.User} with the updated
* data.
* @throws JargonException
* @throws DataNotFoundException
* if user is not found.
*/
void updateUser(User user) throws JargonException, DataNotFoundException;
/**
* Select user objects given an arbitrary 'where' clause.
*
* @param whereStatement
* {@code String} containing iquest syntax for a where
* statement, does not include the actual {@code Where}
* @return {@code List<User>} containing users that match the given
* query
* @throws JargonException
*/
List<User> findWhere(String whereStatement) throws JargonException;
/**
* Change the password for the given user. This method is used for a user
* changing their own password. Jargon will use an obfuscation routine to
* send the new password to iRODS.
*
* @param userName
* {@code String} with the name of the user.
* @param currentPassword
* {@code String} with the password that currently exists.
* @param newPassword
* {@code String} with the new password value.
* @throws JargonException
*/
void changeAUserPasswordByThatUser(String userName, String currentPassword,
String newPassword) throws JargonException;
/**
* Change the password for a given user. This method is used by an admin
* setting the password for an arbitrary user. For a user changing their own
* password, use the {@code changeAPasswordByThatUser(String, String)}
* method
*
* @param userName
* {@code String} with the user name whose password will
* change.
* @param newPassword
* {@code String} with the password to set for the given
* user.
* @throws JargonException
*/
void changeAUserPasswordByAnAdmin(String userName, String newPassword)
throws JargonException;
/**
* Add the AVU metadata for the given user. This is only possible when a
* rods admin.
*
* @param userName
* {@code String} with the user name to whom the AVU
* metadata will be added
* @param avuData
* {@link AvuData} to be added for the user
* @throws JargonException
*/
void addAVUMetadata(String userName, AvuData avuData)
throws JargonException;
/**
* Remove the given AVU metadata from the user. This is only possible when a
* rods admin.
*
* @param userName
* {@code String} with the user name from whom the AVU
* metadata will be removed
* @param avuData
* {@link AvuData} to be removed from the user
* @throws DataNotFoundException
* @throws JargonException
*/
void deleteAVUMetadata(String userName, AvuData avuData)
throws DataNotFoundException, JargonException;
/**
* Modify the given AVU metadata from the user. This is only possible when a
* rods admin.
*
* @param userName
* {@code String} with the user name from whom the AVU
* metadata will be removed
* @param avuData
* {@link AvuData} to be modified
* @throws DataNotFoundException
* @throws JargonException
*/
void modifyAVUMetadata(String userName, AvuData avuData)
throws DataNotFoundException, JargonException;
/**
* For a given partial user name, return the user names that are like that
* one. This is handy for creating auto-complete data entry components that
* need to do quick user name lookups. If actual {@code User} domain
* objects are needed, the {@code findWhere()} method provides an easy
* shortcut for obtaining extended user data. This method will do a 'LIKE'
* query and add a '%' wild card to the provided term
*
* @param userName
* @return {@code List<String>} that are the user names that match the
* partial query
* @throws JargonException
*/
List<String> findUserNameLike(String userName) throws JargonException;
/**
* Generate a temporary password for the connected user. Password validity
* times and number of connections will be set by the iRODS server.
*
* @return {@code String} with the temporary password
* @throws JargonException
*/
String getTemporaryPasswordForConnectedUser() throws JargonException;
/**
* Generate a temporary password for another user. Password validity times
* and number of connections will be set by the iRODS server.
* <p>
* This is a rodsadmin only function, and was added post iRODS 3.0.
*
* @param targetUserName
* {@code String} (required) with the user name for which
* the temporary password will be issued
* @return {@code String} with the temporary password
* @throws JargonException
*/
String getTemporaryPasswordForASpecifiedUser(String targetUserName)
throws JargonException;
/**
* Given a unique numeric user ID, retrieve the user's distinguished name.
* Note that the various list methods do not retrieve the DN by default, as
* it causes unnecessary GenQueries to be issued per user. This method can
* retrieve that data as needed.
* <p>
* The methods that retrieve an individual user do retrieve the DN by
* default.
*
* @param userId
* {@code String} with the iRODS user id (not name)
* @return {@code String} with the user DN, or {@code null} if the
* DN does not exist for the user
* @throws JargonException
*/
String retriveUserDNByUserId(String userId) throws JargonException;
/**
* Update the user info field for the user as a discrete operation.
*
* @param userName
* {@code String} with the name of the user
* @param userInfo
* {@code String} with the info to set, it can be blank, but
* not {@code null}
* @throws DataNotFoundException
* if the user is not found
* @throws JargonException
*/
void updateUserInfo(String userName, String userInfo)
throws DataNotFoundException, JargonException;
/**
* Update the DN for the given user
*
* @param userName
* userName {@code String} with the name of the user
* @param userDN
* {@code DN} to add to the user
* @throws InvalidUserException
* if the user does not exist
* @throws JargonException
*/
void updateUserDN(String userName, String userDN)
throws InvalidUserException, JargonException;
/**
* Remove the DN for the given user. If the user or DN does not exist, it
* will silently ignore the command
*
* @param userName
* userName {@code String} with the name of the user
* @param userDN
* {@code DN} to remove from the user
* @throws JargonException
*/
void removeUserDN(String userName, String userDN) throws JargonException;
}
<file_sep>/**
*
*/
package org.irods.jargon.core.packinstr;
import java.util.ArrayList;
import java.util.List;
import org.irods.jargon.core.exception.JargonException;
import org.irods.jargon.core.pub.domain.AvuData;
/**
* Translation of a ModifyAvuMetadataInp operation into XML protocol format.
*
* @author <NAME> - DICE (www.irods.org)
*
*/
public class ModAvuMetadataInp extends AbstractIRODSPackingInstruction {
public static final String PI_TAG = "ModAVUMetadataInp_PI";
public static final String ARG_PREFIX = "arg";
public static final int MOD_AVU_API_NBR = 706;
/**
* Type of metadata to be modified
*
*/
public enum MetadataTargetType {
RESOURCE, USER, COLLECTION, DATA_OBJECT
}
/**
* Modify action
*/
public enum ActionType {
ADD, REMOVE, MOD, SET
}
private final String targetIdentifier;
private final MetadataTargetType metadataTargetType;
private final AvuData avuData;
private final AvuData newAvuData;
private final ActionType actionType;
/**
* Create an instance of the packing instruction that will add the AVU to a
* collection.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForAddCollectionMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.COLLECTION, avuData, null, ActionType.ADD);
}
/**
* Create an instance of the packing instruction that will modify the AVU on
* a collection.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForModifyCollectionMetadata(
final String targetIdentifier, final AvuData avuData,
final AvuData newAvuData) {
if (newAvuData == null) {
throw new IllegalArgumentException("Null newAvuData");
}
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.COLLECTION, avuData, newAvuData,
ActionType.MOD);
}
/**
* Create an instance of the packing instruction that will add the AVU to a
* collection.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForDeleteCollectionMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.COLLECTION, avuData, null, ActionType.REMOVE);
}
/**
* Create an instance of the packing instruction that will add the AVU to a
* data object.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForAddDataObjectMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.DATA_OBJECT, avuData, null, ActionType.ADD);
}
/**
* Create an instance of the packing instruction that will modify the AVU on
* a data object.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForModifyDataObjectMetadata(
final String targetIdentifier, final AvuData avuData,
final AvuData newAvuData) {
if (newAvuData == null) {
throw new IllegalArgumentException("Null newAvuData");
}
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.DATA_OBJECT, avuData, newAvuData,
ActionType.MOD);
}
/**
* Create an instance of the packing instruction that will add the AVU to a
* data object.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForDeleteDataObjectMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.DATA_OBJECT, avuData, null,
ActionType.REMOVE);
}
/**
* Create an instance of the packing instruction that will add the AVU to a
* resource.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForAddResourceMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.RESOURCE, avuData, null, ActionType.ADD);
}
/**
* Create an instance of the packing instruction that will set the AVU to a
* resource.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForSetResourceMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.RESOURCE, avuData, null, ActionType.SET);
}
/**
* Create an instance of the packing instruction that will modify the AVU on
* a resource.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForModifyResourceMetadata(
final String targetIdentifier, final AvuData avuData,
final AvuData newAvuData) {
if (newAvuData == null) {
throw new IllegalArgumentException("Null newAvuData");
}
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.RESOURCE, avuData, newAvuData,
ActionType.MOD);
}
/**
* Create an instance of the packing instruction that will remove the AVU
* from a resource .
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForDeleteResourceMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier,
MetadataTargetType.RESOURCE, avuData, null, ActionType.REMOVE);
}
/**
* Create an instance of the packing instruction that will add the AVU to a
* user.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForAddUserMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier, MetadataTargetType.USER,
avuData, null, ActionType.ADD);
}
/**
* Create an instance of the packing instruction that will modify the AVU on
* a user.
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForModifyUserMetadata(
final String targetIdentifier, final AvuData avuData,
final AvuData newAvuData) {
if (newAvuData == null) {
throw new IllegalArgumentException("Null newAvuData");
}
return new ModAvuMetadataInp(targetIdentifier, MetadataTargetType.USER,
avuData, newAvuData, ActionType.MOD);
}
/**
* Create an instance of the packing instruction that will remove the AVU
* from a user .
*
* @param targetIdentifier
* {@code String} with the path or unique name of the object
* to which the metadata will be added
* @return {@link ModAvuMetadataInp}
*/
public static final ModAvuMetadataInp instanceForDeleteUserMetadata(
final String targetIdentifier, final AvuData avuData) {
return new ModAvuMetadataInp(targetIdentifier, MetadataTargetType.USER,
avuData, null, ActionType.REMOVE);
}
private ModAvuMetadataInp(final String targetIdentifier,
final MetadataTargetType metadataTargetType, final AvuData avuData,
final AvuData newAvuData, final ActionType actionType) {
super();
if (targetIdentifier == null || targetIdentifier.isEmpty()) {
throw new IllegalArgumentException(
"null or empty target identifier");
}
if (metadataTargetType == null) {
throw new IllegalArgumentException("metadataTargetType is null");
}
if (avuData == null) {
throw new IllegalArgumentException("null or missing avuData");
}
if (actionType == null) {
throw new IllegalArgumentException("null action type");
}
this.targetIdentifier = targetIdentifier;
this.metadataTargetType = metadataTargetType;
this.avuData = avuData;
this.actionType = actionType;
this.newAvuData = newAvuData;
setApiNumber(MOD_AVU_API_NBR);
}
@Override
public Tag getTagValue() throws JargonException {
List<String> argList = new ArrayList<String>();
Tag message = new Tag(PI_TAG);
if (actionType == ActionType.ADD) {
argList.add("add");
} else if (actionType == ActionType.REMOVE) {
argList.add("rmw");
} else if (actionType == ActionType.MOD) {
argList.add("mod");
} else if (actionType == ActionType.SET) {
argList.add("set");
}
if (metadataTargetType == MetadataTargetType.COLLECTION) {
argList.add("-c");
} else if (metadataTargetType == MetadataTargetType.DATA_OBJECT) {
argList.add("-d");
} else if (metadataTargetType == MetadataTargetType.RESOURCE) {
argList.add("-R");
} else if (metadataTargetType == MetadataTargetType.USER) {
argList.add("-u");
} else {
throw new JargonException(
"metadata target type is not currently supported:"
+ metadataTargetType);
}
argList.add(targetIdentifier);
// add the AVU elements
argList.add(avuData.getAttribute());
argList.add(avuData.getValue());
if (!avuData.getUnit().isEmpty()) {
argList.add(avuData.getUnit());
}
if (actionType == ActionType.MOD) {
StringBuilder sb = new StringBuilder();
// attrib
sb.append("n:");
sb.append(newAvuData.getAttribute());
argList.add(sb.toString());
// value
sb = new StringBuilder();
sb.append("v:");
sb.append(newAvuData.getValue());
argList.add(sb.toString());
// unit
sb = new StringBuilder();
sb.append("u:");
sb.append(newAvuData.getUnit());
argList.add(sb.toString());
}
StringBuilder argBuilder;
String val = "";
for (int i = 0; i < 10; i++) {
argBuilder = new StringBuilder(ARG_PREFIX);
argBuilder.append(i);
val = "";
if (i < argList.size()) {
val = argList.get(i);
}
message.addTag(argBuilder.toString(), val);
}
// take the arg list and compact the params
return message;
}
public String getTargetIdentifier() {
return targetIdentifier;
}
public MetadataTargetType getMetadataTargetType() {
return metadataTargetType;
}
public AvuData getAvuData() {
return avuData;
}
public ActionType getActionType() {
return actionType;
}
public AvuData getNewAvuData() {
return newAvuData;
}
}
<file_sep>/**
*
*/
package org.irods.jargon.core.rule;
/**
* Enumerates the type of rule to be processed. This enum describes the type of
* a specific rule instance, and is distinct from the
* {@link IrodsRuleInvocationTypeEnum} value that represents a parameter in a
* user request to process a rule. That is, this is the actual type of the rule,
* the <code>IrodsRuleInvocationTypeEnum</code> is the user request. A user may
* request 'Auto Detection', resulting in an assignment of a type.
*
* @author <NAME>
*
*/
public enum IrodsRuleEngineTypeEnum {
IRODS, PYTHON, UNKNOWN
}
<file_sep>/**
*
*/
package org.irods.jargon.core.unittest;
import org.irods.jargon.core.rule.IRODSRuleTest;
import org.irods.jargon.core.rule.IRODSRuleTranslatorTest;
import org.irods.jargon.core.rule.RuleParsingUtilsTest;
import org.irods.jargon.core.rule.RuleTypeDetectorTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ IRODSRuleTest.class, IRODSRuleTranslatorTest.class, RuleParsingUtilsTest.class,
RuleTypeDetectorTest.class })
public class RuleTests {
}
<file_sep>package org.irods.jargon.core.rule;
import org.junit.Test;
import junit.framework.Assert;
public class RuleTypeDetectorTest {
@Test
public void testDetectTypeFromExtensionIrods() {
String testFileName = "/a/path/to/core.r";
RuleTypeDetector detector = new RuleTypeDetector();
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromExtension(testFileName);
Assert.assertEquals(IrodsRuleEngineTypeEnum.IRODS, actual);
}
@Test
public void testDetectTypeFromExtensionPython() {
String testFileName = "/a/path/to/core.py";
RuleTypeDetector detector = new RuleTypeDetector();
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromExtension(testFileName);
Assert.assertEquals(IrodsRuleEngineTypeEnum.PYTHON, actual);
}
@Test
public void testDetectTypeFromExtensionUnknown() {
String testFileName = "/a/path/to/core.wtf";
RuleTypeDetector detector = new RuleTypeDetector();
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromExtension(testFileName);
Assert.assertEquals(IrodsRuleEngineTypeEnum.UNKNOWN, actual);
}
@Test(expected = IllegalArgumentException.class)
public void testDetectTypeFromExtensionNull() {
RuleTypeDetector detector = new RuleTypeDetector();
detector.detectTypeFromExtension(null);
}
@Test
public void testDetectTypeFromTextWithIrodsAnnotation() throws Exception {
RuleTypeDetector detector = new RuleTypeDetector();
String ruleText = "# @RuleEngine=\"IRODS\"";
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromRuleText(ruleText);
Assert.assertEquals(IrodsRuleEngineTypeEnum.IRODS, actual);
}
@Test
public void testDetectTypeFromTextWithPythonAnnotation() throws Exception {
RuleTypeDetector detector = new RuleTypeDetector();
String ruleText = "# @RuleEngine=\"PYTHON\"";
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromRuleText(ruleText);
Assert.assertEquals(IrodsRuleEngineTypeEnum.PYTHON, actual);
}
@Test
public void testDetectTypeFromTextWithIrodsSpacey() throws Exception {
RuleTypeDetector detector = new RuleTypeDetector();
String ruleText = "# @RuleEngine=\" IRODS \" ";
IrodsRuleEngineTypeEnum actual = detector.detectTypeFromRuleText(ruleText);
Assert.assertEquals(IrodsRuleEngineTypeEnum.IRODS, actual);
}
}
<file_sep>
# Project: Jargon-core API
#### Date:
#### Release Version: 4.2.0.1-SNAPSHOT
#### git tag:
#### Developer: <NAME> - DICE
## News
4.2.0 Compatability and maintenance
for milestone: https://github.com/DICE-UNC/jargon/milestone/19
=======
Please go to [[https://github.com/DICE-UNC/jargon]] for the latest news and info.
Jargon-core consists of the following libraries
* jargon-core - base libraries, implementation of the iRODS protocol
* jargon-data-utils - additional functionality for dealing with iRODS data, such as building trees, storing information in iRODS on behalf of applications, and doing diffs between local and iRODS
* jargon-user-tagging - code for using free tagging and other metadata metaphors on top of iRODS
* jargon-user-profile - allows management of user profile and related configuration data in a user home directory
* jargon-ticket - support for ticket processing
* jargon-httpstream - stream http content into iRODS via Jargon
* jargon-ruleservice - support for running and managing rules from interfaces
* jargon-pool - initial implementation of commons-pool caching of iRODS agent connections. This is initially for WebDav, and will be utilized as an option in REST and cloud browser. Consider this code experimental
## Requirements
* Jargon depends on Java 1.8+
* Jargon is built using Apache Maven2, see POM for dependencies
* Jargon supports iRODS 4.1.0 through 4.2.X
## Libraries
Jargon-core uses Maven for dependency management. See the pom.xml file for references to various dependencies.
Note that the following bug and feature requests are logged in GForge with related commit information [[https://github.com/DICE-UNC/jargon/issues]]
## Changes
#### Failures against 4.1.9 with neg require on server executing file.deleteWithForceOption in unit tests. #216
Fixes to flush behavior (related to #224) remaining after a switch to the SSL negotiation communication regime, corrections to behavior of flush() in client status operation send/receive in recursive delete operations
#### User lacks privileges to invoke the given API" when adding groups / users to groups #255
Added function to UserGroupAO with 'asGroupAdmin' variants to manipulate groups as a user type groupadmin. A few needed functions are added, with plans to add more in coming updates
#### add enum to indicate rule executing on chosen rule engine #259
Added code to RuleProcessingAO to indicate rule type, and do simple auto detection based on extension when running from a file
<file_sep>/**
*
*/
package org.irods.jargon.core.rule;
/**
* Indicates type of iRODS rule engine (e.g. iRODS rule language, Python rule) a
* rule invocate is bound for. <code>AUTO_DETECT</code> indicates a request to
* have the service guess the type of rule it is.
* <p/>
* Note that <code>SPECIFIED</code> indicates that the full name of the target
* rule engine will be provided by the user.
*
* @author <NAME>
*
*/
public enum IrodsRuleInvocationTypeEnum {
IRODS, PYTHON, JAVASCRIPT, AUTO_DETECT, SPECIFIED
}
<file_sep>/**
*
*/
package org.irods.jargon.core.rule;
import org.irods.jargon.core.exception.JargonException;
import org.irods.jargon.core.utils.LocalFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <NAME>
*
*/
public class RuleTypeDetector {
private static final Logger log = LoggerFactory.getLogger(RuleTypeDetector.class);
/**
* annotation that can be added in a comment that can have a value of IRODS |
* PYTHON for now
*/
public static final String RULE_ENGINE_ANNOTATION = "@RuleEngine=\"";
/**
* Guess a rule type based on the file extenstion
*
* @param fileName
* <code>String</code> with a file name or even a path
* @return {@link IrodsRuleEngineTypeEnum} which can return UNKNOWN if it can't
* guess
*/
public IrodsRuleEngineTypeEnum detectTypeFromExtension(final String fileName) {
log.info("detectTypeFromExtension()");
if (fileName == null || fileName.isEmpty()) {
throw new IllegalArgumentException("null or empty fileName");
}
log.info("fileName:{}", fileName);
String extension = LocalFileUtils.getFileExtension(fileName);
log.debug("extension is:{}", extension);
IrodsRuleEngineTypeEnum enumVal;
if (extension.trim().equals(".r")) {
enumVal = IrodsRuleEngineTypeEnum.IRODS;
} else if (extension.trim().equals(".py")) {
enumVal = IrodsRuleEngineTypeEnum.PYTHON;
} else {
enumVal = IrodsRuleEngineTypeEnum.UNKNOWN;
}
return enumVal;
}
public IrodsRuleEngineTypeEnum detectTypeFromRuleText(final String ruleText) throws JargonException {
log.info("detectTypeFromRuleText()");
if (ruleText == null || ruleText.isEmpty()) {
throw new IllegalArgumentException("null or empty ruleText");
}
log.info("ruleText:{}", ruleText);
/*
* first look for an @Engine annotation! This is something that needs to be
* formalized but for now it's a handy trick if something goes wrong
*/
IrodsRuleEngineTypeEnum enumVal;
int reAnnotationIndex = ruleText.indexOf(RULE_ENGINE_ANNOTATION);
if (reAnnotationIndex > -1) {
log.debug("found an annotation!");
// for now just looks for the next space and pulls out the string after the =,
// yes
// this is brittle
int endOfAnnotation = reAnnotationIndex + RULE_ENGINE_ANNOTATION.length();
int nextSpace = ruleText.indexOf("\"", endOfAnnotation);
if (nextSpace == -1) {
throw new JargonException("found a rule engine annotation but could not find type after =");
}
String annotationType = ruleText.substring(endOfAnnotation, nextSpace).trim();
log.debug("annotationType:{}", annotationType);
if (annotationType.equals(IrodsRuleEngineTypeEnum.IRODS.toString())) {
enumVal = IrodsRuleEngineTypeEnum.IRODS;
} else if (annotationType.equals(IrodsRuleEngineTypeEnum.PYTHON.toString())) {
enumVal = IrodsRuleEngineTypeEnum.PYTHON;
} else {
enumVal = IrodsRuleEngineTypeEnum.UNKNOWN;
}
} else {
enumVal = IrodsRuleEngineTypeEnum.UNKNOWN;
}
return enumVal;
}
}
|
0133b0b56151c78294fff480bd11535ffd755d37
|
[
"Markdown",
"Java"
] | 8
|
Java
|
lllchuanshuo/jargon
|
1e84a1336897557970080425870e4246b384dc03
|
020b70edf2addc1259ccf79d6c7b13ae19308ccf
|
refs/heads/master
|
<repo_name>Clayden-Wang/rtthread_imu<file_sep>/applications/main.c
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-05-10 zhuangwei first version
*/
// I2C2,引脚CAMDATA6(GPIO56)和CAMDATA7(GPIO57)的第四复用
// I2C鏁版嵁浼犺緭鏂瑰悜
#define LS1C_I2C_SDA2_GPIO56 (56)
#define LS1C_I2C_SCL2_GPIO57 (57)
#define LS1C_UART2_IRQ1 5
#define NULL ((void *)0)
#include "../libraries/ls1c_uart.h"
#include "../libraries/ls1c_irq.h"
#include "../libraries/ls1c_pin.h"
#include <rtthread.h>
#include "../libraries/ls1c_public.h"
#include "../libraries/ls1c_gpio.h"
#include "../libraries/ls1c_delay.h"
#include "../libraries/ls1c_i2c.h"
ls1c_i2c_info_t i2c_info;
//int slave_addr=0x50 >> 1;
void i2c_INT()
{
// I2C2,引脚CAMDATA6(GPIO56)和CAMDATA7(GPIO57)的第四复用
pin_set_remap(LS1C_I2C_SDA2_GPIO56, PIN_REMAP_FOURTH);
pin_set_remap(LS1C_I2C_SCL2_GPIO57, PIN_REMAP_FOURTH);
i2c_info.clock = 50*1000; // 50kb/s
i2c_info.I2Cx = LS1C_I2C_2;
i2c_init(&i2c_info);
}
void test_uart_irqhandler(int IRQn, void *param) //中断服务程序
{
ls1c_uart_t uartx = uart_irqn_to_uartx(IRQn);
void *uart_base = uart_get_base(uartx);
unsigned char iir = reg_read_8(uart_base + LS1C_UART_IIR_OFFSET);
int slave_addr = 0xb8 >> 1;
// 判断是否为接收超时或接收到有效数据
if ((IIR_RXTOUT & iir) || (IIR_RXRDY & iir))
{
// 是,则读取数据,并原样发送回去
while (LSR_RXRDY & reg_read_8(uart_base + LS1C_UART_LSR_OFFSET))
{
i2c_send_start_and_addr(&i2c_info, slave_addr, LS1C_I2C_DIRECTION_READ);
i2c_send_ack(&i2c_info);
i2c_send_data(&i2c_info,reg_read_8(uart_base+LS1C_UART_IIR_OFFSET),8);
i2c_send_stop(&i2c_info);
}
}
return ;
}
void test_uart2_send_recv(void) //初始化
{
unsigned int tx_gpio = 37;
unsigned int rx_gpio = 36;
ls1c_uart_info_t uart2_info = {0};
// 设置复用
pin_set_remap(tx_gpio, PIN_REMAP_SECOND);
pin_set_remap(rx_gpio, PIN_REMAP_SECOND);
// 重新初始化串口2(使能接收中断)
uart2_info.UARTx = LS1C_UART2;
uart2_info.baudrate = 115200;
uart2_info.rx_enable= 1; // 使能接收中断
uart_init(&uart2_info);
// 设置中断处理函数
irq_install(LS1C_UART2_IRQ1);
irq_enable(LS1C_UART2_IRQ1);
while (1)
{
delay_s(1);
}
}
int main(int argc, char **argv)
{
i2c_INT();
test_uart2_send_recv();
return(0);
}
<file_sep>/JY901_lib/JY901.c
#include "JY901.h"
void StartIIC()
{
ucDevAddr = 0x50;
}
void StartIIC(unsigned char ucAddr)
{
ucDevAddr = ucAddr;
}
void CopeSerialData(unsigned char ucData)
{
static unsigned char ucRxBuffer[250];
static unsigned char ucRxCnt = 0;
ucRxBuffer[ucRxCnt++]=ucData;
if (ucRxBuffer[0]!=0x55)
{
ucRxCnt=0;
return;
}
}
}
void readRegisters(unsigned char deviceAddr,unsigned char addressToRead, unsigned char bytesToRead, char * dest)
{
}
void writeRegister(unsigned char deviceAddr,unsigned char addressToWrite,unsigned char bytesToRead, char *dataToWrite)
{
}
void WriteWord(unsigned char ucAddr,short sData)
{
writeRegister(ucDevAddr, ucAddr, 2, (char *)&sData);
}
void ReadData(unsigned char ucAddr,unsigned char ucLength,char chrData[])
{
readRegisters(ucDevAddr, ucAddr, ucLength, chrData);
}
void GetTime()
{
readRegisters(ucDevAddr, 0x30, 8, (char*)&sTime);
}
void GetAcc()
{
readRegisters(ucDevAddr, AX, 6, (char *)&sAcc);
}
void GetGyro()
{
readRegisters(ucDevAddr, GX, 6, (char *)&sGyro);
}
void GetAngle()
{
readRegisters(ucDevAddr, Roll, 6, (char *)&sAngle);
}
void GetMag()
{
readRegisters(ucDevAddr, HX, 6, (char *)&sMag);
}
void CJY901::GetPress()
{
readRegisters(ucDevAddr, PressureL, 8, (char *)&sPress);
}
void CJY901::GetDStatus()
{
readRegisters(ucDevAddr, D0Status, 8, (char *)&sDStatus);
}
void CJY901::GetLonLat()
{
readRegisters(ucDevAddr, LonL, 8, (char *)&sLonLat);
}
void CJY901::GetGPSV()
{
readRegisters(ucDevAddr, GPSHeight, 8, (char *)&sGPSV);
}
<file_sep>/applications/ted_led.c
/* * File : test_led.c 测试 led 接口在 finsh/msh 中运行 1. test_led() / test_led */
#include <rtthread.h>
#include "../libraries/ls1c_public.h"
#include "../libraries/ls1c_gpio.h"
#include "../libraries/ls1c_delay.h"
#define led_gpio 52
/* * 测试库中 gpio 作为输出时的相关接口 * led 闪烁 10 次 */
void test_led(void)
{
int i;
// 初始化
rt_kprintf("Init led! \n");
gpio_init(led_gpio, gpio_mode_output);
gpio_set(led_gpio, gpio_level_high); // 指示灯默认熄灭
// 输出 10 个矩形波,如果 gpio50 上有 led,则可以看见 led 闪烁 10 次
for (i=0; i<30; i++)
{
gpio_set(led_gpio, gpio_level_low);
delay_s(100);
gpio_set(led_gpio, gpio_level_high);
delay_s(100);
rt_kprintf("current time: %d \n", i);
}
return ;
}
#include <finsh.h>
FINSH_FUNCTION_EXPORT(test_led, test_led e.g.test_led());
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(test_led, test led flash );
|
f756fdf492398b7a16fd30eee4551538062e39a4
|
[
"C"
] | 3
|
C
|
Clayden-Wang/rtthread_imu
|
812694d5d38d1c6dbf4f2c740564c6b3bfd48bef
|
bb043b5257e642340b43445972296548cee17ae5
|
refs/heads/main
|
<repo_name>vladislav2/ColorViewHW_2.2<file_sep>/ColorViewHW_2.2/ViewController.swift
//
// ViewController.swift
// ColorViewHW_2.2
//
// Created by user on 29.01.2021.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var colorsView: UIView!
@IBOutlet weak var redLabel: UILabel!
@IBOutlet weak var greenLabel: UILabel!
@IBOutlet weak var blueLabel: UILabel!
@IBOutlet weak var redSlider: UISlider!
@IBOutlet weak var greenSlider: UISlider!
@IBOutlet weak var blueSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
changeBackgroundColorView(slider: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
colorsView.layer.cornerRadius = 16
}
@IBAction func sliderValueChanged(_ sender: UISlider) {
changeBackgroundColorView(slider: sender)
}
private func changeBackgroundColorView(slider: UISlider?) {
colorsView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1)
switch slider {
case redSlider:
redLabel.text = String(format: "%.2f", redSlider.value)
case greenSlider:
greenLabel.text = String(format: "%.2f", greenSlider.value)
case blueSlider:
blueLabel.text = String(format: "%.2f", blueSlider.value)
default:
redLabel.text = String(format: "%.2f", redSlider.value)
greenLabel.text = String(format: "%.2f", greenSlider.value)
blueLabel.text = String(format: "%.2f", blueSlider.value)
}
}
}
|
f002fd7029ee54565e3bd9269579de685238ceba
|
[
"Swift"
] | 1
|
Swift
|
vladislav2/ColorViewHW_2.2
|
95d40aac66c096934ccf61ee2b972327307ef201
|
86d7281891dcddcaa8ed22da9174ed89a3c0f851
|
refs/heads/master
|
<repo_name>du2016/create-kvm<file_sep>/create-kvm
#!/bin/bash
TEMP_DIR=`date +%H%M%S%N`
STORAGE_PATH=/opt/create_kvm/images/
IMG_PATH=/images/
XML_PATH=/xmls/
CONF_PATH=/opt/create_kvm/files/
MAC=`python -c "from virtinst.util import randomMAC;print randomMAC(type='qemu')"`
while getopts "n:t:p:g:m:h" opt; do
case $opt in
n)
#echo "this is name the arg is ! $OPTARG"
NAME=$OPTARG
;;
t)
#echo "this is type option"
TYPE=$OPTARG
;;
p)
#echo "this is ipaddress option"
IP_ADDRESS=$OPTARG
;;
g)
#echo "this is gateway option"
GATE_WAY=$OPTARG
;;
m)
#echo "this is mask option"
MASK=$OPTARG
;;
h)
echo
echo "create_kvm command with options: -n name -t type -p ip -g gateway -m mask"
echo
echo -e "\t example: create-kvm -n 10.10.100.121 -t 8 -p 10.10.100.121 -g 10.10.100.1 -m 24"
echo -n """
--------------------------------
type 1 is centos6-6-4c-8g-200g,
"""
exit 0
esac
done
if [[ $NAME == "" ]]
then
echo "name don't can be null"
exit 1
elif [ -f ${XML_PATH}${type}-${NAME}.xml ]
then
echo "this image is already esxit"
break 1
fi
#if [[ $type -eq 2 ]]
#then
# type=centos6-6-8c-16g-500g
#else
# type=centos6-6-4c-8g-200g
#fi
case $TYPE in
1)
TYPE=centos6-6-4c-8g-200g
;;
*)
echo "unknow type!!!"
exit 1
esac
if [[ $IP_ADDRESS == "" ]]
then
echo "IP_ADDRESS don't can be null"
exit 1
fi
if [[ $MASK == "" ]]
then
echo "MASK don't can be null"
exit 1
fi
if [[ $GATE_WAY == "" ]]
then
echo "GATE_WAY don't can be null"
exit 1
fi
mkdir ${CONF_PATH}${TEMP_DIR}
#复制dev配置
cp ${CONF_PATH}70-persistent-net.rules-base ${CONF_PATH}${TEMP_DIR}/70-persistent-net.rules
#复制网卡配置
cp ${CONF_PATH}ifcfg-eth0-base ${CONF_PATH}${TEMP_DIR}/ifcfg-eth0
#复制zabbix配置
cp ${CONF_PATH}zabbix_agentd.conf-base ${CONF_PATH}${TEMP_DIR}/zabbix_agentd.conf
#复制新虚拟机配置文件及磁盘
cp ${STORAGE_PATH}${TYPE}.xml ${XML_PATH}${TYPE}-${NAME}.xml
cp ${STORAGE_PATH}${TYPE}.qcow2 ${IMG_PATH}${TYPE}-$NAME.qcow2
#修改虚拟机名称 包括硬盘名称
sed -i "s/${TYPE}/${TYPE}-${NAME}/g" ${XML_PATH}${TYPE}-${NAME}.xml
#修改MAC地址
sed -i "s/mac address='.*'/mac address='${MAC}'/g" ${XML_PATH}${TYPE}-${NAME}.xml
#修改eth0 dev mac地址
sed -i "s/MAC_ADDRESS/${MAC}/g" ${CONF_PATH}${TEMP_DIR}/70-persistent-net.rules
#设置网络配置
sed -i "s/IP_ADDRESS/${IP_ADDRESS}/g" ${CONF_PATH}${TEMP_DIR}/ifcfg-eth0
sed -i "s/GATE_WAY/${GATE_WAY}/g" ${CONF_PATH}${TEMP_DIR}/ifcfg-eth0
sed -i "s/MASK/${MASK}/g" ${CONF_PATH}${TEMP_DIR}/ifcfg-eth0
#设置zabbix-agent hostname
sed -i "s/^Hostname=.*$/Hostname=${IP_ADDRESS}/g" ${CONF_PATH}${TEMP_DIR}/zabbix_agentd.conf
#复制到虚拟机
virt-copy-in ${CONF_PATH}${TEMP_DIR}/70-persistent-net.rules -a ${IMG_PATH}${TYPE}-${NAME}.qcow2 /etc/udev/rules.d/
virt-copy-in ${CONF_PATH}${TEMP_DIR}/ifcfg-eth0 -a ${IMG_PATH}${TYPE}-${NAME}.qcow2 /etc/sysconfig/network-scripts/
virt-copy-in ${CONF_PATH}${TEMP_DIR}/zabbix_agentd.conf -a ${IMG_PATH}${type}-${NAME}.qcow2 /opt/app/zabbix/etc/
#清理
rm -f ${CONF_PATH}${TEMP_DIR}
virsh define ${XML_PATH}${TYPE}-${NAME}.xml
virsh start ${TYPE}-${NAME}
<file_sep>/README.md
######1.一键安装kvm脚本,一键配置IP地址。
######2.一共五个参数都必须指定。
######3.根据模板镜像进行复制,手动指定MAC地址解决克隆虚拟机网卡变为eth1问题。
######4.需要指定镜像存储位置、虚拟机磁盘目录位置、虚拟机配置文件、其他配置文件的目录。
|
125742fe564427a922db2085411d566ec4f72ac2
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
du2016/create-kvm
|
aa3185aa734292543e72ed93fc8521104b836d12
|
1da172a54e06027a834f7fc4113e68163574fb2e
|
refs/heads/main
|
<repo_name>StWadeSt/2020_will<file_sep>/fetch.php
<?php
include('DBConn.php');
session_start();
if(isset($_POST["year"]))
{
$query = "
SELECT * FROM dams
WHERE name = '".$_POST["year"]."'
ORDER BY Year_ ASC
";
$result = mysqli_query($conn, $query) or die('error getting data from table');
foreach($result as $row)
{
$output[] = array(
'month' => $row["Year_"],
'profit' => floatval($row["waterLevel"])
);
}
echo json_encode($output);
}
?>
<file_sep>/index.php
<?php
$message="";
include("dbConn.php");
session_start();
$id = $_SESSION['userID'] ;
if (isset($_POST['submit'])) {
if ($id != null) {
$query = "
SELECT address FROM users
WHERE userID = '".$id."'
";
$result = mysqli_query($conn, $query) or die('error getting data from table');
foreach ($result as $key)
{
$address = $key['address'];
}
if ($_POST['selectedMessage'] ==1) {
$message = " ***IMPORTANT***** We are experiencing issues with a burst pipe in my area. Please send assistance! My address: $address";
}
if ($_POST['selectedMessage'] ==2) {
$message = " ***IMPORTANT***** We are experiencing issues with low water pressure in my area. Please send assistance! My address: $address";
}
if ($_POST['selectedMessage'] ==3) {
$message = "***IMPORTANT***** We are not receiving any water in area. Please send assistance! My address: $address";
}
}
else{
if ($_POST['selectedMessage'] ==1) {
$message = " ***IMPORTANT***** We are experiencing issues with a burst pipe in -----ENTER YOUR AREA-----. Please send assistance!";
}
if ($_POST['selectedMessage'] ==2) {
$message = " ***IMPORTANT***** We are experiencing issues with low water pressure in -----ENTER YOUR AREA-----. Please send assistance!";
}
if ($_POST['selectedMessage'] ==3) {
$message = "***IMPORTANT***** We are not receiving any water in -----ENTER YOUR AREA-----. Please send assistance!";
}
}
}
if(isset($_POST["name"]))
{
$damName = $_POST["name"];
echo $damName;
//$temp_title = "Avarage Water Levels per Year For "+ $damName;
$query = "
SELECT * FROM dams
WHERE name = '".$damName."'
ORDER BY Year_ ASC
";
$result = mysqli_query($conn, $query) or die('error getting data from table');
foreach($result as $row)
{
$output[] = array(
'year' => $row["Year_"],
'waterLevel' => floatval($row["waterLevel"])
);
}
drawMonthwiseChart($output);
}
if (isset($_POST['saveReport'])) {
$date = date("Y-m-d");
$context = $_POST['reportArea'];
if ($id!= null) {
$userEmail = $_SESSION['userEmail'];
$query = "INSERT INTO `reports`(`reportID`, `context`, `userID`, `state`, `dateOfReport`, `userEmail`) VALUES (null,'$context', '$id','Unresolved', '$date', '$userEmail')";
$result = mysqli_query($conn,$query)or die('error getting data from table');
if($result){
echo "<script>alert('Thank You For Your Input. Our Query will be looked into !');</script>";
}
}
else{
echo "<script>alert('Please Sign in first, as we will need your address for more accurate service!');</script>";
}
}
$query = "SELECT name FROM dams";
$result = mysqli_query($conn, $query) or die('error getting data from table');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Water, Our Concern</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<header>
<h1><span> My Water</span></h1>
<nav>
<ul>
<li><a href="login.php">Login</a></li>
<li><a href="logout.php">Logout</a></li>
<li><a href="maap.html">Map</a></li>
</ul>
</nav>
</header>
<body>
<div style="background-color: grey; padding: 20px;">
<center>
<h1>Your Water, Our Concern <img src="./image/k37116405.jpg"></h1>
</center>
</div>
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br />
<center>
<h3 style="text-align: center; font-style: bold">Experiencing a Problem?</h3>
<form method="POST" >
<select name="selectedMessage" style="margin-left:25px; margin-bottom: 10px"> class="form-control">
<option value="1">Burst pipe</option>
<option value="2">Low water pressure</option>
<option value="3">No water flow</option>
</select>
<input type="submit" name="submit" value="Select" style="margin-bottom: 10px ">
<form method="POST">
<div id="report">
<textarea name="reportArea" class="form-control" style="width: 400px; height: 120px; position: center; text-align: center; border-color: black; "><?php echo $message?></textarea>
<input type="submit" name="saveReport" value="Report">
</div>
</form>
</form>
</center>
<br><br>
<div class="container">
<h3 align="center">Water Levels For Mayor PE Dams</h3>
<br />
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-md-9">
</div>
<div class="col-md-3">
<select name="year" class="form-control" id="year">
<option value="">Select Dam</option>
<?php
$count = 0;
foreach($result as $row)
{
if ($count<5) {
echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
}
$count ++;
}
?>
</select>
</div>
</div>
</div>
<div class="panel-body">
<div id="chart_area" style="width: 1000px; height: 320px;"></div>
</div>
</div>
</div>
<footer>
<div class="footer-social-icons">
<ul>
<li><a href="" target="blank" class="fa fa-facebook"></a></li>
<li><a href="" target="blank" class="fa fa-twitter"></a></li>
<li><a href="" target="blank" class="fa fa-instagram"></a></li>
</ul>
</div>
</footer>
</body>
</html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback();
function load_dam_data(year, title)
{
var temp_title = title + ' '+year+'';
$.ajax({
url:"fetch.php",
method:"POST",
data:{year:year},
dataType:"JSON",
success:function(data)
{
drawMonthwiseChart(data, temp_title);
}
});
}
function drawMonthwiseChart(chart_data, chart_main_title)
{
var jsonData = chart_data;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Years');
data.addColumn('number', 'Water Level(%)');
$.each(jsonData, function(i, jsonData){
var month = jsonData.month;
var profit = parseFloat($.trim(jsonData.profit));
data.addRows([[month, profit]]);
});
var options = {
title:chart_main_title,
hAxis: {
title: "Years"
},
vAxis: {
title: 'Water Level(%)'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_area'));
chart.draw(data, options);
}
</script>
<script>
$(document).ready(function(){
$('#year').change(function(){
var year = $(this).val();
if(year != '')
{
load_dam_data(year, 'Average Water Level per Year for');
}
});
});
</script><file_sep>/login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="loginStyling.css" />
</head>
<body>
<?php
include('DBconn.php');
session_start();
$_SESSION['userID'] = "";
// when form submitted it inserts the values into the database.
if (isset($_POST['username']))
{
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($conn,$username);
$lastName = stripslashes($_REQUEST['lastName']);
//escapes special characters in a string
$lastName = mysqli_real_escape_string($conn,$lastName);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking if user exists in the database by comparing the username and hashed password
$query = "SELECT * FROM `users` WHERE fname ='".$username."'
and password_='".md5($password)."'";
$result = mysqli_query($conn,$query) or die (mysql_error());//executing the sql statement
$rows = mysqli_num_rows($result);//checking whether there are any users with matching information and how many there are
if($rows>0)// if theres one record found with mathing information
{
foreach ($result as $key) {
$_SESSION['userID'] = $key['userID'];
$_SESSION['userEmail'] = $key['email'];
}
$id = $_SESSION['userID'];
header("Location: index.php");// Redirect user to index.php
}
else//if no mastches are found in the table
{
//notifies user that the information entered is incorrect and prompts them to go back to login page where they can register if needed
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}
else
{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" value="<?php if(isset($_POST['username'])){echo $_POST['username'];} ?>" name="username" placeholder="<NAME>" required /><br>
<input type="text" value="<?php if(isset($_POST['username'])){echo $_POST['username'];} ?>" name="lastName" placeholder="<NAME>" required /><br>
<input type="text" value="<?php if(isset($_POST['username'])){echo $_POST['username'];} ?>" name="email" placeholder="Email" required /><br>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required /><br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
<?php
}
?>
</body>
</html><file_sep>/adminLogin.php
<?php
session_start();
include('DBConn.php');
if(isset($_POST['submit']))
{
$username = stripslashes($_REQUEST['username']);
$password = stripslashes($_REQUEST['password']);
if ($username =="admin" && $password == "<PASSWORD>") {
$_SESSION['username'] = $username;
header("Location: adminpage.php");
}
else
{
echo "<h3>adminName/password is incorrect.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<link rel="stylesheet" href="loginStyling.css" />
</head>
<body>
<div class= "form"><br><br><br><br><br><br><br><br>
<h1>Admin Login</h1>
<form action="" method="post" name ="login">
<input type= "text" value= "<?php if(isset($_POST['username'])){echo $_POST['username'];} ?>" name="username" placeholder="<NAME>" required /><br>
<input type="<PASSWORD>" name ="password" placeholder="<PASSWORD>" required/><br>
<input name="submit" type="submit" value="Login"/>
</form>
</div>
</body>
</html>
<file_sep>/README.md
# 2020_will
Water levels in dams within the Port Elizabeth area.
<file_sep>/registration.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registration</title>
<link rel="stylesheet" href="loginStyling.css" />
</head>
<body>
<?php
include('DBConn.php');//including database connection
session_start();//starts new session
// If form submitted, insert values into the database.
if (isset($_REQUEST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
$Lname = stripslashes($_REQUEST['LName']);
//escapes special characters in a string
$username = mysqli_real_escape_string($conn,$username);
$Lname = mysqli_real_escape_string($conn,$Lname);
$address = stripslashes($_REQUEST['address']);
//escapes special characters in a string
$address = mysqli_real_escape_string($conn,$address);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//this inserts the new user's information from the registration form into the database
$query = "INSERT INTO `users`(`userID`, `email`, `password_`, `fname`, `lname`, `address`) VALUES (null,'$email', '".md5($password)."','$username', '$Lname', '$address' )";
$result = mysqli_query($conn,$query);
if($result){
//if the insert statement is successful the user is prompted with a success message
echo "<div class='form'>
<h3>Registration Successful.</h3>
<br/>Return to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Registration</h1>
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="<NAME>" required /><br>
<input type="text" name="LName" placeholder="<NAME>" required /><br>
<input type="text" value="<?php if(isset($_POST['username'])){echo $_POST['address'];} ?>" name="address" placeholder="Address" required /><br>
<input type="email" name="email" placeholder="Email" required /><br>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required /><br>
<input type="submit" name="submit" value="Register" />
</form>
</div>
<?php } ?>
</body>
</html>
|
a01bc65a11dba4042598b73a2f33804ed56d1b0a
|
[
"Markdown",
"PHP"
] | 6
|
PHP
|
StWadeSt/2020_will
|
6b38f334642120730743342750fc840573017dda
|
2e853c02697bc65f223857eb81f3e1a7fd0b58f9
|
refs/heads/master
|
<file_sep>using System.Collections.ObjectModel;
using WPF.ComboHierarchy.Core.Mvvm;
using WPF.ComboHierarchy.Model;
using WPF.ComboHierarchy.Repository;
namespace WPF.ComboHierarchy.ViewModel
{
internal class MainWindowViewModel : ViewModelBase
{
private readonly IStudyRepository _studyRepository;
public MainWindowViewModel(IStudyRepository studyRepository)
{
_studyRepository = studyRepository;
Studies = new ObservableCollection<Study>(_studyRepository.List());
}
public ObservableCollection<Study> Studies { get; private set; }
private Study _selectedStudy;
public Study SelectedStudy
{
get { return _selectedStudy; }
set
{
_selectedStudy = value;
Screenings = new ObservableCollection<Screening>(_selectedStudy.Screenings);
NotifyPropertyChanged();
}
}
private ObservableCollection<Screening> _screenings;
public ObservableCollection<Screening> Screenings
{
get { return _screenings; }
set
{
_screenings = value;
NotifyPropertyChanged();
}
}
private Screening _selectedScreening;
public Screening SelectedScreening
{
get { return _selectedScreening; }
set
{
_selectedScreening = value;
Patients = new ObservableCollection<Patient>(_selectedScreening.Patients);
NotifyPropertyChanged();
}
}
private ObservableCollection<Patient> _patients;
public ObservableCollection<Patient> Patients
{
get { return _patients; }
set
{
_patients = value;
NotifyPropertyChanged();
}
}
}
}<file_sep>using System.Collections.Generic;
using WPF.ComboHierarchy.Model;
namespace WPF.ComboHierarchy.Repository
{
internal class StudyRepository : IStudyRepository
{
public List<Study> List()
{
var studies = new List<Study>();
var study = new Study(1, "Fake study");
var screening = new Screening(1, "Screening 01", study);
var patient1 = new Patient(1, "James", "Bond", screening);
var patient2 = new Patient(2, "Fox", "Mulder", screening);
study.AddScreening(screening);
screening.AssignPatient(patient1);
screening.AssignPatient(patient2);
studies.Add(study);
return studies;
}
}
}<file_sep>namespace WPF.ComboHierarchy.Model
{
public class Patient
{
public Patient(int id, string firstName, string lastName, Screening screening)
{
PatientId = id;
FirstName = firstName;
LastName = lastName;
Screening = screening;
}
public int PatientId { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Screening Screening { get; private set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}<file_sep>using System.Collections.Generic;
namespace WPF.ComboHierarchy.Model
{
public class Study
{
public Study(int id, string name)
{
StudyId = id;
Name = name;
Screenings = new List<Screening>();
}
public int StudyId { get; private set; }
public string Name { get; private set; }
public List<Screening> Screenings { get; private set; }
public void AddScreening(Screening screening)
{
Screenings.Add(screening);
}
}
}<file_sep>using System.Collections.Generic;
namespace WPF.ComboHierarchy.Model
{
public class Screening
{
public Screening(int id, string name, Study study)
{
ScreeningId = id;
Name = name;
Study = study;
Patients = new List<Patient>();
}
public int ScreeningId { get; private set; }
public string Name { get; private set; }
public Study Study { get; private set; }
public List<Patient> Patients { get; private set; }
public void AssignPatient(Patient patient)
{
Patients.Add(patient);
}
}
}<file_sep>using System.Collections.Generic;
using WPF.ComboHierarchy.Model;
namespace WPF.ComboHierarchy.Repository
{
public interface IStudyRepository
{
List<Study> List();
}
}
|
58243f3737703ea2760b22751e6d466c1b9c20d1
|
[
"C#"
] | 6
|
C#
|
marekzet/wpf-combo-hierarchy
|
ed17bb6c8c8e33c135f86635bb935ed4cac41a99
|
884bf2ef797ad7b67fdc7ae7da0b475c719f17b7
|
refs/heads/main
|
<file_sep>package WEEK_02;
import java.util.Scanner;
public class Baekjoon_10809 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.next();
for( char i = 'a'; i <= 'z'; i++){
System.out.print(word.indexOf(i)+" ");
}
}
}
<file_sep>package WEEK_02;
import java.util.Scanner;
public class Baekjoon_2445 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int s = (n - 1); s > i; s--) {
System.out.print(" ");
}
for (int q = (n - 1); q > i; q--) {
System.out.print(" ");
}
for (int w = 0; w <= i; w++) {
System.out.print("*");
}
System.out.println();
}
for (int e = 0; e < n-1; e++) {
for (int r = (n-1); r >= e+1; r--) {
System.out.print("*");
}
for (int t = 0; t < e+1; t++) {
System.out.print(" ");
}
for (int a = 0; a < e+1; a++) {
System.out.print(" ");
}
for (int d = (n-1); d >= e+1; d--) {
System.out.print("*");
}
System.out.println();
}
}
}
<file_sep>package WEEK_02;
public class EnumTest {
public static void main(String[] args) {
Week today = Week.SUNDAY;
System.out.println(today);
//name() 메소드
String name = today.name();
System.out.println(name);
}
}
<file_sep>package WEEK_01;
import java.util.Scanner;
public class CODEUP_1019 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String [] strDate = str.split("\\."); //"."으로 구분해서 입력
String result = "";
int year = Integer.parseInt(strDate[0]);
int month = Integer.parseInt(strDate[1]);
int day = Integer.parseInt(strDate[2]);
// year가 네자릿수가 아닐 경우 네자릿수로 맞춰서 result에 추가
if ((year>0) && (year<10)){
result += "000"+year;
} else if ((year>9) && (year<100)){
result += "00"+year;
} else if ((year>99) && (year<1000)){
result += "0"+year;
} else {
result += year;
}
// month가 한 자리일 경우 두자릿수로 맞춰서 result에 추가
result += ((month>0) && (month<10)) ? (".0"+month) : ("."+month);
// day가 한 자리 경우 앞에 두자릿수로 맞춰서 result에 추가
result += ((day>0) && (day<10)) ? (".0"+day) : ("."+day);
System.out.println(result);
}
}
<file_sep>package WEEK_02;
import java.util.Scanner;
public class Baekjoon_1259 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
String n = sc.next();
if(n.equals("0")) System.exit(0);
String[] arr = new String[n.length()];
String[] arr2 = new String[n.length()];
for(int i=0; i<n.length(); i++){
arr[i] = n.substring(i, i+1);
}
for(int i = 0; i<n.length(); i++){
arr2[i] = arr[n.length()-1-i];
}
int count = 0;
for (int i=0; i<n.length(); i++){
if(arr[i].equals(arr2[i])){
count++;
}
}
if(count == n.length()){
System.out.println("yes");
}
else{
System.out.println("no");
}
}
}
}
<file_sep>package WEEK_01;
import java.util.Scanner;
public class BAEKJOON_1008 {
public static void main(String[] args) {
//System.out.print("두 정수 A, B를 입력하세요.\n ");
Scanner scanner = new Scanner(System.in);
//System.out.print("A, B :");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
if (((0<a)&&(0<b)) && ((a<10)&&(b<10))){
System.out.println(a/b);
}
else {
System.out.println(" 0 < a,b < 10 인 값을 입력하세요. \n");
}
}
}
|
013ab4b99f565a0e14b05f3bfd1052606d8ffae0
|
[
"Java"
] | 6
|
Java
|
naa02/JAVA_practice
|
cc58bc3d53fb65adf8277959c3a5fd189c767611
|
fa38eb21cd1c2be0cc94a94601d4afc0448f4c4c
|
refs/heads/master
|
<repo_name>Grivladan/k-means-algo<file_sep>/k-means/k_means.py
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns; sns.set()
points = np.vstack(((np.random.randn(150, 2) * 0.75 + np.array([1, 0])),
(np.random.randn(50, 2) * 0.25 + np.array([-0.5, 0.5])),
(np.random.randn(50, 2) * 0.5 + np.array([-0.5, -0.5]))))
"""plt.scatter(points[:, 0], points[:, 1])
ax = plt.gca()
ax.add_artist(plt.Circle(np.array([1, 0]), 0.75/2, fill=False, lw=3))
ax.add_artist(plt.Circle(np.array([-0.5, 0.5]), 0.25/2, fill=False, lw=3))
ax.add_artist(plt.Circle(np.array([-0.5, -0.5]), 0.5/2, fill=False, lw=3))"""
def initialize_centroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k]
def closest_centroid(points, centroids):
"""returns an array containing the index to the nearest centroid for each point"""
distances = np.sqrt(((points - centroids[:, np.newaxis])**2).sum(axis=2))
return np.argmin(distances, axis=0)
def move_centroids(points, closest, centroids):
"""returns the new centroids assigned from the points closest to them"""
return np.array([points[closest==k].mean(axis=0) for k in range(centroids.shape[0])])
from matplotlib import animation
# create a simple animation
fig = plt.figure()
ax = plt.axes(xlim=(-4, 4), ylim=(-4, 4))
centroids = initialize_centroids(points, 3)
def init():
return
def animate(i):
global centroids
closest = closest_centroid(points, centroids)
centroids = move_centroids(points, closest, centroids)
ax.cla()
ax.scatter(points[:, 0], points[:, 1], c=closest)
ax.scatter(centroids[:, 0], centroids[:, 1], c='r', s=100)
return
ani = animation.FuncAnimation(fig, animate, init_func=init,
frames=10, interval=200, blit=False)
plt.show()
|
d5d8593d85618ef91ddc484664004d72a8605e37
|
[
"Python"
] | 1
|
Python
|
Grivladan/k-means-algo
|
ed3e1892bcb0dd35d1ca7973e39fd907f5e40c8e
|
6a13b8ba51549ea0efd8495e3fd2c5fd280d7286
|
refs/heads/main
|
<repo_name>cleitoncorreas/gamestore<file_sep>/src/styles/fonts.ts
export default {
heading: 'Inter_600SemiBold',
text: 'Inter_400Regular',
medium: 'Inter_500Medium'
}<file_sep>/src/styles/colors.ts
export default {
background: "#23232A",
main: "#66FFAC",
white: "#F0F0F0",
gray: "#D8D8D8",
dark_gray: "#3A3A3F"
}
|
cf13dfaf4c7d03dcfa6fbc37c17cbab9a5d15374
|
[
"TypeScript"
] | 2
|
TypeScript
|
cleitoncorreas/gamestore
|
a80dd48af23468dc77d6146b23769fabcb25880b
|
a4a2c2188f3f7cdbd75777ed1ccc4f7bc89c6d33
|
refs/heads/master
|
<repo_name>ybayart/servers-dedibox-bin<file_sep>/certbot
#!/bin/bash
docker run -i --rm --name certbot -v "/etc/letsencrypt:/etc/letsencrypt" -v "/var/lib/letsencrypt:/var/lib/letsencrypt" -v "/var/www/letsencrypt:/var/www/letsencrypt" certbot/certbot "$@"
<file_sep>/nginx
#!/bin/bash
docker exec nginx nginx "$@"
<file_sep>/adblock
#! /usr/bin/env bash
if [ "$(whoami)" != "root" ]
then
echo "Use script as root"
exit 1
fi
cd /data/bind9
mv /tmp/bind9.zip .
echo -n "Decompressing... "
unzip -o bind9.zip > /dev/null && echo done || echo KO
rm bind9.zip
sed -i "s/192.168.1.0\/24/$(dig +short yann5.hexanyn.fr)/g" bind/named.conf.options
echo -n "Restarting... "
/usr/bin/docker-compose restart 2>/dev/null && echo done || echo KO
<file_sep>/update-docker
#! /bin/bash
if [ ! "$1" ]
then
>&2 echo 'Please enter name of dir'
exit 1
fi
if cd /data/$1 > /dev/null 2>&1
then
OPWD=$PWD
cd /data/$1
docker-compose pull 2>&1
docker-compose down 2>&1
docker-compose up -d 2>&1
docker image prune --force 2>&1
cd $OPWD
else
>&2 echo "Directory '$1' doesn't exist"
fi
|
6a655dec61c73a1609c528778cadd370cab7377d
|
[
"Shell"
] | 4
|
Shell
|
ybayart/servers-dedibox-bin
|
ee9db6eafc3df00c3b97e8f82b6a9c315a1fe78e
|
2e838d1904384c613671b807ee3975676fcc97dc
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
class Timer extends Component {
state={
todayTimeused:0
};
componentDidMount(){
setInterval(() => {
let newTime= Date.now();
let todayTimeusedFull=newTime-this.props.time;
let todayTimeused=Math.round(todayTimeusedFull/1000);
this.setState({todayTimeused:todayTimeused});
console.log(this.state.todayTimeused);
}, 1000);
}
render() {
return (
<div>
<h1 >here is me and your time so come with us </h1>
<span>{this.state.todayTimeused} </span>
<h5>seconds </h5>
</div>
);
}
}
export default Timer;
|
eac04db978d2c0d01c9c67b0a63857342b2a755f
|
[
"JavaScript"
] | 1
|
JavaScript
|
satyaarthchhabra/timer
|
d0ea603b93ca934d2628a51eea7c1e163d87fc17
|
b4e5d7909aabff28841ef953046753d4cbfbaeb2
|
refs/heads/master
|
<repo_name>akantic/srcnn<file_sep>/model.py
import tensorflow as tf
import os
class SRCNN(object):
def __init__(self,
sess,
image_size,
label_size,
c):
self.sess = sess
self.image_size = image_size
self.label_size = label_size
self.c = c
self.images = tf.placeholder(tf.float32, [None, self.image_size, self.image_size, self.c], name='images')
self.labels = tf.placeholder(tf.float32, [None, self.label_size, self.label_size, self.c], name='labels')
self.pred = self.model()
self.loss = tf.reduce_mean(tf.square(self.labels - self.pred))
self.saver = tf.train.Saver()
def model(self):
weights = {
'w1': tf.Variable(tf.random_normal([9, 9, self.c, 64], stddev=1e-3), name='w1'),
'w2': tf.Variable(tf.random_normal([1, 1, 64, 32], stddev=1e-3), name='w2'),
'w3': tf.Variable(tf.random_normal([5, 5, 32, self.c], stddev=1e-3), name='w3')
}
biases = {
'b1': tf.Variable(tf.zeros([64], name='b1')),
'b2': tf.Variable(tf.zeros([32], name='b2')),
'b3': tf.Variable(tf.zeros([self.c], name='b3'))
}
conv1 = tf.nn.relu(tf.nn.conv2d(self.images, weights['w1'], strides=[1,1,1,1], padding='VALID') + biases['b1'])
conv2 = tf.nn.relu(tf.nn.conv2d(conv1, weights['w2'], strides=[1,1,1,1], padding='VALID') + biases['b2'])
conv3 = tf.nn.conv2d(conv2, weights['w3'], strides=[1,1,1,1], padding='VALID') + biases['b3']
return conv3
def load(self, checkpoint_dir):
print("\nReading Checkpoints...")
checkpoint_dir = os.path.join(checkpoint_dir, "srcnn")
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
ckpt_path = str(ckpt.model_checkpoint_path)
self.saver.restore(self.sess, os.path.join(os.getcwd(), ckpt_path))
print("\n Checkpoint Loading Success! %s\n"% ckpt_path)
else:
print("\n! Checkpoint Loading Failed \n")
def save(self, checkpoint_dir, step):
model_name = "SRCNN.model"
checkpoint_dir = os.path.join(checkpoint_dir, "srcnn")
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
self.saver.save(self.sess,
os.path.join(checkpoint_dir, model_name),
global_step=step)<file_sep>/main.py
import tensorflow as tf
from model import SRCNN
from train import train
from test import test
flags = tf.app.flags
config = flags.FLAGS
flags.DEFINE_integer("epoch", 1500, "Number of epoch")
flags.DEFINE_integer("image_size", 33, "The size of image input")
flags.DEFINE_integer("label_size", 21, "The size of image output")
flags.DEFINE_integer("f1", 9, "f1")
flags.DEFINE_integer("f2", 1, "f2")
flags.DEFINE_integer("f3", 5, "f3")
flags.DEFINE_integer("c", 3, "Image color channels")
flags.DEFINE_boolean("train", False, "Train or not")
flags.DEFINE_integer("scale", 3, "Image scale factor")
flags.DEFINE_integer("stride", 21, "Stride")
flags.DEFINE_string("checkpoint_dir", "checkpoint", "Checkpoint directory")
flags.DEFINE_float("learning_rate", 1e-4 , "Learning rate")
flags.DEFINE_string("image_name", "butterfly_GT.bmp", "image to use for testing")
def main(_):
with tf.Session() as sess:
if config.train:
srcnn = SRCNN(sess, image_size = config.image_size, label_size = config.label_size, c = config.c)
train(srcnn, config)
else:
diff = config.image_size - config.label_size
srcnn = SRCNN(sess, image_size = config.image_size + diff, label_size = config.image_size, c = config.c)
test(srcnn, config)
if __name__=='__main__':
tf.app.run()
<file_sep>/utils.py
import cv2
import numpy as np
import tensorflow as tf
import os
import glob
import h5py
import math
import scipy.misc
import scipy.ndimage
from PIL import Image
def modcrop(img, scale =3):
if len(img.shape) == 3:
h, w, _ = img.shape
h = h - np.mod(h, scale)
w = w - np.mod(w, scale)
img = img[0:h, 0:w, :]
else:
h, w = img.shape
h = h - np.mod(h, scale)
w = w - np.mod(w, scale)
img = img[0:h, 0:w]
return img
def imread(path):
img = cv2.imread(path)
return img
def imsave(image, path):
cv2.imwrite(os.path.join(os.getcwd(), path), image)
def preprocess(path, scale = 3, save=False):
img = imread(path)
label_ = modcrop(img, scale)
bicbuic_img = scipy.misc.imresize(label_, (1./scale), interp="bicubic")
input_ = scipy.misc.imresize(bicbuic_img, scale/1., interp="bicubic")
# bicbuic_img = cv2.resize(label_,None,fx = 1.0/scale ,fy = 1.0/scale, interpolation = cv2.INTER_CUBIC)# Resize by scaling factor
# input_ = cv2.resize(bicbuic_img,None,fx = scale ,fy=scale, interpolation = cv2.INTER_CUBIC)# Resize by scaling factor
if (save):
imsave(input_, "result/bicubic-" + path.split("/")[-1])
print("Bicubic PSNR", psnr(input_, label_))
return input_, label_
def postprocess(img):
x = img < 0
img[x] = 0
x = img > 1
img[x] = 1.0
img *= 255.
return img.astype(np.uint8)
def psnr(noisy_image, original_image):
im1 = cv2.cvtColor(noisy_image.astype(np.uint8), cv2.COLOR_BGR2YCR_CB)
im2 = cv2.cvtColor(original_image, cv2.COLOR_BGR2YCR_CB)
y1 = im1[:,:,0]
y2 = im2[:,:,0]
imdiff = y2-y1
rmse = math.sqrt(np.mean(imdiff**2))
psnr = 20*math.log10(255./rmse)
return psnr
def psnr_two(original_image, noisy_image):
checkimage(original_image)
checkimage(noisy_image)
h, w, c = original_image.shape
print("MAX: ", np.max(noisy_image), np.max(original_image * 255.))
mse = np.sum((original_image * 255. - noisy_image) ** 2)/(h*w*c)
if mse == 0:
return 100
PIXEL_MAX = 255.0
return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
def merge(images, size, shape):
print("[merge] Starting to merge the final image, sub_images size: {} into original shape: {}".format(size, shape))
h, w = images.shape[1], images.shape[2]
img = np.zeros((w*size[1], h*size[0], shape[2]))
for idx, image in enumerate(images):
i = idx % size[0]
j = idx // size[0]
img[j * h : j * h + h,i * w : i * w + w, :] = image
img = img[0:shape[0], 0:shape[1], :]
return img
def prepare_train_data(config):
data_dir = os.path.join(os.getcwd(), "Train")
data = glob.glob(os.path.join(data_dir, "*.*"))
print(data)
sub_input_sequence = []
sub_label_sequence = []
padding = abs(config.image_size - config.label_size) / 2
for i in range(len(data)):
input_, label_ = preprocess(data[i], config.scale)
if len(input_.shape) == 3:
h, w, c = input_.shape
else:
h, w = input_.shape
for x in range(0, h - config.image_size + 1, config.stride):
for y in range(0, w - config.image_size + 1, config.stride):
sub_input = input_[x: x + config.image_size, y: y + config.image_size]
sub_label = label_[x + int(padding): x + int(padding) + config.label_size, y + int(padding): y + int(padding) + config.label_size]
sub_input = sub_input.reshape([config.image_size, config.image_size, config.c])
sub_label = sub_label.reshape([config.label_size, config.label_size, config.c])
sub_input = sub_input / 255.0
sub_label = sub_label / 255.0
sub_input_sequence.append(sub_input)
sub_label_sequence.append(sub_label)
arrinput = np.asarray(sub_input_sequence)
arrlabel = np.asarray(sub_label_sequence)
print(arrinput.shape)
print(arrlabel.shape)
return arrinput, arrlabel
def prepare_test_data(config, image_name):
data_dir = os.path.join(os.getcwd(), "Test")
data = glob.glob(os.path.join(data_dir, image_name))
print(data)
sub_input_sequence = []
sub_label_sequence = []
help_sequence = []
input_, label_, = preprocess(data[0], config.scale, True)
if len(input_.shape) == 3:
h, w, c = input_.shape
else:
h, w = input_.shape
print(input_.shape)
nx, ny = 0, 0
padding = abs(config.image_size - config.label_size) / 2
diff = config.image_size - config.label_size
for x in range(0, h - config.image_size + 1, config.stride + diff):
for y in range(0, w - config.image_size + 1, config.stride + diff):
sub_input = input_[x: x + config.image_size, y: y + config.image_size] # 33 * 33
sub_input = np.pad(sub_input, ((6,6),(6,6),(0,0)), "edge")
sub_input = sub_input.reshape([config.image_size+12, config.image_size+12, config.c])
sub_label = label_[x + int(padding): x + int(padding) + config.label_size, y + int(padding): y + int(padding) + config.label_size] # 21 * 21
sub_label = sub_label.reshape([config.label_size, config.label_size, config.c])
sub_input = sub_input / 255.0
sub_label = sub_label / 255.0
sub_input_sequence.append(sub_input)
sub_label_sequence.append(sub_label)
if x+2*config.image_size > h:
sub_input = input_[x + config.image_size: h, y : y + config.image_size] # 33 * 33
sub_input = np.pad(sub_input, ((0,(x+2*config.image_size)-h), (0,0),(0,0)), "edge")
sub_input = np.pad(sub_input, ((6,6),(6,6),(0,0)), "edge")
sub_input = sub_input / 255.0
help_sequence.append(sub_input)
if y+2*config.image_size > w:
sub_input = input_[x: x + config.image_size, y + config.image_size: w] # 33 * 33
sub_input = np.pad(sub_input, ((0,0),(0,(y+2*config.image_size)-w),(0,0)), "edge")
sub_input = np.pad(sub_input, ((6,6),(6,6),(0,0)), "edge")
sub_input = sub_input / 255.0
sub_input_sequence.append(sub_input)
if (x+2*config.image_size > h) and (y+2*config.image_size > w):
sub_input = input_[x + config.image_size: h, y + config.image_size: w] # 33 * 33
sub_input = np.pad(sub_input, ((0,(x+2*config.image_size)-h),(0,(y+2*config.image_size)-w),(0,0)), "edge")
sub_input = np.pad(sub_input, ((6,6),(6,6),(0,0)), "edge")
sub_input = sub_input / 255.0
help_sequence.append(sub_input)
sub_label_sequence.append(sub_label)
sub_input_sequence.extend(help_sequence)
arrinput = np.asarray(sub_input_sequence)
arrlabel = np.asarray(sub_label_sequence)
print(arrinput.shape)
nx = math.ceil(w / config.image_size)
ny = math.ceil(h / (config.image_size))
print(nx, ny)
return arrinput, arrlabel, nx, ny, label_
<file_sep>/test.py
import tensorflow as tf
import time
import os
import numpy as np
from utils import prepare_test_data, merge, imsave, psnr, postprocess
def test(model, config):
input_, label_, nx, ny, original_image = prepare_test_data(config, config.image_name)
tf.initialize_all_variables().run()
print("Now Start Testing...")
model.load("checkpoint")
result = model.pred.eval({model.images: input_})
#print(label_[1] - result[1])
print(result.shape, np.squeeze(result).shape)
predicted_image = merge(result, [nx, ny], original_image.shape)
#image_LR = merge(input_, [nx, ny], self.c_dim)
#checkimage(image_LR)
img = postprocess(predicted_image)
imsave(img, 'result/' + "srcnn-" + config.image_name)
print("PSNR", psnr(img, original_image))
<file_sep>/README.md
Image super-resolution using deep convolutional neural networks, implementation of SRCNN in Python Tensorflow.
Master's degree thesis.
<file_sep>/train.py
import tensorflow as tf
import time
import os
import numpy as np
from utils import prepare_train_data
def train(model, config):
input_, label_ = prepare_train_data(config)
model.train_op = tf.train.AdamOptimizer(learning_rate=config.learning_rate).minimize(model.loss)
tf.initialize_all_variables().run()
counter = 0
time_ = time.time()
model.load("checkpoint")
print("Starting to train on {} images".format(input_.shape))
for ep in range(config.epoch):
batch_i = len(input_) // config.batch_size
for idx in range(0, batch_i):
batch_images = input_[idx * config.batch_size : (idx + 1) * config.batch_size]
batch_labels = label_[idx * config.batch_size : (idx + 1) * config.batch_size]
counter += 1
_, err = model.sess.run([model.train_op, model.loss], feed_dict={model.images: batch_images, model.labels: batch_labels})
if counter % 100 == 0:
print("Epoch: [%2d], step: [%2d], time: [%4.4f], loss: [%.8f]" % ((ep+1), counter, time.time()-time_, err))
if counter % 1000 == 0:
model.save("checkpoint", counter)
|
8251f0affc23c235d3e8ed1c99638612985f6fe7
|
[
"Markdown",
"Python"
] | 6
|
Python
|
akantic/srcnn
|
3aefebc9b977662dcf54bf2a13e1a71b2fb600ea
|
ed0324ed2490f6dc0b719067fadc98484b89c8d4
|
refs/heads/master
|
<repo_name>omkar806/HackethonIOforum<file_sep>/Hackethon/hackethonapp/views.py
from django.http.response import HttpResponse
from django.shortcuts import render,HttpResponse
import pyrebase
# Create your views here.
def index (request):
return render (request ,"index.html")
def signup(request):
return render(request , "signup.html")
# def postsignup(request):
<file_sep>/Hackethon/hackethonapp/apps.py
from django.apps import AppConfig
class HackethonappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'hackethonapp'
<file_sep>/Hackethon/hackethonapp/urls.py
from django.contrib import admin
from django.urls import path,include
from hackethonapp import views
urlpatterns = [
path("" , views.index , name="index"),
path("signup/" , views.signup , name="signup")
# path("postsignup" , views.postsignup , name="postsignup")
]
|
47d198d5a0916693a1cad2cdb0270a14121202d3
|
[
"Python"
] | 3
|
Python
|
omkar806/HackethonIOforum
|
477c6db5c3d071449e29b3786f440d9c30fd12e8
|
f2c523f68a1187a159ffe98b9182fde382952960
|
refs/heads/master
|
<file_sep>/* See LICENSE file for copyright and license details. */
#include <X11/XF86keysym.h>
/* appearance */
static const unsigned int borderpx = 1; /* border pixel of windows */
static const unsigned int snap = 32; /* snap pixel */
static const unsigned int gappx = 16;
static const int showbar = 1; /* 0 means no bar */
static const int topbar = 1; /* 0 means bottom bar */
static const char *fonts[] = {"noto-sans-emoji:size=10"};
static const char dmenufont[] = "noto-sans-emoji:size=10";
static const char col_gray1[] = "#282828"; // 222222
static const char col_gray2[] = "#1d2021"; // 444444
static const char col_gray3[] = "#d5c4a1"; // bbbbbb
static const char col_gray4[] = "#ebdbb2";
// static const char col_cyan[] = "#076678";
static const char col_cyan[] = "#2222ff";
static const unsigned int baralpha = 0x05;
static const char *colors[][3] = {
/* fg bg border */
[SchemeNorm] = {col_gray3, col_gray1, col_gray2},
[SchemeSel] = {col_gray4, col_cyan, col_cyan},
};
/* tagging */
static const char *tags[] = {"i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};
static const Rule rules[] = {
/* xprop(1):
* WM_CLASS(STRING) = instance, class
* WM_NAME(STRING) = title
*/
/* class instance title tags mask isfloating monitor */
{"Gimp", NULL, NULL, 0, 1, -1},
{"Firefox", NULL, NULL, 1 << 8, 0, -1},
};
/* layout(s) */
static const float mfact = 0.55; /* factor of master area size [0.05..0.95] */
static const int nmaster = 1; /* number of clients in master area */
static const int resizehints = 1; /* 1 means respect size hints in tiled resizals */
static const Layout layouts[] = {
/* symbol arrange function */
{"Tile", tile}, /* first entry is default */
{"Float", NULL}, /* no layout function means floating behavior */
{"Monocle", monocle},
};
/* key definitions */
#define MODKEY Mod4Mask
#define TAGKEYS(KEY, TAG) \
{MODKEY, KEY, view, {.ui = 1 << TAG}}, \
{MODKEY | ControlMask, KEY, toggleview, {.ui = 1 << TAG}}, \
{MODKEY | ShiftMask, KEY, tag, {.ui = 1 << TAG}}, \
{MODKEY | ControlMask | ShiftMask, KEY, toggletag, {.ui = 1 << TAG}},
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define SHCMD(cmd) \
{ \
.v = (const char *[]) { "/bin/sh", "-c", cmd, NULL } \
}
/* commands */
static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */
static const char *dmenucmd[] = {"dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL};
static const char *termcmd[] = {"alacritty", NULL};
static const char *firefoxcmd[] = {"firefox", NULL};
static const char *sptcmd[] = {"alacritty", "-e", "spt", NULL};
static const char *upvol[] = {"/usr/bin/pactl", "set-sink-volume", "0", "+5%", NULL};
static const char *downvol[] = {"/usr/bin/pactl", "set-sink-volume", "0", "-5%", NULL};
static const char *mutevol[] = {"/usr/bin/pactl", "set-sink-mute", "0", "toggle", NULL};
static Key keys[] = {
/* modifier key function argument */
{0, XF86XK_AudioLowerVolume, spawn, {.v = downvol}},
{0, XF86XK_AudioMute, spawn, {.v = mutevol}},
{0, XF86XK_AudioRaiseVolume, spawn, {.v = upvol}},
{MODKEY, XK_m, spawn, {.v = sptcmd}},
{MODKEY, XK_p, spawn, {.v = dmenucmd}},
{MODKEY, XK_Return, spawn, {.v = termcmd}},
{MODKEY, XK_b, togglebar, {0}},
{MODKEY, XK_j, focusstack, {.i = +1}},
{MODKEY, XK_k, focusstack, {.i = -1}},
{MODKEY, XK_i, incnmaster, {.i = +1}},
{MODKEY, XK_d, incnmaster, {.i = -1}},
{MODKEY, XK_h, setmfact, {.f = -0.05}},
{MODKEY, XK_l, setmfact, {.f = +0.05}},
{MODKEY, XK_space, zoom, {0}},
{MODKEY, XK_Tab, view, {0}},
{MODKEY, XK_q, killclient, {0}},
{MODKEY, XK_t, setlayout, {.v = &layouts[0]}},
{MODKEY | ShiftMask, XK_f, setlayout, {.v = &layouts[1]}},
{MODKEY, XK_m, setlayout, {.v = &layouts[2]}},
//{ MODKEY, XK_space, setlayout, {0} },
//{ MODKEY|ShiftMask, XK_space, togglefloating, {0} },
{MODKEY, XK_0, view, {.ui = ~0}},
{MODKEY | ShiftMask, XK_0, tag, {.ui = ~0}},
{MODKEY, XK_comma, focusmon, {.i = -1}},
{MODKEY, XK_period, focusmon, {.i = +1}},
{MODKEY | ShiftMask, XK_comma, tagmon, {.i = -1}},
{MODKEY | ShiftMask, XK_period, tagmon, {.i = +1}},
{MODKEY, XK_f, spawn, {.v = firefoxcmd}},
TAGKEYS(XK_1, 0)
TAGKEYS(XK_2, 1)
TAGKEYS(XK_3, 2)
TAGKEYS(XK_4, 3)
TAGKEYS(XK_5, 4)
TAGKEYS(XK_6, 5)
TAGKEYS(XK_7, 6)
TAGKEYS(XK_8, 7)
TAGKEYS(XK_9, 8){MODKEY | ShiftMask, XK_q, quit, {0}},
};
/* button definitions */
/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static Button buttons[] = {
/* click event mask button function argument */
{ClkLtSymbol, 0, Button1, setlayout, {0}},
{ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]}},
{ClkWinTitle, 0, Button2, zoom, {0}},
{ClkStatusText, 0, Button2, spawn, {.v = termcmd}},
{ClkClientWin, MODKEY, Button1, movemouse, {0}},
{ClkClientWin, MODKEY, Button2, togglefloating, {0}},
{ClkClientWin, MODKEY, Button3, resizemouse, {0}},
{ClkTagBar, 0, Button1, view, {0}},
{ClkTagBar, 0, Button3, toggleview, {0}},
{ClkTagBar, MODKEY, Button1, tag, {0}},
{ClkTagBar, MODKEY, Button3, toggletag, {0}},
};
|
3ca18c9d896673b59eda996d0a6103ec265b25a4
|
[
"C"
] | 1
|
C
|
accusitive/dwm
|
dbffa46d3d58f69c8c6c9c0741faa0a92fe0e7ea
|
d7d028a519992787bdd826d884dd86550773dfdf
|
refs/heads/master
|
<repo_name>sagiv1996/news<file_sep>/nuxt.config.js
export default {
server: {
port: 3333, // default: 3000
},
// Global page headers (https://go.nuxtjs.dev/config-head)
head: {
titleTemplate: '%s - news',
title: 'news',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/png', href: '/icon.png' }
]
},
// Global CSS (https://go.nuxtjs.dev/config-css)
css: [
],
vendor: ["aos"],
// Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
plugins: [
'@/plugins/rtl.js',
'@/plugins/CountryFlag.js',
{src: "@/Plugins/MarqueeText.js", mode: 'client'},
{src: "@/Plugins/aos.js", mode: 'client'}
],
purgeCSS: {
whitelist: ["aos-init", "aos-animate", "data-aos-delay", "data-aos-duration", "fade-up", "zoom-in"],
},
// Auto import components (https://go.nuxtjs.dev/config-components)
components: true,
// Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
buildModules: [
// https://go.nuxtjs.dev/vuetify
'@nuxtjs/vuetify',
],
// Modules (https://go.nuxtjs.dev/config-modules)
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
'@nuxtjs/onesignal',
// https://go.nuxtjs.dev/pwa
'@nuxtjs/pwa',
'vue-social-sharing/nuxt',
'nuxt-i18n',
],
// Axios module configuration (https://go.nuxtjs.dev/config-axios)
axios: {
baseURL: "http://newsapi.org/v2/top-headlines?apiKey=<KEY>",
},
// Vuetify module configuration (https://go.nuxtjs.dev/config-vuetify)
vuetify: {
},
// Build Configuration (https://go.nuxtjs.dev/config-build)
build: {
},
i18n: {
langDir: "locales/",
locales: [
{
code: 'ar',
iso: 'es-AR',
file: 'es.json',
name: 'Argentina'
},
{
code: 'au',
iso: 'en-AU',
file: 'en.json',
name: 'Australia'
},
{
code: 'at',
iso: 'de-AT',
file: 'de.json',
name: 'Austria'
},
{
code: 'be',
iso: 'nl-BE',
file: 'nl.json',
name: 'Belgium'
},
{
code: 'br',
iso: 'pt-BR',
file: 'pt.json',
name: 'Brazil'
},
{
code: 'bg',
iso: 'bg-BG',
file: 'bg.json',
name: 'Bulgaria'
},
{
code: 'ca',
iso: 'en-CA',
file: 'en.json',
name: 'Canada'
},
{
code: 'cn',
iso: 'zh-CN',
file: 'zh.json',
name: 'China'
},
{
code: 'co',
iso: 'es-CO',
file: 'es.json',
name: 'Colombia'
},
{
code: 'cu',
iso: 'es-CU',
file: 'es.json',
name: 'Cuba'
},
{
code: 'cz',
iso: 'cs-CZ',
file: 'cs.json',
name: 'Czech Republic'
},
{
code: 'eg',
iso: 'ar-EG',
file: 'ar.json',
name: 'Egypt'
},
{
code: 'fr',
iso: 'fr-FR',
file: 'fr.json',
name: 'France'
},
{
code: 'de',
iso: 'de-DE',
file: 'de.json',
name: 'Germany'
},
{
code: 'gr',
iso: 'el-GR',
file: 'el.json',
name: 'Greece'
},
{
code: 'hk',
iso: 'zh-HK',
file: 'zh.json',
name: 'Hong Kong SAR'
},
{
code: 'hu',
iso: 'hu-HU',
file: 'hu.json',
name: 'Hungary'
},
{
code: 'in',
iso: 'en-IN',
file: 'en.json',
name: 'India'
},
{
code: 'id',
iso: 'id-ID',
file: 'id.json',
name: 'Indonesia'
},
{
code: 'ie',
iso: 'en-IE',
file: 'en.json',
name: 'Ireland'
},
{
code: 'it',
iso: 'it-IT',
file: 'it.json',
name: 'Italy'
},
{
code: 'jp',
iso: 'ja-JP',
file: 'ja.json',
name: 'Japan'
},
{
code: 'kr',
iso: 'ko-KR',
file: 'ko.json',
name: 'Korea'
},
{
code: 'lv',
iso: 'lv-LV',
file: 'lv.json',
name: 'Latvia'
},
{
code: 'lt',
iso: 'lt-LT',
file: 'lt.json',
name: 'Lithuania'
},
{
code: 'my',
iso: 'ms-MY',
file: 'ms.json',
name: 'Malaysia'
},
{
code: 'mx',
iso: 'es-MX',
file: 'es.json',
name: 'Mexico'
},
{
code: 'ma',
iso: 'ar-MA',
file: 'ar.json',
name: 'Morocco'
},
{
code: 'nz',
iso: 'en-NZ',
file: 'en.json',
name: 'New Zealand'
},
{
code: 'ng',
iso: 'en-ng',
file: 'en.json',
name: 'Nigeria'
},
{
code: 'no',
iso: 'nb-NO',
file: 'nb.json',
name: 'Norway'
},
{
code: 'ph',
iso: 'en-PH',
file: 'en.json',
name: 'Philippines'
},
{
code: 'pl',
iso: 'pl-PL',
file: 'pl.json',
name: 'Poland'
},
{
code: 'pt',
iso: 'pt-PT',
file: 'pt.json',
name: 'Portugal'
},
{
code: 'ro',
iso: 'ro-RO',
file: 'ro.json',
name: 'Romania'
},
{
code: 'ru',
iso: 'ru-RU',
file: 'ru.json',
name: 'Russia'
},
{
code: 'rs',
iso: 'Cy-sr-SP',
file: 'sr.json',
name: 'Serbia'
},
{
code: 'sg',
iso: 'zh-SG',
file: 'zh.json',
name: 'Singapore'
},
{
code: 'sk',
iso: 'sk-SK',
file: 'sk.json',
name: 'Slovakia'
},
{
code: 'si',
iso: 'sl-SI',
file: 'sl.json',
name: 'Slovenia'
},
{
code: 'za',
iso: 'en-ZA',
file: 'en.json',
name: 'South Africa'
},
{
code: 'se',
iso: 'sv-SE',
file: 'sv.json',
name: 'Sweden'
},
{
code: 'ch',
iso: 'de-CH',
file: 'de.json',
name: 'Switzerland'
},
{
code: 'tw',
iso: 'zh-TW',
file: 'zh.json',
name: 'Taiwan'
},
{
code: 'th',
iso: 'th-TH',
file: 'th.json',
name: 'Thailand'
},
{
code: 'nl',
iso: 'nl-NL',
file: 'nl.json',
name: 'The Netherlands'
},
{
code: 'tr',
iso: 'tr-TR',
file: 'tr.json',
name: 'Turkey'
},
{
code: 'ua',
iso: 'uk-UA',
file: 'uk.json',
name: 'Ukraine'
},
{
code: 'ae',
iso: 'ar-AE',
file: 'ar.json',
name: 'United Arab Emirates'
},
{
code: 'gb',
iso: 'en-GB',
file: 'en.json',
name: 'United Kingdom'
},
{
code: 'us',
iso: 'en-US',
file: 'en.json',
name: 'United States'
},
{
code: 've',
iso: 'es-VE',
file: 'es.json',
name: 'Venezuela'
},
{
code: 'il',
iso: 'he-IL',
file: 'he.json',
name: 'israel'
},
{
code: 'sa',
iso: 'ar-SA',
file: 'ar.json',
name: 'schimbă limba'
}
],
seo: true,
strategy: "prefix_and_default",
defaultLocale: "il",
lazy: true,
vueI18nLoader: true,
},
pwa: {
manifest: {
start_url: '/pwa'
},
},
oneSignal: {
init: {
appId: 'dde5af34-ca4c-4263-9b87-d3195564ec70',
allowLocalhostAsSecureOrigin: true,
welcomeNotification: {
disable: true
}
}
}
}
<file_sep>/store/index.js
export const state = () => ({
host: null,
})
export const mutations = {
setApiHost (state, host) {
state.host = host
}
}
export const actions = {
nuxtServerInit ({ commit }, { req }) {
commit('setApiHost', req.headers.host)
}
}
|
b697d515c42c4227b76168e52f657ebde42dc821
|
[
"JavaScript"
] | 2
|
JavaScript
|
sagiv1996/news
|
15c197fe68f667aa3868c9dc486786a571868702
|
c18bb1d132732bf1b4327b4f8a3bd6f171620e7e
|
refs/heads/master
|
<repo_name>zevstravitz/Nux<file_sep>/client/types/api.ts
export interface ITerm {
id: string,
term: string,
acadyear: string
}
export interface ISchool {
id: string,
name: string
}
export interface ISubject {
abbv: string,
name: string,
path: string
}
export interface IPreviewClass {
abbv: string,
name: string,
path: string
}
export interface IClass1 {
id: string,
name: string,
topic: string,
section: string,
instructor: string[],
path: string,
meeting_time: string[],
overview_of_class: string
}
export interface IClass2 {
id: string,
lmod: string,
name: string,
title: string,
topic: string,
class_mtg_info: {
meet_t: string,
meet_l: string
}[],
instructor?: string[],
path?: string,
meeting_time?: string[],
descriptions?: {
name: string,
value: string
}[],
instructors?: {
instructor_name: string,
instructor_phone: string,
instructor_addr: string
}[],
enrl_requirement?: string,
class_attributes?: string
}<file_sep>/routes/api/search.js
const { Router } = require('express');
const config = require('../../config/index');
const axios = require('axios');
const { KEY } = config;
const router = Router()
const classPrefix = 'https://www.northwestern.edu/class-descriptions/';
const instructorPrefix = 'http://api.asg.northwestern.edu';
// Get Terms List
router.get('/terms', async (req, res) => {
try {
const terms =
await axios.get('https://www.northwestern.edu/class-descriptions/index-v2.json')
return res.send(terms.data);
} catch {
res.status(400).json({ msg: courses });
}
});
// Get Course List
router.get('/courses/:term/:school/:subject', async (req, res) => {
try {
const courses =
await axios.get(`${classPrefix}${term}/${school}/${subject}/index-v2.json`)
return res.send(courses.data);
} catch {
res.status(400).json({ msg: "Courses fetch failed" });
}
});
// Get Instructor List
router.get('/instructors/:subject', async (req, res) => {
try {
const instructors =
await axios.get(`${instructorPrefix}/instructors/?key=${KEY}&subject=${req.params.subject}`)
return res.send(instructors.data);
} catch (e) {
res.status(400).json({ msg: "Instructors Fetch Failed" });
}
});
module.exports = router;
|
5aa914cad5d909bfbbb433744163a26c9d95371f
|
[
"JavaScript",
"TypeScript"
] | 2
|
TypeScript
|
zevstravitz/Nux
|
5934c5a8edd80c906ab12dfb94a078d84b6ddaf1
|
17ec8398c63eb0ef9073f5a043f7d4be794fe1fb
|
refs/heads/master
|
<file_sep>package cn.springmvc.dao;
import cn.springmvc.model.Announcement;
public interface AnnouncementMapper {
int deleteByPrimaryKey(Integer id);
int insert(Announcement record);
int insertSelective(Announcement record);
Announcement selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Announcement record);
int updateByPrimaryKey(Announcement record);
}<file_sep>jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/reviewDB?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=<PASSWORD>
|
0116813df9a352b93f6f475a0977a05708760667
|
[
"Java",
"INI"
] | 2
|
Java
|
Auler/review
|
e8d38de152309287c5c56ce801034fe60c1ef6ea
|
a31b3bc916e27b0a45458740b926c2ace7cb3b12
|
refs/heads/master
|
<file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as dataset
from torch.nn.modules.normalization import LayerNorm
from torch.nn.init import xavier_uniform_
from Data import load_vocab, load_x
import numpy as np
import math
import os
def init_params(model, escape=None):
param_num = 0
for name, param in model.named_parameters():
if escape is not None and escape in name:
print('no_init', name, param.size())
continue
print('[init]', name, '[size]', param.size())
s_ = 1
for ax_ in param.size():
s_ *= ax_
param_num += s_
if param.data.dim() > 1:
xavier_uniform_(param.data)
print('[total params]', param_num)
def new_tensor(array, requires_grad=False):
tensor = torch.tensor(array, requires_grad=requires_grad)
# if torch.cuda.is_available():
# tensor = tensor.cuda()
return tensor
def create_emb_layer(emb_matrix, non_trainable=True):
vocab_size, emb_size = emb_matrix.size()
emb_layer = nn.Embedding(vocab_size, emb_size, padding_idx=0)
emb_layer.load_state_dict({'weight': emb_matrix})
if non_trainable:
emb_layer.weight.requires_grad = False
return emb_layer
class AutoEncoder(nn.Module):
# 训练自动编码机
def __init__(self, encoder, decoder, sos=1, eos=3):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.sos = sos
self.eos = eos
def forward(self, x, tgt, *args, **kwargs):
dec_inp = torch.cat([new_tensor([self.sos] * x.size(0), requires_grad=False).long().unsqueeze(1), x],
dim=1)
dec_tgt = torch.cat([x, new_tensor([0] * x.size(0), requires_grad=False).long().unsqueeze(1)], dim=1)
enc_out = self.encoder(x)
dec_out = self.decoder(dec_inp, enc_out, dec_tgt.ne(0).detach())
return F.cross_entropy(dec_out.view(-1, dec_out.size(-1)), dec_tgt.view(-1), ignore_index=0)
class Classifier(nn.Module):
# 训练情感分类器
def __init__(self, encoder, discriminator):
super().__init__()
self.encoder = encoder
self.discriminator = discriminator
def forward(self, x, tgt, *args, **kwargs):
enc_out = self.encoder(x)
out = self.discriminator(enc_out)
return F.binary_cross_entropy(out.view(-1), tgt.float().view(-1))
class Generator(nn.Module):
# 训练a>b, b>a两个生成器,希望可以骗过情感分类器,判别器并重建(三个loss)
def __init__(self, encoder, ab, ba, sent_discriminator, fake_discriminator):
super().__init__()
self.encoder = encoder
self.ab = ab
self.ba = ba
self.sent_discriminator = sent_discriminator
self.fake_discriminator = fake_discriminator
def forward(self, x, tgt, src='a', from_encoder=None, *args, **kwargs):
enc_out = self.encoder(x).detach() if from_encoder is None else from_encoder.detach()
if src == 'a':
forward = self.ab
backward = self.ba
else:
forward = self.ab
backward = self.ba
fake = forward(enc_out)
sent_predict = self.sent_discriminator(fake)
sent_loss = F.binary_cross_entropy(sent_predict.view(-1), tgt.float().view(-1))
fake_predict = self.fake_discriminator(fake)
fake_loss = F.binary_cross_entropy(fake_predict.view(-1), torch.tensor(1.).repeat(fake_predict.size(0)))
rebuild = backward(fake)
rebuild_loss = F.l1_loss(rebuild.view(-1), enc_out.view(-1))
return sent_loss.unsqueeze(0), fake_loss.unsqueeze(0), rebuild_loss.unsqueeze(0)
class Discriminator(nn.Module):
# 训练判别器,希望能分辨数据是否被生成器处理过
def __init__(self, encoder, ab, ba, fake_discriminator):
super().__init__()
self.encoder = encoder
self.ab = ab
self.ba = ba
self.fake_discriminator = fake_discriminator
def forward(self, x, tgt, src='a', from_encoder=None, *args, **kwargs):
enc_out = self.encoder(x).detach() if from_encoder is None else from_encoder.detach()
if src == 'a':
forward = self.ab
else:
forward = self.ab
fake = forward(enc_out).detach()
true_loss = F.binary_cross_entropy(self.fake_discriminator(enc_out).view(-1),
torch.tensor(1.).repeat(fake.size(0)))
fake_loss = F.binary_cross_entropy(self.fake_discriminator(fake).view(-1),
torch.tensor(0.).repeat(fake.size(0)))
return true_loss.unsqueeze(0), fake_loss.unsqueeze(0)
class WeakSupervision(nn.Module):
# 使用弱监督训练自动编码机和生成器
def __init__(self, encoder, ab, ba, decoder):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.ab = ab
self.ba = ba
def forward(self, x, tgt, src='a', *args, **kwargs):
if src == 'a':
forward = self.ab
else:
forward = self.ab
enc_out = self.encoder(x)
fake = forward(enc_out)
dec_inp = torch.cat([new_tensor([self.bos] * tgt.size(0), requires_grad=False).long().unsqueeze(1), tgt], dim=1)
dec_tgt = torch.cat([tgt, new_tensor([self.eos] * tgt.size(0), requires_grad=False).long().unsqueeze(1)], dim=1)
dec_out = self.decoder(dec_inp, fake)
return F.cross_entropy(dec_out, dec_tgt)
class Trainer:
def __init__(self, vocab_size, emb_size, d_model, nhead, num_layers, emb_matrix, multi_emb, hidden_size,
dim_feedforward):
from EUST import Encoder, Decoder, SentDiscriminator, FakeDiscriminator, A2B, B2A
self.vocab_size = vocab_size
if emb_matrix is None:
self.embedding = nn.Embedding(vocab_size, emb_size, padding_idx=0)
else:
self.embedding = create_emb_layer(emb_matrix)
self.encoder = Encoder(vocab_size=vocab_size, emb_size=emb_size, d_model=d_model, nhead=nhead,
num_layers=num_layers, emb_layer=self.embedding, multi_emb=multi_emb,
dim_feedforward=dim_feedforward)
self.decoder = Decoder(vocab_size=vocab_size, emb_size=emb_size, d_model=d_model, nhead=nhead,
num_layers=num_layers, emb_layer=self.embedding, dim_feedforward=dim_feedforward)
self.sent_discriminator = SentDiscriminator(d_model=d_model, nhead=multi_emb, hidden_size=10)
self.fake_discriminator = FakeDiscriminator(d_model=d_model, nhead=multi_emb, hidden_size=10)
self.ab = A2B(d_model=d_model, nhead=multi_emb, hidden_size=hidden_size)
self.ba = B2A(d_model=d_model, nhead=multi_emb, hidden_size=hidden_size)
self.encoder_optimizer = optim.Adam(self.encoder.parameters(), lr=3e-4)
self.decoder_optimizer = optim.Adam(self.decoder.parameters(), lr=3e-4)
self.sent_optimizer = optim.Adam(self.sent_discriminator.parameters(), lr=3e-4)
self.fake_optimizer = optim.Adam(self.sent_discriminator.parameters(), lr=3e-4)
self.ab_optimizer = optim.Adam(self.ab.parameters(), lr=3e-4)
self.ba_optimizer = optim.Adam(self.ba.parameters(), lr=3e-4)
self.AutoEncoder = AutoEncoder(self.encoder, self.decoder)
self.Classifier = Classifier(self.encoder, self.sent_discriminator)
self.Generator = Generator(self.encoder, self.ab, self.ba, self.sent_discriminator, self.fake_discriminator)
self.Discriminator = Discriminator(self.encoder, self.ab, self.ba, self.fake_discriminator)
self.WeakSupervision = WeakSupervision(self.encoder, self.ab, self.ba, self.decoder)
self.Model = {'encoder': (self.encoder, self.encoder_optimizer),
'decoder': (self.decoder, self.decoder_optimizer),
'sent_discriminator': (self.sent_discriminator, self.sent_optimizer),
'fake_discriminator': (self.fake_discriminator, self.fake_optimizer),
'ab': (self.ab, self.ab_optimizer),
'ba': (self.ba, self.ba_optimizer)}
self.Schedule = {'AutoEncoder': self.AutoEncoder,
'Classifier': self.Classifier,
'Generator': self.Generator,
'Discriminator': self.Discriminator,
'WeakSupervision': self.WeakSupervision}
self.Optimize = {'AutoEncoder': ('encoder', 'decoder'),
'Classifier': ('encoder', 'sent_discriminator'),
'Generator': ('ab', 'ba'),
'Discriminator': ('fake_discriminator',),
'WeakSupervision': ('encoder', 'ab', 'ba', 'decoder')}
self.init_params()
def init_params(self):
for model in self.Model:
print('################')
print('[init_params]', model)
init_params(self.Model[model][0])
print('################')
def train_batch(self, x, tgt, src, enable, epoch):
report = []
for schedule in enable:
optimizer = self.Optimize[schedule]
for p in optimizer:
self.Model[p][1].zero_grad()
loss = self.Schedule[schedule](x, tgt, src=src)
if isinstance(loss, tuple) or isinstance(loss, list):
loss = torch.cat(loss, dim=-1).mean()
closs = loss.cpu().item()
else:
loss = loss.mean()
closs = loss.cpu().item()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.Schedule[schedule].parameters(), 2)
for p in optimizer:
self.Model[p][1].step()
report.append('[epoch]{} [schedule]{} [loss]{}'.format(epoch, schedule, closs))
print(report[-1])
return report
def train_epoch(self, x, tgt, batch_size, enable, epoch):
data = dataset.TensorDataset(x, tgt)
train_loader = dataset.DataLoader(data, batch_size=batch_size, shuffle=True)
for j, data in enumerate(train_loader, 0):
self.train_batch(data[0], data[1], src='a', enable=enable, epoch=epoch)
def save_weights(self, path):
for model in self.Model:
torch.save(self.Model[model][0].state_dict(), path + '_' + model + '.pkl')
def load_weights(self, path):
for model in self.Model:
self.Model[model][0].load_state_dict(torch.load(path + '_' + model + '.pkl'))
if __name__ == '__main__':
# {'AutoEncoder': self.AutoEncoder,
# 'Classifier': self.Classifier,
# 'Generator': self.Generator,
# 'Discriminator': self.Discriminator,
# 'WeakSupervision': self.WeakSupervision}
args = dict(vocab_size=22543, emb_size=256, d_model=256, nhead=8, num_layers=2, emb_matrix=None, multi_emb=1,
hidden_size=10, dim_feedforward=2048)
agent = Trainer(**args)
# agent.load_weights('model/')
vocab2id, id2vocab, id2freq = load_vocab('data/vocab', t=2)
print(len(vocab2id))
data, label = load_x('data/test.tsv', vocab2id)
print(max([len(x) for x in data]))
print(len(data))
agent.train_epoch(torch.tensor([[1, 2, 3], [4, 5, 0], [3, 8, 6], [4, 4, 3]]),
torch.tensor([[1], [0], [1], [0]]),
batch_size=2, epoch=0,
enable=('AutoEncoder', 'Classifier', 'Generator', 'Discriminator',))
# agent.save_weights('model/')
<file_sep>import os
import codecs
import pickle
import torch
import numpy as np
import jieba
import sys
import time
PAD_WORD = '[PAD]'
BOS_WORD = '[BOS]'
UNK_WORD = '[UNK]'
EOS_WORD = '[EOS]'
SEP_WORD = '[SEP]'
CLS_WORD = '[CLS]'
MASK_WORD = '[MASK]'
def all_path(dirname):
"""
获得文件夹下所有文件列表
"""
result = []
for maindir, subdir, file_name_list in os.walk(dirname):
for filename in file_name_list:
apath = os.path.join(maindir, filename)
result.append(apath)
return result
def read_file(filename, vocab_dict, vocab_freq):
"""
读文件添加到词表里
filename:文件名
vocab_dict:词典
vocab_freq:词频
"""
with open(filename, "r", encoding='utf-8') as f:
for line in f:
for word in jieba.cut(line.split('\t')[1]):
if word in vocab_dict:
vocab_freq[vocab_dict[word]] += 1
else:
vocab_dict[word] = vocab_dict['[INDEX]']
vocab_dict['[INDEX]'] += 1
vocab_freq.append(1)
return vocab_dict, vocab_freq
def build_vocab(dirname, save_path):
"""
构建词典和词频
dirname:语料库的文件夹
save_path:保存词典,按词频顺序
"""
vocab_dict = {'[INDEX]': 0}
vocab_freq = []
path_list = all_path(dirname)
for filename in path_list:
vocab_dict, vocab_freq = read_file(filename, vocab_dict, vocab_freq)
STOP_WORD = ['[INDEX]', 'NaN', '<', 'SEP', '>']
vocab_freq.append(0)
vocab_list = list(vocab_dict.keys())
vocab_list.sort(key=lambda x: vocab_freq[vocab_dict[x]], reverse=True)
vocab_freq.sort(reverse=True)
with open(save_path, 'w') as wf:
for word, freq in zip(vocab_list, vocab_freq):
if word not in STOP_WORD:
wf.write(word + '\t' + str(freq) + '\n')
def load_vocab(vocab_file, t=0, vocab_size=None):
"""
从词频字典加载字典
vocab_file:词频字典
t:定义最小词频
vocab_size:词典大小
"""
thisvocab2id = {PAD_WORD: 0, BOS_WORD: 1, UNK_WORD: 2, EOS_WORD: 3, SEP_WORD: 4, CLS_WORD: 5, MASK_WORD: 6}
thisid2vocab = [PAD_WORD, BOS_WORD, UNK_WORD, EOS_WORD, SEP_WORD, CLS_WORD, MASK_WORD]
id2freq = [0 for _ in range(7)]
with codecs.open(vocab_file, 'r') as f:
for line in f:
try:
name, freq = line.strip('\n').strip('\r').split('\t')
except:
continue
if int(freq) >= t:
idx = len(thisid2vocab)
thisvocab2id[name] = idx
thisid2vocab.append(name)
id2freq.append(int(freq))
if vocab_size is not None and len(thisid2vocab) == vocab_size:
break
id2freq[0] = sum(id2freq) // len(id2freq)
id2freq[1] = id2freq[0]
id2freq[2] = id2freq[0]
id2freq[3] = id2freq[0]
print('item size: ', len(thisvocab2id))
return thisvocab2id, thisid2vocab, id2freq
def load_x(filename, vocab2idx):
"""
加载文本数据集
filename:数据集文件
vocab2id:vocab2id词典
"""
if os.path.exists(filename + '.pkl'):
with open(filename + '.pkl', 'rb') as f:
return pickle.load(f)
data = []
label = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
m, line = line.split('\t')
label.append(int(m))
data.append([vocab2idx.get(item, 2) for item in jieba.cut(line)] + [3])
# data.append([vocab2id.get(x, vocab2id[UNK_WORD]) for x in line.split(' ')] + [vocab2id[EOS_WORD]])
with open(filename + '.pkl', 'wb') as f:
pickle.dump((data, label), f)
return data, label
def load_embeddings(emb_text_filepath, vocab2idx, emb_dim):
"""
加载预训练词向量
emb_text_filepath:词向量文件
vocab2idx:vocab2idx词典
emb_dim:词向量大小
"""
if os.path.exists(emb_text_filepath + '.pkl'):
with open(emb_text_filepath + '.pkl', 'rb') as f:
return pickle.load(f)
matrix_len = len(vocab2idx)
emb_matrix = torch.zeros((matrix_len, emb_dim))
matched = [0 for _ in range(matrix_len)]
with open(emb_text_filepath, "r", encoding='utf-8') as f:
i = 0
for line in f:
tmp = line.strip().split(' ')
if len(tmp) < 300:
continue
name = ' '.join(tmp[:-300])
if name in vocab2idx:
emb_matrix[vocab2idx[name]] = torch.tensor([float(x) for x in tmp[-300:]])
matched[vocab2idx[name]] = 1
if i % 20000 == 0:
print(i, sum(matched), '/', matrix_len)
i += 1
for i in range(matrix_len):
if matched[i] != 1:
emb_matrix[i] = torch.tensor(np.random.normal(scale=0.6, size=(emb_dim,)))
with open(emb_text_filepath + '.pkl', 'wb') as f:
pickle.dump(emb_matrix, f)
return emb_matrix
if __name__ == '__main__':
# from transformers import BertTokenizer
#
# tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
# x, y = load_x('data/train.tsv', tokenizer)
# build_vocab('data/s', 'data/vocab')
vocab2id, id2vocab, id2freq = load_vocab('data/vocab', t=2)
print(len(vocab2id))
data, label = load_x('data/test.tsv', vocab2id)
print(max([len(x) for x in data]))
print(len(data))
<file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.normalization import LayerNorm
import numpy as np
import math
NEAR_INF = 1e20
NEAR_INF_FP16 = 65504
def neginf(dtype):
if dtype is torch.float16:
return -NEAR_INF_FP16
else:
return -NEAR_INF
def new_tensor(array, requires_grad=False):
tensor = torch.tensor(array, requires_grad=requires_grad)
# if torch.cuda.is_available():
# tensor = tensor.cuda()
return tensor
def universal_sentence_embedding(sentences, mask, sqrt=True):
sentence_sums = torch.bmm(
sentences.permute(0, 2, 1), mask.float().unsqueeze(-1)
).squeeze(-1)
divisor = (mask.sum(dim=1).view(-1, 1).float())
if sqrt:
divisor = divisor.sqrt()
sentence_sums /= divisor
return sentence_sums
def _generate_square_subsequent_mask(sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, neginf(torch.float32)).masked_fill(mask == 1, float(0.0))
# if torch.cuda.is_available():
# mask = mask.cuda()
return mask
def create_emb_layer(emb_matrix, non_trainable=True):
vocab_size, emb_size = emb_matrix.size()
emb_layer = nn.Embedding(vocab_size, emb_size, padding_idx=0)
emb_layer.load_state_dict({'weight': emb_matrix})
if non_trainable:
emb_layer.weight.requires_grad = False
return emb_layer
class PositionalEmbedding(nn.Module):
def __init__(self, embedding_size, dropout=0.1, max_len=5000):
super(PositionalEmbedding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, embedding_size)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, embedding_size, 2).float() * (-math.log(10000.0) / embedding_size))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, x):
p = self.pe[:x.size(-2)]
for i in range(len(x.size()) - 2):
p = p.unsqueeze(0)
x = x + p
return self.dropout(x)
class Encoder(nn.Module):
def __init__(self, vocab_size, emb_size, d_model, nhead=1, num_layers=1, emb_layer=None, multi_emb=2,
dim_feedforward=2018):
super().__init__()
self.multi_emb = multi_emb
self.embedding = emb_layer
self.emb_dropout = nn.Dropout(0.1)
self.pos_embedding = PositionalEmbedding(emb_size)
self.utterEnc = nn.TransformerEncoder(
encoder_layer=nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward),
num_layers=num_layers,
norm=LayerNorm(d_model))
self.ext = nn.Linear(d_model, d_model * multi_emb)
self.multi_pre = nn.TransformerEncoderLayer(d_model * multi_emb, multi_emb, dim_feedforward=dim_feedforward,
dropout=0.1,
activation='relu')
def forward(self, x):
mask = x.ne(0).detach()
batch_size = x.size(0)
out = self.pos_embedding(self.emb_dropout(self.embedding(x)))
out = self.utterEnc(out.transpose(0, 1), src_key_padding_mask=~mask).transpose(0, 1)
out = self.ext(out)
out = self.multi_pre(out.transpose(0, 1), src_key_padding_mask=~mask).transpose(0, 1)
pres = universal_sentence_embedding(out, mask)
pres = pres.view(batch_size, self.multi_emb, -1)
return pres
class Decoder(nn.Module):
def __init__(self, vocab_size, emb_size, d_model, nhead=1, num_layers=1, emb_layer=None, dim_feedforward=2018):
super().__init__()
self.embedding = emb_layer
self.emb_dropout = nn.Dropout(0.1)
self.pos_embedding = PositionalEmbedding(emb_size)
self.utterDec = nn.TransformerDecoder(
decoder_layer=nn.TransformerDecoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward),
num_layers=num_layers,
norm=LayerNorm(d_model))
self.fc = nn.Linear(d_model, vocab_size)
def forward(self, tgt, memory, mask):
tgt = self.pos_embedding(self.emb_dropout(self.embedding(tgt)))
tgt_out = self.utterDec(tgt.transpose(0, 1), memory.transpose(0, 1),
tgt_mask=_generate_square_subsequent_mask(tgt.size(1)),
tgt_key_padding_mask=~mask).transpose(0, 1)
tgt_out = self.fc(tgt_out)
return tgt_out
def inference(self, memory, bos):
N, L, S = memory.size()
decoder_input = new_tensor([bos] * batch_size, requires_grad=False)
all_decode_outputs = [dict({'state': decoder_states})]
greedy_indices = list()
greedy_end = new_tensor([0] * batch_size).long() == 1
for t in range(max_len):
decode_outputs = model.decode(
data, decoder_input, encode_outputs, all_decode_outputs[-1]
)
gen_output = model.generate(data, encode_outputs, decode_outputs, softmax=True)
probs, ids = model.to_word(data, gen_output, 1)
all_decode_outputs.append(decode_outputs)
greedy_indice = ids[:, 0]
greedy_this_end = greedy_indice == EOS
if t == 0:
greedy_indice.masked_fill_(greedy_this_end, UNK)
else:
greedy_indice.masked_fill_(greedy_end, PAD)
greedy_indices.append(greedy_indice.unsqueeze(1))
greedy_end = greedy_end | greedy_this_end
decoder_input = model.generation_to_decoder_input(data, greedy_indice)
greedy_indice = torch.cat(greedy_indices, dim=1)
return greedy_indice
class SentDiscriminator(nn.Module):
def __init__(self, d_model, nhead, hidden_size):
super().__init__()
self.hidden = nn.Linear(d_model * nhead, hidden_size)
self.fc = nn.Linear(hidden_size, 1)
self.activation = nn.Sigmoid()
def forward(self, x):
x = x.view(x.size(0), -1)
out = self.hidden(x)
out = self.fc(out)
out = self.activation(out)
return out
class FakeDiscriminator(nn.Module):
def __init__(self, d_model, nhead, hidden_size):
super().__init__()
self.hidden = nn.Linear(d_model * nhead, hidden_size)
self.fc = nn.Linear(hidden_size, 1)
self.activation = nn.Sigmoid()
def forward(self, x):
x = x.view(x.size(0), -1)
out = self.hidden(x)
out = self.fc(out)
out = self.activation(out)
return out
class A2B(nn.Module):
def __init__(self, d_model, nhead, hidden_size):
super().__init__()
self.enc = nn.Linear(d_model * nhead, hidden_size)
self.dec = nn.Linear(hidden_size, d_model * nhead)
def forward(self, x):
N, H, L = x.size()
x = x.view(N, -1)
out = self.enc(x)
out = self.dec(out)
return (x + out).view(N, H, L)
class B2A(nn.Module):
def __init__(self, d_model, nhead, hidden_size):
super().__init__()
self.enc = nn.Linear(d_model * nhead, hidden_size)
self.dec = nn.Linear(hidden_size, d_model * nhead)
def forward(self, x):
N, H, L = x.size()
x = x.view(x.size(0), -1)
out = self.enc(x)
out = self.dec(out)
return (x + out).view(N, H, L)
if __name__ == '__main__':
emb = nn.Embedding(10, 4, padding_idx=0)
ec = Encoder(vocab_size=10, emb_size=4, d_model=4, nhead=1, num_layers=1, emb_layer=emb, multi_emb=2)
dc = Decoder(vocab_size=10, emb_size=4, d_model=4, nhead=1, num_layers=1, emb_layer=emb)
sc = SentDiscriminator(d_model=4, nhead=2, hidden_size=10)
fk = FakeDiscriminator(d_model=4, nhead=2, hidden_size=10)
ab = A2B(d_model=4, nhead=2, hidden_size=10)
ba = B2A(d_model=4, nhead=2, hidden_size=10)
tmp = ec(torch.tensor([[1, 2, 3], [4, 5, 0]]))
res = dc(torch.tensor([[1, 2, 3, 4], [4, 5, 0, 0]]), tmp)
cls = sc(tmp)
trs = ab(tmp)
print(tmp.size(), res.size(), cls.size(), trs.size())
<file_sep># SDU-BigData-team
SDU-BigData-team created by GitHub Classroom
|
91dfd6a9c715537f6c3b0c9222fbec649c8f5401
|
[
"Markdown",
"Python"
] | 4
|
Python
|
SDUBigDataCourse/SDU-BigData-team
|
90de35419a73d822b357ba219ee5079f2a478507
|
8c99e10d43ce1517ef0f1932d06f60ca7e0bfec8
|
refs/heads/main
|
<repo_name>FlosWelt/tlfbot<file_sep>/index.js
const Discord = require("discord.js")
const client = new Discord.Client()
const config = require("./config.json")
//const client = new Discord.Client()
//const queue = new Map();
client.login(config.token)
const activities_list = [
"Mitglieder",
".help",
"discord.gg/qRhTWUQPzf",
"Moderatoren",
"sich den Server an"
]; // creates an arraylist containing phrases you want your bot to switch through.
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
zaehler = 0
setInterval(() => {
zaehler = zaehler + 1;
if (zaehler === 5) {
zaehler = 0;
}
const index = zaehler; // generates a random number between 1 and the length of the activities array list (in this case 5).
client.user.setActivity(activities_list[index],{type: "WATCHING"}); // sets bot's activities to one of the phrases in the arraylist.
//onsole.log(`Still online!` + Date.now() + `Zaehler:` + zaehler);
}, 10 * 1000); // Runs this every 10 seconds.
setInterval(() => {
//client.user.setActivity(activities_list[index],{type: "WATCHING"}); // sets bot's activities to one of the phrases in the arraylist.
//console.log(`Still online!` + Date.now() + `Zaehler:` + zaehler);
client.channels.fetch("800690431759351811")
.then(channel => channel.send(`
╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬:arrow_right: TLF :arrow_left:╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝
Was ihr hier seht? TLF
TLF ist ein Server, der noch am Anfang steht
Wir freuen uns über jedes neue Mitglied, dass den Server ein Stück weit aktiver macht
Egal ob Du ein Zocker bist, ein Künstler bist oder einfach gerne entspannst: Bei uns bist Du jederzeit Willkommen
Das Beste
:infinity: Häufige Gewinnspiele bei denen man Server, Steamkeys, Nitro und viel mehr gewinnen kann
:infinity: Du kannst bei uns das moderieren erlernen (bei großen Servern braucht man meistens schon Erfahrung, die Du bei uns sammeln kannst)
════════════════════════════════════════
Und das bieten wir
:white_check_mark: Ein übersichtliches Regelwerk :books:
:white_check_mark: Die Möglichkeit, in unser Team zu kommen :white_check_mark:
:white_check_mark: Die Möglichkeit, Partner zu werden :newspaper:
:white_check_mark: Ein Casino, in dem ihr ein wöchentliches Einkommen bekommen könnt :moneybag:
:white_check_mark: Ein Kopfgeld System :bust_in_silhouette:
:white_check_mark: Einen guten Musikbot :headphones:
:white_check_mark: (Fast) keine everyone pings :mute:
:white_check_mark: Übersichtliche Kanäle :dividers:
:white_check_mark: Einen eigenen Memechannel mit dem beliebtem Dankmemer :frog:
:white_check_mark: Reaction roles :performing_arts:
:white_check_mark: Ein Levelsystem, dass für Aktivität belohnt :first_place:
:white_check_mark: lustige Minigames wie TicTacToe :game_die:
:white_check_mark: Giveaways bei allen Meilensteinen und auch Giveaways ohne besonderen Anlass :tada:
════════════════════════════════════════
Du möchtest jetzt auf unseren Server kommen?
Dann klick einfach auf die Einladung
Viel Spaß auf dem Server:thumbsup:
https://discord.gg/UVeKuzrDA7
`));
}, 20 * 1000); // Runs this every 10 seconds.
});
client.on("message", function(message) {
const args = message.content.split(' ');
const command = args.shift().toLowerCase();
if (command === ".help") {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('TLF Hilfe')
.setURL('https://tlfbot.floswelt.com')
.setAuthor('Tlf Bot 1.0', 'https://cdn.discordapp.com/attachments/818871522164080701/819228760528125982/image0.png', 'https://discord.gg/7S49xvb7GC')
.setDescription('Hilfe des Tlf Servers.')
.setThumbnail('https://cdn.discordapp.com/attachments/818871522164080701/819228760528125982/image0.png')
.addFields(
{ name: 'Moderatoren Hilfe', value: 'Um mit unseren Moderatoren in Kontakt zu kommen gehe in #🎫︱ticket-erstellen.' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Bot Commands', value: 'Klicke hier um alle BotCommands an zusehen: https://tlfbot.floswelt.com', inline: true },
{ name: 'Coming Soon...', value: '--- ', inline: true },
)
.addField('Bot Status:', 'https://status.floswelt.com/', true)
//.setImage('https://cdn.discordapp.com/attachments/818871522164080701/819228760528125982/image0.png')
.setTimestamp()
.setFooter('© TLF', 'https://cdn.discordapp.com/attachments/818871522164080701/819228760528125982/image0.png');
message.channel.send(exampleEmbed);
}}
);
<file_sep>/README.md
DEPRECATED!!!
The Bot was created for the Tlf Discord Server([Invite](https://discord.gg/ahfYvC39SM) [German Server]).
|
51ca6881cfb862d18d3d3ac6164159c79c8daafe
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
FlosWelt/tlfbot
|
a4506f2cb365e857440873b1f09da281d90cadd4
|
0303aa90b7535e4cf98f0f1936df214ed0349f57
|
refs/heads/master
|
<file_sep>import React from "react"
import BookShelf from "./BookCase"
import './App.css'
import { Link } from 'react-router-dom'
class MainPage extends React.Component {
switchBookOnShelves = (shelf, book) => {
this.props.onSwitchBookOnShelves(shelf, book)
};
render() {
return (
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<div className="list-books-content">
<div>
<BookShelf name="Currently Reading" books={this.props.currentlyreading} onSwitchBookOnShelves={this.switchBookOnShelves}/>
<BookShelf name="Want to Read" books={this.props.wantToRead} onSwitchBookOnShelves={this.switchBookOnShelves}/>
<BookShelf name="Read" books={this.props.read} onSwitchBookOnShelves={this.switchBookOnShelves}/>
</div>
</div>
<div className="open-search">
<Link to="/search">
<button>Add a book</button>
</Link>
</div>
</div>
)
}
}
export default MainPage;<file_sep>import React from 'react'
import * as BooksAPI from './BooksAPI'
import './App.css'
import MainPage from "./MainPage"
import SearchPage from "./SearchPage"
import { Route } from 'react-router-dom'
class BooksApp extends React.Component {
state = {
books: [],
currentlyreading: [],
read: [],
wantToRead: []
}
componentDidMount() {
BooksAPI.getAll().then(books => {
this.updateBookState(books)
});
}
updateBookState = (books) => {
const currentlyreading = books
.filter(book => book.shelf === "currentlyReading");
const read = books
.filter(book => book.shelf === "read");
const wantToRead = books
.filter(book => book.shelf === "wantToRead");
this.setState(() => ({
books: books,
currentlyreading: currentlyreading,
read: read,
wantToRead: wantToRead
}));
}
switchBookOnShelves = (shelf, book) => {
const allbook = this.state.books;
const newBooks = allbook.map(filteredbook => {
if (filteredbook.id === book.id) {
filteredbook.shelf = shelf
}
return filteredbook;
})
this.updateBookState(newBooks);
BooksAPI.update(book, shelf);
};
addBook = (shelf, book) => {
let updatebooks = this.state.books;
updatebooks.push(book)
this.setState(() => ({
books: updatebooks
}))
this.switchBookOnShelves(shelf, book)
}
render() {
return (
<div className="app">
<Route exact path='/' render={() => (
<MainPage
books={this.state.books}
currentlyreading={this.state.currentlyreading}
read={this.state.read}
wantToRead={this.state.wantToRead}
onSwitchBookOnShelves={this.switchBookOnShelves}
/>
)}
/>
<Route exact path='/search' render={() => (
<SearchPage books={this.state.books}
onAddBook={this.addBook}/>
)}
/>
</div>
)
}
}
export default BooksApp;
|
59b8a1f50bab61110994ac6394eca7a6bead6f23
|
[
"JavaScript"
] | 2
|
JavaScript
|
NarutoUzumaki77/myReads
|
a41350a2c8d7c08642f6f71b6d215c4ed87c3cfa
|
736d42d0cf02ceea6cf09b0bc29be02f5c6b75e1
|
refs/heads/master
|
<file_sep>package com.wext.hunting.views;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.wext.hunting.MainActivity;
import com.wext.hunting.R;
import com.wext.hunting.models.User;
public class Register extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private User user = new User("","","");
private ClickRegistro clickRegistro;
private DatabaseReference mDatabase;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public class ClickRegistro{
private EditText email, password, cpassword, user;
private ClickRegistro(EditText email, EditText password,EditText cpassword, EditText user){
this.email = email;
this.password = <PASSWORD>;
this.cpassword = <PASSWORD>;
this.user = user;
}
public void regisIn(View view){
final String correo = email.getText().toString().trim();
String pass = password.getText().toString().trim();
String cpass = cpassword.getText().toString().trim();
final String usuario = user.getText().toString().trim();
if (TextUtils.isEmpty(correo)){
Toast.makeText(Register.this, "Introduce un email",
Toast.LENGTH_SHORT).show();
return;
}
else if (!Patterns.EMAIL_ADDRESS.matcher(correo).matches()){
Toast.makeText(Register.this, "Introduce un email Valido",
Toast.LENGTH_SHORT).show();
return;
}
else if (pass.length() <= 5){
Toast.makeText(Register.this, "El password debe de tener al menos 6 caracteres",
Toast.LENGTH_SHORT).show();
return;
}
else if (!pass.equals(cpass)){
Toast.makeText(Register.this, "El password no coincide",
Toast.LENGTH_SHORT).show();
return;
}
else{
progressDialog.setTitle("Registrando usuario");
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
//Escritura a DataBase
mDatabase = FirebaseDatabase.getInstance().getReference("Usuarios");
firebaseAuth.createUserWithEmailAndPassword(correo, pass)
.addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
mDatabase.child(user.getUid()).child("user").setValue(usuario);
mDatabase.child(user.getUid()).child("mail").setValue(correo);
updateUI(user);
progressDialog.dismiss();
} else {
// If sign in fails, display a message to the user.
progressDialog.dismiss();
Toast.makeText(Register.this, "Error de Comunicacion",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
}
}
private void updateUI (FirebaseUser user){
if(user != null){
Toast.makeText(Register.this, "Usuario Registrado",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
else {
}
}
}
<file_sep>include ':app'
rootProject.name='HMC'
|
846476786e4753f72574f71dcb1414d18b5a8e0a
|
[
"Java",
"Gradle"
] | 2
|
Java
|
Jos9eM/Hunting
|
70c1a838d6f0ff14981723bb1394eb2369b291f0
|
02047791419a16005795f14fbd570df213ff25e6
|
refs/heads/master
|
<file_sep>import { Contacto } from './contacto';
export class Cliente{
codigo:number;
nombre:string;
contactos:Contacto[];
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http'; // necesario para REST
import { CamareroService } from './services/camarero.service';
import { ClienteService } from './services/cliente.service';
import { ProductoService } from './services/producto.service';
import { PedidoService } from './services/pedido.service';
import { Camarero2Service } from './services/camarero2.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, HttpClientModule
],
providers:[ CamareroService,
ClienteService,
ProductoService,
PedidoService,
Camarero2Service
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { CamareroService } from './services/camarero.service';
import { Camarero } from './model/camarero';
import { Cliente } from './model/cliente';
import { ClienteService } from './services/cliente.service';
import { Producto } from './model/producto';
import { ProductoService } from './services/producto.service';
import { PedidoService } from './services/pedido.service';
import { Pedido } from './model/pedido';
import { Camarero2Service } from './services/camarero2.service';
import { Camarero2 } from './model/camarero2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
camareros:Camarero[] = undefined;
clientes:Cliente[] = undefined;
productos:Producto[] = undefined;
pedidos:Pedido[] = undefined;
camareros2:Camarero2[] = undefined;
constructor(private camareroService:CamareroService,
private clienteService:ClienteService,
private productoService:ProductoService,
private pedidoService:PedidoService,
private camarero2Service:Camarero2Service){}
ngOnInit(): void {
this.pedidoService.getAll().subscribe(datos => {
this.pedidos = datos;
});
this.camareroService.getAll().subscribe(datos => {
this.camareros = datos;
});
this.clienteService.getAll().subscribe(datos => {
this.clientes = datos;
});
this.productoService.getAll().subscribe(datos => {
this.productos = datos;
});
this.camarero2Service.getAll().subscribe(datos =>
this.camareros2 = datos)
}
// funciones para poder añadir elementos en Camarero y clientes
crearCamarero(){
let codigoAleatorio:number = Math.floor(Math.random() * 100000);
let camarero = new Camarero();
camarero.codigo = codigoAleatorio;
camarero.nombre = "camarero_sinensia_" + codigoAleatorio;
this.camareroService.create(camarero).subscribe(datos => {
console.log(datos);
});
}
crearCliente(){
let cliente = {
codigo:222,
nombre:"Pepito222",
contactos: [
{
nombre:"<NAME>",
telefono:"222222"
}
]
}
this.clienteService.create(cliente).subscribe(datos => {
console.log(datos);
});
}
}
<file_sep>
export class Camarero2 {
codigo:number;
nombre:string;
}<file_sep>export class Contacto{
nombre:string;
telefono:string;
}
|
1ae5ca1b9b319ea3dcd4b1903f3d62e965dff8fe
|
[
"TypeScript"
] | 5
|
TypeScript
|
jgverges/clientehttphw_profe
|
806d06f457a6fa571b8ef65841cb6353aa6f7fcc
|
8b42677bd943c79cac2dbb0910e424d40584fee5
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import csv
import sys
fname = sys.argv[1]
with open(fname, 'r') as fi:
r = csv.reader(fi)
print('| Year | Mean |')
print('| ---- | ---- |')
for row in r:
print('| {} |'.format(' | '.join(row)))
<file_sep>!/bin/bash
# [wf]: validate results and get a table
set -ex
# [wf]: verify that we got actual result values
scripts/validate_output.py data/global_per_capita_mean.csv
# [wf]: generate markdown table
scripts/get_mdown_table.py data/global_per_capita_mean.csv
<file_sep>#!/bin/bash
# [wf]: obtain n-year means
set -ex
# [wf]: group every n years and obtain mean over each group
scripts/get_mean.py data/global_clean.csv 5
|
51bcf667cf8edfe9290e7e45ffb757a8e2eab8e3
|
[
"Python",
"Shell"
] | 3
|
Python
|
carlosmalt/co2-emissions
|
200a08ddec62ce2d79d912ba6bf10ad24f8eda60
|
e149524100c16202e80dfbfac102faf4f349b894
|
refs/heads/master
|
<repo_name>jjshi/pdo_kdb<file_sep>/kdb_driver.c
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2013 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include<stdio.h>
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "ext/standard/file.h"
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
#include "kingbase-type.h" /* needed for PG_VERSION */
#include "php_pdo_kdb.h"
#include "php_pdo_kdb_int.h"
#include "zend_exceptions.h"
static char * _pdo_kdb_trim_message(const char *message, int persistent)
{
register int i = strlen(message)-1;
char *tmp;
if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
--i;
}
while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
--i;
}
++i;
tmp = pemalloc(i + 1, persistent);
memcpy(tmp, message, i);
tmp[i] = '\0';
return tmp;
}
int _pdo_kdb_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *file, int line TSRMLS_DC) /* {{{ */
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
pdo_kdb_error_info *einfo = &H->einfo;
char *errmsg = KCIConnectionGetLastError(H->server);
einfo->errcode = errcode;
einfo->file = file;
einfo->line = line;
if (einfo->errmsg) {
pefree(einfo->errmsg, dbh->is_persistent);
einfo->errmsg = NULL;
}
if (sqlstate == NULL || strlen(sqlstate) >= sizeof(pdo_error_type)) {
strcpy(*pdo_err, "HY000");
}
else {
strcpy(*pdo_err, sqlstate);
}
if (errmsg) {
einfo->errmsg = _pdo_kdb_trim_message(errmsg, dbh->is_persistent);
}
if (!dbh->methods) {
zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
*pdo_err, einfo->errcode, einfo->errmsg);
}
return errcode;
}
/* }}} */
static void _pdo_kdb_notice(pdo_dbh_t *dbh, const char *message) /* {{{ */
{
/* pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data; */
}
/* }}} */
static int pdo_kdb_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC) /* {{{ */
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
pdo_kdb_error_info *einfo = &H->einfo;
if (einfo->errcode) {
add_next_index_long(info, einfo->errcode);
add_next_index_string(info, einfo->errmsg, 1);
}
return 1;
}
/* }}} */
/* {{{ pdo_kdb_create_lob_stream */
static size_t kdb_lob_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
{
struct pdo_kdb_lob_self *self = (struct pdo_kdb_lob_self*)stream->abstract;
return KCIBlobWrite(self->conn, self->lfd, (char*)buf, count);
}
static size_t kdb_lob_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
struct pdo_kdb_lob_self *self = (struct pdo_kdb_lob_self*)stream->abstract;
return KCIBlobRead(self->conn, self->lfd, buf, count);
}
static int kdb_lob_close(php_stream *stream, int close_handle TSRMLS_DC)
{
struct pdo_kdb_lob_self *self = (struct pdo_kdb_lob_self*)stream->abstract;
pdo_dbh_t *dbh = self->dbh;
if (close_handle) {
KCILobClose(self->conn, self->lfd);
}
efree(self);
php_pdo_dbh_delref(dbh TSRMLS_CC);
return 0;
}
static int kdb_lob_flush(php_stream *stream TSRMLS_DC)
{
return 0;
}
static int kdb_lob_seek(php_stream *stream, off_t offset, int whence,
off_t *newoffset TSRMLS_DC)
{
struct pdo_kdb_lob_self *self = (struct pdo_kdb_lob_self*)stream->abstract;
int pos = KCIBlobSeek(self->conn, self->lfd, offset, whence);
*newoffset = pos;
return pos >= 0 ? 0 : -1;
}
php_stream_ops pdo_kdb_lob_stream_ops = {
kdb_lob_write,
kdb_lob_read,
kdb_lob_close,
kdb_lob_flush,
"pdo_kdb lob stream",
kdb_lob_seek,
NULL,
NULL,
NULL
};
php_stream *pdo_kdb_create_lob_stream(pdo_dbh_t *dbh, int lfd, Oid oid TSRMLS_DC)
{
php_stream *stm;
struct pdo_kdb_lob_self *self = ecalloc(1, sizeof(*self));
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
self->dbh = dbh;
self->lfd = lfd;
self->oid = oid;
self->conn = H->server;
stm = php_stream_alloc(&pdo_kdb_lob_stream_ops, self, 0, "r+b");
if (stm) {
php_pdo_dbh_addref(dbh TSRMLS_CC);
return stm;
}
efree(self);
return NULL;
}
/* }}} */
static int kdb_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) /* {{{ */
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
if (H) {
if (H->server) {
KCIConnectionDestory(H->server);
H->server = NULL;
}
if (H->einfo.errmsg) {
pefree(H->einfo.errmsg, dbh->is_persistent);
H->einfo.errmsg = NULL;
}
pefree(H, dbh->is_persistent);
dbh->driver_data = NULL;
}
return 0;
}
/* }}} */
static int kdb_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
pdo_kdb_stmt *S = ecalloc(1, sizeof(pdo_kdb_stmt));
int scrollable;
#if HAVE_KCISTATEMENTPREPARE
int ret;
char *nsql = NULL;
int nsql_len = 0;
int emulate = 0;
#endif
S->H = H;
stmt->driver_data = S;
stmt->methods = &kdb_stmt_methods;
scrollable = pdo_attr_lval(driver_options, PDO_ATTR_CURSOR,
PDO_CURSOR_FWDONLY TSRMLS_CC) == PDO_CURSOR_SCROLL;
if (scrollable) {
if (S->cursor_name) {
efree(S->cursor_name);
}
spprintf(&S->cursor_name, 0, "pdo_crsr_%08x", ++H->stmt_counter);
#if HAVE_KCISTATEMENTPREPARE
emulate = 1;
#endif
}
#if HAVE_KCISTATEMENTPREPARE
else if (driver_options) {
if (pdo_attr_lval(driver_options, PDO_KDB_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT, H->disable_native_prepares TSRMLS_CC) == 1 ||
pdo_attr_lval(driver_options, PDO_ATTR_EMULATE_PREPARES, H->emulate_prepares TSRMLS_CC) == 1) {
emulate = 1;
}
} else {
emulate = H->disable_native_prepares || H->emulate_prepares;
}
if (!emulate && KCIConnectionGetProtocolVersion(H->server) > 2) {
stmt->supports_placeholders = PDO_PLACEHOLDER_NAMED;
stmt->named_rewrite_template = "$%d";
ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);
if (ret == 1) {
/* query was re-written */
sql = nsql;
} else if (ret == -1) {
/* couldn't grok it */
strcpy(dbh->error_code, stmt->error_code);
return 0;
}
spprintf(&S->stmt_name, 0, "pdo_stmt_%08x", ++H->stmt_counter);
/* that's all for now; we'll defer the actual prepare until the first execute call */
if (nsql) {
S->query = nsql;
} else {
S->query = estrdup(sql);
}
return 1;
}
#endif
stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
return 1;
}
static long kdb_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
KCIResult *res;
long ret = 1;
KCIExecuteStatus qs;
if (!(res = KCIStatementExecute(H->server, sql))) {
/* fatal error */
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, NULL);
return -1;
}
qs = KCIResultGetStatusCode(res);
if (qs != EXECUTE_COMMAND_OK && qs != EXECUTE_TUPLES_OK) {
pdo_kdb_error(dbh, qs, pdo_kdb_sqlstate(res));
KCIResultDealloc(res);
return -1;
}
H->kdboid = KCIResultInsertRowOid(res);
ret = (qs == EXECUTE_COMMAND_OK) ? atol(KCIResultGetAffectedCount(res)) : 0L;
KCIResultDealloc(res);
return ret;
}
static int kdb_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
{
unsigned char *escaped;
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
size_t tmp_len;
switch (paramtype) {
case PDO_PARAM_LOB:
/* escapedlen returned by KCIEscapeBytea() accounts for trailing 0 */
#ifdef HAVE_KCIESCAPEBYTEAEX
escaped = KCIEscapeByteaEx(H->server, unquoted, unquotedlen, &tmp_len);
#else
escaped = KCIEscapeBytea(unquoted, unquotedlen, &tmp_len);
#endif
*quotedlen = (int)tmp_len + 1;
*quoted = emalloc(*quotedlen + 1);
memcpy((*quoted)+1, escaped, *quotedlen-2);
(*quoted)[0] = '\'';
(*quoted)[*quotedlen-1] = '\'';
(*quoted)[*quotedlen] = '\0';
KCIFree(escaped);
break;
default:
*quoted = safe_emalloc(2, unquotedlen, 3);
(*quoted)[0] = '\'';
#ifndef HAVE_KCIESCAPESTRINGEX
*quotedlen = KCIEscapeString(*quoted + 1, unquoted, unquotedlen);
#else
*quotedlen = KCIEscapeStringEx(H->server, *quoted + 1, unquoted, unquotedlen, NULL);
#endif
(*quoted)[*quotedlen + 1] = '\'';
(*quoted)[*quotedlen + 2] = '\0';
*quotedlen += 2;
}
return 1;
}
static char *pdo_kdb_last_insert_id(pdo_dbh_t *dbh, const char *name, unsigned int *len TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
char *id = NULL;
if (name == NULL) {
if (H->kdboid == InvalidOid) {
return NULL;
}
*len = spprintf(&id, 0, "%ld", (long) H->kdboid);
} else {
KCIResult *res;
KCIExecuteStatus status;
const char *q[1];
q[0] = name;
res = KCIStatementExecuteParams(H->server, "SELECT CURRVAL($1)", 1, NULL, q, NULL, NULL, 0);
status = KCIResultGetStatusCode(res);
if (res && (status == EXECUTE_TUPLES_OK)) {
id = estrdup((char *)KCIResultGetColumnValue(res, 0, 0));
*len = KCIResultGetColumnValueLength(res, 0, 0);
} else {
pdo_kdb_error(dbh, status, pdo_kdb_sqlstate(res));
}
if (res) {
KCIResultDealloc(res);
}
}
return id;
}
static int pdo_kdb_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
switch (attr) {
case PDO_ATTR_CLIENT_VERSION:
ZVAL_STRING(return_value, KDB_VERSION, 1);
break;
case PDO_ATTR_SERVER_VERSION:
if (KCIConnectionGetProtocolVersion(H->server) >= 3) { /* PostgreSQL 7.4 or later */
ZVAL_STRING(return_value, (char*)KCIConnectionGetParameterValue(H->server, "server_version"), 1);
} else /* emulate above via a query */
{
KCIResult *res = KCIStatementExecute(H->server, "SELECT VERSION()");
if (res && KCIResultGetStatusCode(res) == EXECUTE_TUPLES_OK) {
ZVAL_STRING(return_value, (char *)KCIResultGetColumnValue(res, 0, 0), 1);
}
if (res) {
KCIResultDealloc(res);
}
}
break;
case PDO_ATTR_CONNECTION_STATUS:
switch (KCIConnectionGetStatus(H->server)) {
case CONNECTION_STARTED:
ZVAL_STRINGL(return_value, "Waiting for connection to be made.", sizeof("Waiting for connection to be made.")-1, 1);
break;
case CONNECTION_MADE:
case CONNECTION_OK:
ZVAL_STRINGL(return_value, "Connection OK; waiting to send.", sizeof("Connection OK; waiting to send.")-1, 1);
break;
case CONNECTION_AWAITING_RESPONSE:
ZVAL_STRINGL(return_value, "Waiting for a response from the server.", sizeof("Waiting for a response from the server.")-1, 1);
break;
case CONNECTION_AUTH_OK:
ZVAL_STRINGL(return_value, "Received authentication; waiting for backend start-up to finish.", sizeof("Received authentication; waiting for backend start-up to finish.")-1, 1);
break;
#ifdef CONNECTION_SSL_STARTUP
case CONNECTION_SSL_STARTUP:
ZVAL_STRINGL(return_value, "Negotiating SSL encryption.", sizeof("Negotiating SSL encryption.")-1, 1);
break;
#endif
case CONNECTION_SETENV:
ZVAL_STRINGL(return_value, "Negotiating environment-driven parameter settings.", sizeof("Negotiating environment-driven parameter settings.")-1, 1);
break;
case CONNECTION_BAD:
default:
ZVAL_STRINGL(return_value, "Bad connection.", sizeof("Bad connection.")-1, 1);
break;
}
break;
case PDO_ATTR_SERVER_INFO: {
int spid = KCIConnectionGetBackendPid(H->server);
char *tmp;
spprintf(&tmp, 0,
"PID: %d; Client Encoding: %s; Is Superuser: %s; Session Authorization: %s; Date Style: %s",
spid,
(char*)KCIConnectionGetParameterValue(H->server, "client_encoding"),
(char*)KCIConnectionGetParameterValue(H->server, "is_superuser"),
(char*)KCIConnectionGetParameterValue(H->server, "session_authorization"),
(char*)KCIConnectionGetParameterValue(H->server, "DateStyle"));
ZVAL_STRING(return_value, tmp, 0);
}
break;
default:
return 0;
}
return 1;
}
/* {{{ */
static int pdo_kdb_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
if (KCIConnectionGetStatus(H->server) == CONNECTION_BAD) {
KCIConnectionRepoll(H->server);
}
return (KCIConnectionGetStatus(H->server) == CONNECTION_OK) ? SUCCESS : FAILURE;
}
/* }}} */
static int pdo_kdb_transaction_cmd(const char *cmd, pdo_dbh_t *dbh TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
KCIResult *res;
int ret = 1;
res = KCIStatementExecute(H->server, cmd);
if (KCIResultGetStatusCode(res) != EXECUTE_COMMAND_OK) {
pdo_kdb_error(dbh, KCIResultGetStatusCode(res), pdo_kdb_sqlstate(res));
ret = 0;
}
KCIResultDealloc(res);
return ret;
}
static int kdb_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)
{
return pdo_kdb_transaction_cmd("BEGIN", dbh TSRMLS_CC);
}
static int kdb_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)
{
return pdo_kdb_transaction_cmd("COMMIT", dbh TSRMLS_CC);
}
static int kdb_handle_rollback(pdo_dbh_t *dbh TSRMLS_DC)
{
return pdo_kdb_transaction_cmd("ROLLBACK", dbh TSRMLS_CC);
}
static int kdb_handle_in_transaction(pdo_dbh_t *dbh TSRMLS_DC)
{
pdo_kdb_db_handle *H;
H = (pdo_kdb_db_handle *)dbh->driver_data;
return KCIConnectionGetTransactionStatus(H->server);
}
/* {{{ proto string PDO::kdbCopyFromArray(string $table_name , array $rows [, string $delimiter [, string $null_as ] [, string $fields])
Returns true if the copy worked fine or false if error */
static PHP_METHOD(PDO, kdbCopyFromArray)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
zval *kdb_rows;
char *table_name, *kdb_delim = NULL, *kdb_null_as = NULL, *kdb_fields = NULL;
int table_name_len, kdb_delim_len = 0, kdb_null_as_len = 0, kdb_fields_len;
char *query;
KCIResult *kdb_result;
KCIExecuteStatus status;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s/a|sss",
&table_name, &table_name_len, &kdb_rows,
&kdb_delim, &kdb_delim_len, &kdb_null_as, &kdb_null_as_len, &kdb_fields, &kdb_fields_len) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(kdb_rows))) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot copy from an empty array");
RETURN_FALSE;
}
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
if (kdb_fields) {
spprintf(&query, 0, "COPY %s (%s) FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, kdb_fields, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
} else {
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
}
/* Obtain db Handle */
H = (pdo_kdb_db_handle *)dbh->driver_data;
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
kdb_result = KCIStatementExecute(H->server, query);
efree(query);
query = NULL;
if (kdb_result) {
status = KCIResultGetStatusCode(kdb_result);
} else {
status = (KCIExecuteStatus) KCIConnectionGetStatus(H->server);
}
if (status == EXECUTE_COPY_IN && kdb_result) {
int command_failed = 0;
int buffer_len = 0;
zval **tmp;
HashPosition pos;
KCIResultDealloc(kdb_result);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(kdb_rows), &pos);
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(kdb_rows), (void **) &tmp, &pos) == SUCCESS) {
int query_len;
convert_to_string_ex(tmp);
if (buffer_len < Z_STRLEN_PP(tmp)) {
buffer_len = Z_STRLEN_PP(tmp);
query = erealloc(query, buffer_len + 2); /* room for \n\0 */
}
memcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
query_len = Z_STRLEN_PP(tmp);
if (query[query_len - 1] != '\n') {
query[query_len++] = '\n';
}
query[query_len] = '\0';
if (KCICopySendData(H->server, query, query_len) != 1) {
efree(query);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "copy failed");
RETURN_FALSE;
}
zend_hash_move_forward_ex(Z_ARRVAL_P(kdb_rows), &pos);
}
if (query) {
efree(query);
}
if (KCICopySendEOF(H->server, NULL) != 1) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "putcopyend failed");
RETURN_FALSE;
}
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
if (EXECUTE_COMMAND_OK != KCIResultGetStatusCode(kdb_result)) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
command_failed = 1;
}
KCIResultDealloc(kdb_result);
}
RETURN_BOOL(!command_failed);
} else {
KCIResultDealloc(kdb_result);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string PDO::kdbCopyFromFile(string $table_name , string $filename [, string $delimiter [, string $null_as ] [, string $fields])
Returns true if the copy worked fine or false if error */
static PHP_METHOD(PDO, kdbCopyFromFile)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
char *table_name, *filename, *kdb_delim = NULL, *kdb_null_as = NULL, *kdb_fields = NULL;
int table_name_len, filename_len, kdb_delim_len = 0, kdb_null_as_len = 0, kdb_fields_len;
char *query;
KCIResult *kdb_result;
KCIExecuteStatus status;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
&table_name, &table_name_len, &filename, &filename_len,
&kdb_delim, &kdb_delim_len, &kdb_null_as, &kdb_null_as_len, &kdb_fields, &kdb_fields_len) == FAILURE) {
return;
}
/* Obtain db Handler */
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
stream = php_stream_open_wrapper_ex(filename, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, FG(default_context));
if (!stream) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Unable to open the file");
RETURN_FALSE;
}
if (kdb_fields) {
spprintf(&query, 0, "COPY %s (%s) FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, kdb_fields, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
} else {
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
}
H = (pdo_kdb_db_handle *)dbh->driver_data;
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
kdb_result = KCIStatementExecute(H->server, query);
efree(query);
if (kdb_result) {
status = KCIResultGetStatusCode(kdb_result);
} else {
status = (KCIExecuteStatus) KCIConnectionGetStatus(H->server);
}
if (status == EXECUTE_COPY_IN && kdb_result) {
char *buf;
int command_failed = 0;
size_t line_len = 0;
KCIResultDealloc(kdb_result);
while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
if (KCICopySendData(H->server, buf, line_len) != 1) {
efree(buf);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "copy failed");
php_stream_close(stream);
RETURN_FALSE;
}
efree(buf);
}
php_stream_close(stream);
if (KCICopySendEOF(H->server, NULL) != 1) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "putcopyend failed");
RETURN_FALSE;
}
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
if (EXECUTE_COMMAND_OK != KCIResultGetStatusCode(kdb_result)) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
command_failed = 1;
}
KCIResultDealloc(kdb_result);
}
RETURN_BOOL(!command_failed);
} else {
KCIResultDealloc(kdb_result);
php_stream_close(stream);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string PDO::kdbCopyToFile(string $table_name , $filename, [string $delimiter [, string $null_as [, string $fields]]])
Returns true if the copy worked fine or false if error */
static PHP_METHOD(PDO, kdbCopyToFile)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
char *table_name, *kdb_delim = NULL, *kdb_null_as = NULL, *kdb_fields = NULL, *filename = NULL;
int table_name_len, kdb_delim_len = 0, kdb_null_as_len = 0, kdb_fields_len, filename_len;
char *query;
KCIResult *kdb_result;
KCIExecuteStatus status;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
&table_name, &table_name_len, &filename, &filename_len,
&kdb_delim, &kdb_delim_len, &kdb_null_as, &kdb_null_as_len, &kdb_fields, &kdb_fields_len) == FAILURE) {
return;
}
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
H = (pdo_kdb_db_handle *)dbh->driver_data;
stream = php_stream_open_wrapper_ex(filename, "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, FG(default_context));
if (!stream) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Unable to open the file for writing");
RETURN_FALSE;
}
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
if (kdb_fields) {
spprintf(&query, 0, "COPY %s (%s) TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, kdb_fields, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
} else {
spprintf(&query, 0, "COPY %s TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
}
kdb_result = KCIStatementExecute(H->server, query);
efree(query);
if (kdb_result) {
status = KCIResultGetStatusCode(kdb_result);
} else {
status = (KCIExecuteStatus) KCIConnectionGetStatus(H->server);
}
if (status == EXECUTE_COPY_OUT && kdb_result) {
KCIResultDealloc(kdb_result);
while (1) {
char *csv = NULL;
int ret = KCICopyReceiveData(H->server, &csv, 0);
if (ret == -1) {
break; /* done */
} else if (ret > 0) {
if (php_stream_write(stream, csv, ret) != ret) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Unable to write to file");
KCIFree(csv);
php_stream_close(stream);
RETURN_FALSE;
} else {
KCIFree(csv);
}
} else {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed: getline failed");
php_stream_close(stream);
RETURN_FALSE;
}
}
php_stream_close(stream);
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
RETURN_TRUE;
} else {
php_stream_close(stream);
KCIResultDealloc(kdb_result);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string PDO::kdbCopyToArray(string $table_name , [string $delimiter [, string $null_as [, string $fields]]])
Returns true if the copy worked fine or false if error */
static PHP_METHOD(PDO, kdbCopyToArray)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
char *table_name, *kdb_delim = NULL, *kdb_null_as = NULL, *kdb_fields = NULL;
int table_name_len, kdb_delim_len = 0, kdb_null_as_len = 0, kdb_fields_len;
char *query;
KCIResult *kdb_result;
KCIExecuteStatus status;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sss",
&table_name, &table_name_len,
&kdb_delim, &kdb_delim_len, &kdb_null_as, &kdb_null_as_len, &kdb_fields, &kdb_fields_len) == FAILURE) {
return;
}
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
H = (pdo_kdb_db_handle *)dbh->driver_data;
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
if (kdb_fields) {
spprintf(&query, 0, "COPY %s (%s) TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, kdb_fields, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
} else {
spprintf(&query, 0, "COPY %s TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (kdb_delim_len ? *kdb_delim : '\t'), (kdb_null_as_len ? kdb_null_as : "\\\\N"));
}
kdb_result = KCIStatementExecute(H->server, query);
efree(query);
if (kdb_result) {
status = KCIResultGetStatusCode(kdb_result);
} else {
status = (KCIExecuteStatus) KCIConnectionGetStatus(H->server);
}
if (status == EXECUTE_COPY_OUT && kdb_result) {
KCIResultDealloc(kdb_result);
array_init(return_value);
while (1) {
char *csv = NULL;
int ret = KCICopyReceiveData(H->server, &csv, 0);
if (ret == -1) {
break; /* copy done */
} else if (ret > 0) {
add_next_index_stringl(return_value, csv, ret, 1);
KCIFree(csv);
} else {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed: getline failed");
RETURN_FALSE;
}
}
while ((kdb_result = KCIConnectionFetchResult(H->server))) {
KCIResultDealloc(kdb_result);
}
} else {
KCIResultDealloc(kdb_result);
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "Copy command failed");
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string PDO::kdbLOBCreate()
Creates a new large object, returning its identifier. Must be called inside a transaction. */
static PHP_METHOD(PDO, kdbLOBCreate)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
Oid lfd;
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
H = (pdo_kdb_db_handle *)dbh->driver_data;
lfd = KCILobCreate(H->server, lfd, 'b');
if (lfd != InvalidOid) {
char *buf;
spprintf(&buf, 0, "%lu", (long) lfd);
RETURN_STRING(buf, 0);
}
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "HY000");
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource PDO::kdbLOBOpen(string oid [, string mode = 'rb'])
Opens an existing large object stream. Must be called inside a transaction. */
static PHP_METHOD(PDO, kdbLOBOpen)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
Oid oid;
int lfd;
char *oidstr;
int oidstrlen;
char *modestr = "rb";
int modestrlen;
int mode = INV_READ;
char *end_ptr;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
&oidstr, &oidstrlen, &modestr, &modestrlen)) {
RETURN_FALSE;
}
oid = (Oid)strtoul(oidstr, &end_ptr, 10);
if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
RETURN_FALSE;
}
if (strpbrk(modestr, "+w")) {
mode = INV_READ|INV_WRITE;
}
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
H = (pdo_kdb_db_handle *)dbh->driver_data;
lfd = KCILobOpen(H->server, oid, mode);
if (lfd >= 0) {
php_stream *stream = pdo_kdb_create_lob_stream(dbh, lfd, oid TSRMLS_CC);
if (stream) {
php_stream_to_zval(stream, return_value);
return;
}
} else {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "HY000");
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool PDO::kdbLOBUnlink(string oid)
Deletes the large object identified by oid. Must be called inside a transaction. */
static PHP_METHOD(PDO, kdbLOBUnlink)
{
pdo_dbh_t *dbh;
pdo_kdb_db_handle *H;
Oid oid;
char *oidstr, *end_ptr;
int oidlen;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
&oidstr, &oidlen)) {
RETURN_FALSE;
}
oid = (Oid)strtoul(oidstr, &end_ptr, 10);
if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
RETURN_FALSE;
}
dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
PDO_CONSTRUCT_CHECK;
H = (pdo_kdb_db_handle *)dbh->driver_data;
if (1 == KCILobDrop(H->server, oid)) {
RETURN_TRUE;
}
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, "HY000");
RETURN_FALSE;
}
/* }}} */
static const zend_function_entry dbh_methods[] = {
PHP_ME(PDO, kdbLOBCreate, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbLOBOpen, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbLOBUnlink, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbCopyFromArray, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbCopyFromFile, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbCopyToArray, NULL, ZEND_ACC_PUBLIC)
PHP_ME(PDO, kdbCopyToFile, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry *pdo_kdb_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
{
switch (kind) {
case PDO_DBH_DRIVER_METHOD_KIND_DBH:
return dbh_methods;
default:
return NULL;
}
}
static int pdo_kdb_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
{
pdo_kdb_db_handle *H = (pdo_kdb_db_handle *)dbh->driver_data;
switch (attr) {
#if HAVE_KCISTATEMENTPREPARE
case PDO_ATTR_EMULATE_PREPARES:
H->emulate_prepares = Z_LVAL_P(val);
return 1;
case PDO_KDB_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT:
H->disable_native_prepares = Z_LVAL_P(val);
return 1;
#endif
default:
return 0;
}
}
static struct pdo_dbh_methods kdb_methods = {
kdb_handle_closer,
kdb_handle_preparer,
kdb_handle_doer,
kdb_handle_quoter,
kdb_handle_begin,
kdb_handle_commit,
kdb_handle_rollback,
pdo_kdb_set_attr,
pdo_kdb_last_insert_id,
pdo_kdb_fetch_error_func,
pdo_kdb_get_attribute,
pdo_kdb_check_liveness, /* check_liveness */
pdo_kdb_get_driver_methods, /* get_driver_methods */
NULL,
kdb_handle_in_transaction,
};
static int pdo_kdb_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
{
pdo_kdb_db_handle *H;
int ret = 0;
char *conn_str, *p, *e;
long connect_timeout = 30;
H = pecalloc(1, sizeof(pdo_kdb_db_handle), dbh->is_persistent);
dbh->driver_data = H;
H->einfo.errcode = 0;
H->einfo.errmsg = NULL;
/* PostgreSQL wants params in the connect string to be separated by spaces,
* if the PDO standard semicolons are used, we convert them to spaces
*/
e = (char *) dbh->data_source + strlen(dbh->data_source);
p = (char *) dbh->data_source;
while ((p = memchr(p, ';', (e - p)))) {
*p = ' ';
}
if (driver_options) {
connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);
}
/* support both full connection string & connection string + login and/or password */
if (dbh->username && dbh->password) {
spprintf(&conn_str, 0, "%s user=%s password=%s connect_timeout=%ld", dbh->data_source, dbh->username, dbh->password, connect_timeout);
} else if (dbh->username) {
spprintf(&conn_str, 0, "%s user=%s connect_timeout=%ld", dbh->data_source, dbh->username, connect_timeout);
} else if (dbh->password) {
spprintf(&conn_str, 0, "%s password=%s connect_timeout=%ld", dbh->data_source, dbh->password, connect_timeout);
} else {
spprintf(&conn_str, 0, "%s connect_timeout=%ld", (char *) dbh->data_source, connect_timeout);
}
H->server = KCIConnectionCreate(conn_str);
efree(conn_str);
if (KCIConnectionGetStatus(H->server) != CONNECTION_OK) {
pdo_kdb_error(dbh, EXECUTE_FATAL_ERROR, PHP_PDO_KDB_CONNECTION_FAILURE_SQLSTATE);
goto cleanup;
}
KCISetNoticeProcessor(H->server, (void(*)(void*,const char*))_pdo_kdb_notice, (void *)&dbh);
H->attached = 1;
H->kdboid = -1;
dbh->methods = &kdb_methods;
dbh->alloc_own_columns = 1;
dbh->max_escaped_char_length = 2;
ret = 1;
cleanup:
dbh->methods = &kdb_methods;
if (!ret) {
kdb_handle_closer(dbh TSRMLS_CC);
}
return ret;
}
/* }}} */
pdo_driver_t pdo_kdb_driver = {
PDO_DRIVER_HEADER(kdb),
pdo_kdb_handle_factory
};
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<file_sep>/php_pdo_kdb_int.h
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2013 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_PDO_KDB_INT_H
#define PHP_PDO_KDB_INT_H
#include <libkci.h>
#include <php.h>
#define PHP_PDO_KDB_CONNECTION_FAILURE_SQLSTATE "08006"
#define SYS_DIAG_SQLSTATE 'C'
#define KDB_VERSION "7.1"
typedef struct {
const char *file;
int line;
unsigned int errcode;
char *errmsg;
} pdo_kdb_error_info;
/* stuff we use in a kdb database handle */
typedef struct {
KCIConnection *server;
unsigned attached:1;
unsigned _reserved:31;
pdo_kdb_error_info einfo;
Oid kdboid;
#if HAVE_KCISTATEMENTPREPARE
/* The following two variables have the same purpose. Unfortunately we need
to keep track of two different attributes having the same effect.
It might be worth to deprecate the driver specific one soon. */
int emulate_prepares;
int disable_native_prepares;
#endif
unsigned int stmt_counter;
} pdo_kdb_db_handle;
typedef struct {
char *def;
Oid kdb_type;
long intval;
zend_bool boolval;
} pdo_kdb_column;
typedef struct {
pdo_kdb_db_handle *H;
KCIResult *result;
int current_row;
pdo_kdb_column *cols;
char *cursor_name;
#if HAVE_KCISTATEMENTPREPARE
char *stmt_name;
char *query;
char **param_values;
int *param_lengths;
int *param_formats;
Oid *param_types;
#endif
zend_bool is_prepared;
} pdo_kdb_stmt;
typedef struct {
Oid oid;
} pdo_kdb_bound_param;
extern pdo_driver_t pdo_kdb_driver;
extern int _pdo_kdb_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *file, int line TSRMLS_DC);
#define pdo_kdb_error(d,e,z) _pdo_kdb_error(d, NULL, e, z, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_kdb_error_stmt(s,e,z) _pdo_kdb_error(s->dbh, s, e, z, __FILE__, __LINE__ TSRMLS_CC)
extern struct pdo_stmt_methods kdb_stmt_methods;
#define pdo_kdb_sqlstate(r) KCIResultGetErrorField(r, SYS_DIAG_SQLSTATE)
enum {
PDO_KDB_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT = PDO_ATTR_DRIVER_SPECIFIC,
};
struct pdo_kdb_lob_self {
pdo_dbh_t *dbh;
KCIConnection *conn;
int lfd;
Oid oid;
};
enum pdo_kdb_specific_constants {
KDB_TRANSACTION_IDLE = TRANSACTION_IDLE,
KDB_TRANSACTION_ACTIVE = TRANSACTION_ACTIVE,
KDB_TRANSACTION_INTRANS = TRANSACTION_INTRANS,
KDB_TRANSACTION_INERROR = TRANSACTION_INERROR,
KDB_TRANSACTION_UNKNOWN = TRANSACTION_UNKNOWN
};
php_stream *pdo_kdb_create_lob_stream(pdo_dbh_t *stmt, int lfd, Oid oid TSRMLS_DC);
extern php_stream_ops pdo_kdb_lob_stream_ops;
#endif /* PHP_PDO_KDB_INT_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<file_sep>/pdo_kdb.c
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2013 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "php_pdo_kdb.h"
#include "php_pdo_kdb_int.h"
#ifdef HAVE_KDB_CONFIG_H
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
#include <kingbase-type.h>
#endif
#define KDB_VERSION "7.1"
/* {{{ pdo_kdb_functions[] */
const zend_function_entry pdo_kdb_functions[] = {
{NULL, NULL, NULL}
};
/* }}} */
/* {{{ pdo_sqlite_deps
*/
#if ZEND_MODULE_API_NO >= 20050922
static const zend_module_dep pdo_kdb_deps[] = {
ZEND_MOD_REQUIRED("pdo")
ZEND_MOD_END
};
#endif
/* }}} */
/* {{{ pdo_kdb_module_entry */
zend_module_entry pdo_kdb_module_entry = {
#if ZEND_MODULE_API_NO >= 20050922
STANDARD_MODULE_HEADER_EX, NULL,
pdo_kdb_deps,
#else
STANDARD_MODULE_HEADER,
#endif
"pdo_kdb",
pdo_kdb_functions,
PHP_MINIT(pdo_kdb),
PHP_MSHUTDOWN(pdo_kdb),
NULL,
NULL,
PHP_MINFO(pdo_kdb),
"1.0.2",
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_PDO_KDB
ZEND_GET_MODULE(pdo_kdb)
#endif
/* true global environment */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(pdo_kdb)
{
REGISTER_PDO_CLASS_CONST_LONG("KDB_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT", PDO_KDB_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT);
REGISTER_PDO_CLASS_CONST_LONG("KDB_TRANSACTION_IDLE", (long)KDB_TRANSACTION_IDLE);
REGISTER_PDO_CLASS_CONST_LONG("KDB_TRANSACTION_ACTIVE", (long)KDB_TRANSACTION_ACTIVE);
REGISTER_PDO_CLASS_CONST_LONG("KDB_TRANSACTION_INTRANS", (long)KDB_TRANSACTION_INTRANS);
REGISTER_PDO_CLASS_CONST_LONG("KDB_TRANSACTION_INERROR", (long)KDB_TRANSACTION_INERROR);
REGISTER_PDO_CLASS_CONST_LONG("KDB_TRANSACTION_UNKNOWN", (long)KDB_TRANSACTION_UNKNOWN);
php_pdo_register_driver(&pdo_kdb_driver);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(pdo_kdb)
{
php_pdo_unregister_driver(&pdo_kdb_driver);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(pdo_kdb)
{
php_info_print_table_start();
php_info_print_table_header(2, "PDO Driver for KingbaseES", "enabled");
#ifdef HAVE_KCI_CONFIG_H
php_info_print_table_row(2, "KingbaseES(libkci) Version", KDB_VERSION);
#endif
php_info_print_table_row(2, "Module version", pdo_kdb_module_entry.version);
php_info_print_table_row(2, "Revision", " $Id$ ");
php_info_print_table_end();
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
d83ac017bd0cf535bdef4d96a243315681c80042
|
[
"C"
] | 3
|
C
|
jjshi/pdo_kdb
|
e765b725d6af50153f2de6202310ef273fc42aee
|
473aaf581b1da5c386f950208d95ce6462d51f70
|
refs/heads/master
|
<repo_name>meox/parquet-cpp<file_sep>/src/parquet/arrow/writer.cc
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "parquet/arrow/writer.h"
#include <algorithm>
#include <vector>
#include "parquet/util/bit-util.h"
#include "parquet/util/logging.h"
#include "parquet/arrow/schema.h"
#include "arrow/api.h"
using arrow::BinaryArray;
using arrow::MemoryPool;
using arrow::PoolBuffer;
using arrow::PrimitiveArray;
using arrow::Status;
using arrow::Table;
using parquet::ParquetFileWriter;
using parquet::ParquetVersion;
using parquet::schema::GroupNode;
namespace parquet {
namespace arrow {
namespace BitUtil = ::arrow::BitUtil;
class FileWriter::Impl {
public:
Impl(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer);
Status NewRowGroup(int64_t chunk_size);
template <typename ParquetType, typename ArrowType>
Status TypedWriteBatch(
ColumnWriter* writer, const PrimitiveArray* data, int64_t offset, int64_t length);
template <typename ParquetType, typename ArrowType>
Status WriteNullableBatch(TypedColumnWriter<ParquetType>* writer, int64_t length,
const int16_t* def_levels, const int16_t* rep_levels, const uint8_t* valid_bits,
int64_t valid_bits_offset, const typename ArrowType::c_type* data_ptr);
// TODO(uwe): Same code as in reader.cc the only difference is the name of the temporary
// buffer
template <typename InType, typename OutType>
struct can_copy_ptr {
static constexpr bool value =
std::is_same<InType, OutType>::value ||
(std::is_integral<InType>{} && std::is_integral<OutType>{} &&
(sizeof(InType) == sizeof(OutType)));
};
template <typename InType, typename OutType,
typename std::enable_if<can_copy_ptr<InType, OutType>::value>::type* = nullptr>
Status ConvertPhysicalType(const InType* in_ptr, int64_t, const OutType** out_ptr) {
*out_ptr = reinterpret_cast<const OutType*>(in_ptr);
return Status::OK();
}
template <typename InType, typename OutType,
typename std::enable_if<not can_copy_ptr<InType, OutType>::value>::type* = nullptr>
Status ConvertPhysicalType(
const InType* in_ptr, int64_t length, const OutType** out_ptr) {
RETURN_NOT_OK(data_buffer_.Resize(length * sizeof(OutType)));
OutType* mutable_out_ptr = reinterpret_cast<OutType*>(data_buffer_.mutable_data());
std::copy(in_ptr, in_ptr + length, mutable_out_ptr);
*out_ptr = mutable_out_ptr;
return Status::OK();
}
Status WriteFlatColumnChunk(const PrimitiveArray* data, int64_t offset, int64_t length);
Status WriteFlatColumnChunk(const BinaryArray* data, int64_t offset, int64_t length);
Status Close();
virtual ~Impl() {}
private:
friend class FileWriter;
MemoryPool* pool_;
// Buffer used for storing the data of an array converted to the physical type
// as expected by parquet-cpp.
PoolBuffer data_buffer_;
PoolBuffer def_levels_buffer_;
std::unique_ptr<ParquetFileWriter> writer_;
RowGroupWriter* row_group_writer_;
};
FileWriter::Impl::Impl(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer)
: pool_(pool),
data_buffer_(pool),
writer_(std::move(writer)),
row_group_writer_(nullptr) {}
Status FileWriter::Impl::NewRowGroup(int64_t chunk_size) {
if (row_group_writer_ != nullptr) { PARQUET_CATCH_NOT_OK(row_group_writer_->Close()); }
PARQUET_CATCH_NOT_OK(row_group_writer_ = writer_->AppendRowGroup(chunk_size));
return Status::OK();
}
template <typename ParquetType, typename ArrowType>
Status FileWriter::Impl::TypedWriteBatch(ColumnWriter* column_writer,
const PrimitiveArray* data, int64_t offset, int64_t length) {
using ArrowCType = typename ArrowType::c_type;
using ParquetCType = typename ParquetType::c_type;
DCHECK((offset + length) <= data->length());
auto data_ptr = reinterpret_cast<const ArrowCType*>(data->data()->data()) + offset;
auto writer = reinterpret_cast<TypedColumnWriter<ParquetType>*>(column_writer);
if (writer->descr()->max_definition_level() == 0) {
// no nulls, just dump the data
const ParquetCType* data_writer_ptr = nullptr;
RETURN_NOT_OK((ConvertPhysicalType<ArrowCType, ParquetCType>(
data_ptr, length, &data_writer_ptr)));
PARQUET_CATCH_NOT_OK(writer->WriteBatch(length, nullptr, nullptr, data_writer_ptr));
} else if (writer->descr()->max_definition_level() == 1) {
RETURN_NOT_OK(def_levels_buffer_.Resize(length * sizeof(int16_t)));
int16_t* def_levels_ptr =
reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
if (data->null_count() == 0) {
std::fill(def_levels_ptr, def_levels_ptr + length, 1);
const ParquetCType* data_writer_ptr = nullptr;
RETURN_NOT_OK((ConvertPhysicalType<ArrowCType, ParquetCType>(
data_ptr, length, &data_writer_ptr)));
PARQUET_CATCH_NOT_OK(
writer->WriteBatch(length, def_levels_ptr, nullptr, data_writer_ptr));
} else {
const uint8_t* valid_bits = data->null_bitmap_data();
INIT_BITSET(valid_bits, offset);
for (int i = 0; i < length; i++) {
if (bitset & (1 << bit_offset)) {
def_levels_ptr[i] = 1;
} else {
def_levels_ptr[i] = 0;
}
READ_NEXT_BITSET(valid_bits);
}
RETURN_NOT_OK((WriteNullableBatch<ParquetType, ArrowType>(
writer, length, def_levels_ptr, nullptr, valid_bits, offset, data_ptr)));
}
} else {
return Status::NotImplemented("no support for max definition level > 1 yet");
}
PARQUET_CATCH_NOT_OK(writer->Close());
return Status::OK();
}
template <typename ParquetType, typename ArrowType>
Status FileWriter::Impl::WriteNullableBatch(TypedColumnWriter<ParquetType>* writer,
int64_t length, const int16_t* def_levels, const int16_t* rep_levels,
const uint8_t* valid_bits, int64_t valid_bits_offset,
const typename ArrowType::c_type* data_ptr) {
using ParquetCType = typename ParquetType::c_type;
RETURN_NOT_OK(data_buffer_.Resize(length * sizeof(ParquetCType)));
auto buffer_ptr = reinterpret_cast<ParquetCType*>(data_buffer_.mutable_data());
INIT_BITSET(valid_bits, valid_bits_offset);
for (int i = 0; i < length; i++) {
if (bitset & (1 << bit_offset)) {
buffer_ptr[i] = static_cast<ParquetCType>(data_ptr[i]);
}
READ_NEXT_BITSET(valid_bits);
}
PARQUET_CATCH_NOT_OK(writer->WriteBatchSpaced(
length, def_levels, rep_levels, valid_bits, valid_bits_offset, buffer_ptr));
return Status::OK();
}
#define NULLABLE_BATCH_FAST_PATH(ParquetType, ArrowType, CType) \
template <> \
Status FileWriter::Impl::WriteNullableBatch<ParquetType, ArrowType>( \
TypedColumnWriter<ParquetType> * writer, int64_t length, \
const int16_t* def_levels, const int16_t* rep_levels, const uint8_t* valid_bits, \
int64_t valid_bits_offset, const CType* data_ptr) { \
PARQUET_CATCH_NOT_OK(writer->WriteBatchSpaced( \
length, def_levels, rep_levels, valid_bits, valid_bits_offset, data_ptr)); \
return Status::OK(); \
}
NULLABLE_BATCH_FAST_PATH(Int32Type, ::arrow::Int32Type, int32_t)
NULLABLE_BATCH_FAST_PATH(Int64Type, ::arrow::Int64Type, int64_t)
NULLABLE_BATCH_FAST_PATH(FloatType, ::arrow::FloatType, float)
NULLABLE_BATCH_FAST_PATH(DoubleType, ::arrow::DoubleType, double)
// This specialization seems quite similar but it significantly differs in two points:
// * offset is added at the most latest time to the pointer as we have sub-byte access
// * Arrow data is stored bitwise thus we cannot use std::copy to transform from
// ArrowType::c_type to ParquetType::c_type
template <>
Status FileWriter::Impl::TypedWriteBatch<BooleanType, ::arrow::BooleanType>(
ColumnWriter* column_writer, const PrimitiveArray* data, int64_t offset,
int64_t length) {
DCHECK((offset + length) <= data->length());
RETURN_NOT_OK(data_buffer_.Resize(length));
auto data_ptr = reinterpret_cast<const uint8_t*>(data->data()->data());
auto buffer_ptr = reinterpret_cast<bool*>(data_buffer_.mutable_data());
auto writer = reinterpret_cast<TypedColumnWriter<BooleanType>*>(column_writer);
if (writer->descr()->max_definition_level() == 0) {
// no nulls, just dump the data
for (int64_t i = 0; i < length; i++) {
buffer_ptr[i] = BitUtil::GetBit(data_ptr, offset + i);
}
PARQUET_CATCH_NOT_OK(writer->WriteBatch(length, nullptr, nullptr, buffer_ptr));
} else if (writer->descr()->max_definition_level() == 1) {
RETURN_NOT_OK(def_levels_buffer_.Resize(length * sizeof(int16_t)));
int16_t* def_levels_ptr =
reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
if (data->null_count() == 0) {
std::fill(def_levels_ptr, def_levels_ptr + length, 1);
for (int64_t i = 0; i < length; i++) {
buffer_ptr[i] = BitUtil::GetBit(data_ptr, offset + i);
}
// TODO(PARQUET-644): write boolean values as a packed bitmap
PARQUET_CATCH_NOT_OK(
writer->WriteBatch(length, def_levels_ptr, nullptr, buffer_ptr));
} else {
int buffer_idx = 0;
for (int i = 0; i < length; i++) {
if (data->IsNull(offset + i)) {
def_levels_ptr[i] = 0;
} else {
def_levels_ptr[i] = 1;
buffer_ptr[buffer_idx++] = BitUtil::GetBit(data_ptr, offset + i);
}
}
PARQUET_CATCH_NOT_OK(
writer->WriteBatch(length, def_levels_ptr, nullptr, buffer_ptr));
}
} else {
return Status::NotImplemented("no support for max definition level > 1 yet");
}
PARQUET_CATCH_NOT_OK(writer->Close());
return Status::OK();
}
Status FileWriter::Impl::Close() {
if (row_group_writer_ != nullptr) { PARQUET_CATCH_NOT_OK(row_group_writer_->Close()); }
PARQUET_CATCH_NOT_OK(writer_->Close());
return Status::OK();
}
#define TYPED_BATCH_CASE(ENUM, ArrowType, ParquetType) \
case ::arrow::Type::ENUM: \
return TypedWriteBatch<ParquetType, ArrowType>(writer, data, offset, length); \
break;
Status FileWriter::Impl::WriteFlatColumnChunk(
const PrimitiveArray* data, int64_t offset, int64_t length) {
ColumnWriter* writer;
PARQUET_CATCH_NOT_OK(writer = row_group_writer_->NextColumn());
switch (data->type_enum()) {
TYPED_BATCH_CASE(BOOL, ::arrow::BooleanType, BooleanType)
TYPED_BATCH_CASE(UINT8, ::arrow::UInt8Type, Int32Type)
TYPED_BATCH_CASE(INT8, ::arrow::Int8Type, Int32Type)
TYPED_BATCH_CASE(UINT16, ::arrow::UInt16Type, Int32Type)
TYPED_BATCH_CASE(INT16, ::arrow::Int16Type, Int32Type)
case ::arrow::Type::UINT32:
if (writer_->properties()->version() == ParquetVersion::PARQUET_1_0) {
// Parquet 1.0 reader cannot read the UINT_32 logical type. Thus we need
// to use the larger Int64Type to store them lossless.
return TypedWriteBatch<Int64Type, ::arrow::UInt32Type>(
writer, data, offset, length);
} else {
return TypedWriteBatch<Int32Type, ::arrow::UInt32Type>(
writer, data, offset, length);
}
TYPED_BATCH_CASE(INT32, ::arrow::Int32Type, Int32Type)
TYPED_BATCH_CASE(UINT64, ::arrow::UInt64Type, Int64Type)
TYPED_BATCH_CASE(INT64, ::arrow::Int64Type, Int64Type)
TYPED_BATCH_CASE(TIMESTAMP, ::arrow::TimestampType, Int64Type)
TYPED_BATCH_CASE(FLOAT, ::arrow::FloatType, FloatType)
TYPED_BATCH_CASE(DOUBLE, ::arrow::DoubleType, DoubleType)
default:
return Status::NotImplemented(data->type()->ToString());
}
}
Status FileWriter::Impl::WriteFlatColumnChunk(
const BinaryArray* data, int64_t offset, int64_t length) {
ColumnWriter* column_writer;
PARQUET_CATCH_NOT_OK(column_writer = row_group_writer_->NextColumn());
DCHECK((offset + length) <= data->length());
RETURN_NOT_OK(data_buffer_.Resize(length * sizeof(ByteArray)));
auto buffer_ptr = reinterpret_cast<ByteArray*>(data_buffer_.mutable_data());
// In the case of an array consisting of only empty strings or all null,
// data->data() points already to a nullptr, thus data->data()->data() will
// segfault.
const uint8_t* data_ptr = nullptr;
if (data->data()) {
data_ptr = reinterpret_cast<const uint8_t*>(data->data()->data());
DCHECK(data_ptr != nullptr);
}
auto writer = reinterpret_cast<TypedColumnWriter<ByteArrayType>*>(column_writer);
if (writer->descr()->max_definition_level() > 0) {
RETURN_NOT_OK(def_levels_buffer_.Resize(length * sizeof(int16_t)));
}
int16_t* def_levels_ptr = reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
if (writer->descr()->max_definition_level() == 0 || data->null_count() == 0) {
// no nulls, just dump the data
for (int64_t i = 0; i < length; i++) {
buffer_ptr[i] =
ByteArray(data->value_length(i + offset), data_ptr + data->value_offset(i));
}
if (writer->descr()->max_definition_level() > 0) {
std::fill(def_levels_ptr, def_levels_ptr + length, 1);
}
PARQUET_CATCH_NOT_OK(writer->WriteBatch(length, def_levels_ptr, nullptr, buffer_ptr));
} else if (writer->descr()->max_definition_level() == 1) {
int buffer_idx = 0;
for (int64_t i = 0; i < length; i++) {
if (data->IsNull(offset + i)) {
def_levels_ptr[i] = 0;
} else {
def_levels_ptr[i] = 1;
buffer_ptr[buffer_idx++] = ByteArray(
data->value_length(i + offset), data_ptr + data->value_offset(i + offset));
}
}
PARQUET_CATCH_NOT_OK(writer->WriteBatch(length, def_levels_ptr, nullptr, buffer_ptr));
} else {
return Status::NotImplemented("no support for max definition level > 1 yet");
}
PARQUET_CATCH_NOT_OK(writer->Close());
return Status::OK();
}
FileWriter::FileWriter(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer)
: impl_(new FileWriter::Impl(pool, std::move(writer))) {}
Status FileWriter::NewRowGroup(int64_t chunk_size) {
return impl_->NewRowGroup(chunk_size);
}
Status FileWriter::WriteFlatColumnChunk(
const ::arrow::Array* array, int64_t offset, int64_t length) {
int64_t real_length = length;
if (length == -1) { real_length = array->length(); }
if (array->type_enum() == ::arrow::Type::STRING ||
array->type_enum() == ::arrow::Type::BINARY) {
auto binary_array = static_cast<const ::arrow::BinaryArray*>(array);
DCHECK(binary_array);
return impl_->WriteFlatColumnChunk(binary_array, offset, real_length);
} else {
auto primitive_array = dynamic_cast<const PrimitiveArray*>(array);
if (!primitive_array) {
return Status::NotImplemented("Table must consist of PrimitiveArray instances");
}
return impl_->WriteFlatColumnChunk(primitive_array, offset, real_length);
}
}
Status FileWriter::Close() {
return impl_->Close();
}
MemoryPool* FileWriter::memory_pool() const {
return impl_->pool_;
}
FileWriter::~FileWriter() {}
Status WriteFlatTable(const Table* table, MemoryPool* pool,
const std::shared_ptr<OutputStream>& sink, int64_t chunk_size,
const std::shared_ptr<WriterProperties>& properties) {
std::shared_ptr<SchemaDescriptor> parquet_schema;
RETURN_NOT_OK(
ToParquetSchema(table->schema().get(), *properties.get(), &parquet_schema));
auto schema_node = std::static_pointer_cast<GroupNode>(parquet_schema->schema_root());
std::unique_ptr<ParquetFileWriter> parquet_writer =
ParquetFileWriter::Open(sink, schema_node, properties);
FileWriter writer(pool, std::move(parquet_writer));
// TODO(ARROW-232) Support writing chunked arrays.
for (int i = 0; i < table->num_columns(); i++) {
if (table->column(i)->data()->num_chunks() != 1) {
return Status::NotImplemented("No support for writing chunked arrays yet.");
}
}
for (int chunk = 0; chunk * chunk_size < table->num_rows(); chunk++) {
int64_t offset = chunk * chunk_size;
int64_t size = std::min(chunk_size, table->num_rows() - offset);
RETURN_NOT_OK_ELSE(writer.NewRowGroup(size), PARQUET_IGNORE_NOT_OK(writer.Close()));
for (int i = 0; i < table->num_columns(); i++) {
std::shared_ptr<::arrow::Array> array = table->column(i)->data()->chunk(0);
RETURN_NOT_OK_ELSE(writer.WriteFlatColumnChunk(array.get(), offset, size),
PARQUET_IGNORE_NOT_OK(writer.Close()));
}
}
return writer.Close();
}
Status WriteFlatTable(const Table* table, MemoryPool* pool,
const std::shared_ptr<::arrow::io::OutputStream>& sink, int64_t chunk_size,
const std::shared_ptr<WriterProperties>& properties) {
auto wrapper = std::make_shared<ArrowOutputStream>(sink);
return WriteFlatTable(table, pool, wrapper, chunk_size, properties);
}
} // namespace arrow
} // namespace parquet
<file_sep>/src/parquet/arrow/reader.cc
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "parquet/arrow/reader.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
#include "parquet/arrow/schema.h"
#include "parquet/util/bit-util.h"
#include "arrow/api.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit-util.h"
using arrow::Array;
using arrow::Column;
using arrow::Field;
using arrow::MemoryPool;
using arrow::PoolBuffer;
using arrow::Status;
using arrow::Table;
// Help reduce verbosity
using ParquetReader = parquet::ParquetFileReader;
namespace parquet {
namespace arrow {
constexpr int64_t kJulianToUnixEpochDays = 2440588L;
constexpr int64_t kNanosecondsInADay = 86400L * 1000L * 1000L * 1000L;
static inline int64_t impala_timestamp_to_nanoseconds(const Int96& impala_timestamp) {
int64_t days_since_epoch = impala_timestamp.value[2] - kJulianToUnixEpochDays;
int64_t nanoseconds = *(reinterpret_cast<const int64_t*>(&(impala_timestamp.value)));
return days_since_epoch * kNanosecondsInADay + nanoseconds;
}
template <typename ArrowType>
using ArrayType = typename ::arrow::TypeTraits<ArrowType>::ArrayType;
class FileReader::Impl {
public:
Impl(MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader);
virtual ~Impl() {}
bool CheckForFlatColumn(const ColumnDescriptor* descr);
Status GetFlatColumn(int i, std::unique_ptr<FlatColumnReader>* out);
Status ReadFlatColumn(int i, std::shared_ptr<Array>* out);
Status ReadFlatTable(std::shared_ptr<Table>* out);
Status ReadFlatTable(
const std::vector<int>& column_indices, std::shared_ptr<Table>* out);
const ParquetFileReader* parquet_reader() const { return reader_.get(); }
void set_num_threads(int num_threads) { num_threads_ = num_threads; }
private:
MemoryPool* pool_;
std::unique_ptr<ParquetFileReader> reader_;
int num_threads_;
};
class FlatColumnReader::Impl {
public:
Impl(MemoryPool* pool, const ColumnDescriptor* descr, ParquetFileReader* reader,
int column_index);
virtual ~Impl() {}
Status NextBatch(int batch_size, std::shared_ptr<Array>* out);
template <typename ArrowType, typename ParquetType>
Status TypedReadBatch(int batch_size, std::shared_ptr<Array>* out);
template <typename ArrowType>
Status ReadByteArrayBatch(int batch_size, std::shared_ptr<Array>* out);
template <typename ArrowType>
Status InitDataBuffer(int batch_size);
template <typename ArrowType, typename ParquetType>
Status ReadNullableFlatBatch(TypedColumnReader<ParquetType>* reader,
int16_t* def_levels, int64_t values_to_read, int64_t* levels_read);
template <typename ArrowType, typename ParquetType>
Status ReadNonNullableBatch(TypedColumnReader<ParquetType>* reader,
int64_t values_to_read, int64_t* levels_read);
private:
void NextRowGroup();
template <typename InType, typename OutType>
struct can_copy_ptr {
static constexpr bool value =
std::is_same<InType, OutType>::value ||
(std::is_integral<InType>{} && std::is_integral<OutType>{} &&
(sizeof(InType) == sizeof(OutType)));
};
MemoryPool* pool_;
const ColumnDescriptor* descr_;
ParquetFileReader* reader_;
int column_index_;
int next_row_group_;
std::shared_ptr<ColumnReader> column_reader_;
std::shared_ptr<Field> field_;
PoolBuffer values_buffer_;
PoolBuffer def_levels_buffer_;
std::shared_ptr<PoolBuffer> data_buffer_;
uint8_t* data_buffer_ptr_;
std::shared_ptr<PoolBuffer> valid_bits_buffer_;
uint8_t* valid_bits_ptr_;
int64_t valid_bits_idx_;
int64_t null_count_;
};
FileReader::Impl::Impl(MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader)
: pool_(pool), reader_(std::move(reader)), num_threads_(1) {}
bool FileReader::Impl::CheckForFlatColumn(const ColumnDescriptor* descr) {
if ((descr->max_repetition_level() > 0) || (descr->max_definition_level() > 1)) {
return false;
} else if ((descr->max_definition_level() == 1) &&
(descr->schema_node()->repetition() != Repetition::OPTIONAL)) {
return false;
}
return true;
}
Status FileReader::Impl::GetFlatColumn(int i, std::unique_ptr<FlatColumnReader>* out) {
const SchemaDescriptor* schema = reader_->metadata()->schema();
if (!CheckForFlatColumn(schema->Column(i))) {
return Status::Invalid("The requested column is not flat");
}
std::unique_ptr<FlatColumnReader::Impl> impl(
new FlatColumnReader::Impl(pool_, schema->Column(i), reader_.get(), i));
*out = std::unique_ptr<FlatColumnReader>(new FlatColumnReader(std::move(impl)));
return Status::OK();
}
Status FileReader::Impl::ReadFlatColumn(int i, std::shared_ptr<Array>* out) {
std::unique_ptr<FlatColumnReader> flat_column_reader;
RETURN_NOT_OK(GetFlatColumn(i, &flat_column_reader));
return flat_column_reader->NextBatch(reader_->metadata()->num_rows(), out);
}
Status FileReader::Impl::ReadFlatTable(std::shared_ptr<Table>* table) {
std::vector<int> column_indices(reader_->metadata()->num_columns());
for (size_t i = 0; i < column_indices.size(); ++i) {
column_indices[i] = i;
}
return ReadFlatTable(column_indices, table);
}
template <class FUNCTION>
Status ParallelFor(int nthreads, int num_tasks, FUNCTION&& func) {
std::vector<std::thread> thread_pool;
thread_pool.reserve(nthreads);
std::atomic<int> task_counter(0);
std::mutex error_mtx;
bool error_occurred = false;
Status error;
for (int thread_id = 0; thread_id < nthreads; ++thread_id) {
thread_pool.emplace_back(
[&num_tasks, &task_counter, &error, &error_occurred, &error_mtx, &func]() {
int task_id;
while (!error_occurred) {
task_id = task_counter.fetch_add(1);
if (task_id >= num_tasks) { break; }
Status s = func(task_id);
if (!s.ok()) {
std::lock_guard<std::mutex> lock(error_mtx);
error_occurred = true;
error = s;
break;
}
}
});
}
for (auto&& thread : thread_pool) {
thread.join();
}
if (error_occurred) { return error; }
return Status::OK();
}
Status FileReader::Impl::ReadFlatTable(
const std::vector<int>& indices, std::shared_ptr<Table>* table) {
auto descr = reader_->metadata()->schema();
const std::string& name = descr->name();
std::shared_ptr<::arrow::Schema> schema;
RETURN_NOT_OK(FromParquetSchema(descr, indices, &schema));
int num_columns = static_cast<int>(indices.size());
int nthreads = std::min<int>(num_threads_, num_columns);
std::vector<std::shared_ptr<Column>> columns(num_columns);
auto ReadColumn = [&indices, &schema, &columns, this](int i) {
std::shared_ptr<Array> array;
RETURN_NOT_OK(ReadFlatColumn(indices[i], &array));
columns[i] = std::make_shared<Column>(schema->field(i), array);
return Status::OK();
};
if (nthreads == 1) {
for (int i = 0; i < num_columns; i++) {
RETURN_NOT_OK(ReadColumn(i));
}
} else {
RETURN_NOT_OK(ParallelFor(nthreads, num_columns, ReadColumn));
}
*table = std::make_shared<Table>(name, schema, columns);
return Status::OK();
}
FileReader::FileReader(MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader)
: impl_(new FileReader::Impl(pool, std::move(reader))) {}
FileReader::~FileReader() {}
// Static ctor
Status OpenFile(const std::shared_ptr<::arrow::io::ReadableFileInterface>& file,
MemoryPool* allocator, const ReaderProperties& props,
const std::shared_ptr<FileMetaData>& metadata, std::unique_ptr<FileReader>* reader) {
std::unique_ptr<RandomAccessSource> io_wrapper(new ArrowInputFile(file));
std::unique_ptr<ParquetReader> pq_reader;
PARQUET_CATCH_NOT_OK(
pq_reader = ParquetReader::Open(std::move(io_wrapper), props, metadata));
reader->reset(new FileReader(allocator, std::move(pq_reader)));
return Status::OK();
}
Status OpenFile(const std::shared_ptr<::arrow::io::ReadableFileInterface>& file,
MemoryPool* allocator, std::unique_ptr<FileReader>* reader) {
return OpenFile(
file, allocator, ::parquet::default_reader_properties(), nullptr, reader);
}
Status FileReader::GetFlatColumn(int i, std::unique_ptr<FlatColumnReader>* out) {
return impl_->GetFlatColumn(i, out);
}
Status FileReader::ReadFlatColumn(int i, std::shared_ptr<Array>* out) {
try {
return impl_->ReadFlatColumn(i, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadFlatTable(std::shared_ptr<Table>* out) {
try {
return impl_->ReadFlatTable(out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadFlatTable(
const std::vector<int>& column_indices, std::shared_ptr<Table>* out) {
try {
return impl_->ReadFlatTable(column_indices, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
void FileReader::set_num_threads(int num_threads) {
impl_->set_num_threads(num_threads);
}
const ParquetFileReader* FileReader::parquet_reader() const {
return impl_->parquet_reader();
}
FlatColumnReader::Impl::Impl(MemoryPool* pool, const ColumnDescriptor* descr,
ParquetFileReader* reader, int column_index)
: pool_(pool),
descr_(descr),
reader_(reader),
column_index_(column_index),
next_row_group_(0),
values_buffer_(pool),
def_levels_buffer_(pool) {
NodeToField(descr_->schema_node(), &field_);
NextRowGroup();
}
template <typename ArrowType, typename ParquetType>
Status FlatColumnReader::Impl::ReadNonNullableBatch(
TypedColumnReader<ParquetType>* reader, int64_t values_to_read,
int64_t* levels_read) {
using ArrowCType = typename ArrowType::c_type;
using ParquetCType = typename ParquetType::c_type;
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(ParquetCType), false));
auto values = reinterpret_cast<ParquetCType*>(values_buffer_.mutable_data());
int64_t values_read;
PARQUET_CATCH_NOT_OK(*levels_read = reader->ReadBatch(
values_to_read, nullptr, nullptr, values, &values_read));
ArrowCType* out_ptr = reinterpret_cast<ArrowCType*>(data_buffer_ptr_);
std::copy(values, values + values_read, out_ptr + valid_bits_idx_);
valid_bits_idx_ += values_read;
return Status::OK();
}
#define NONNULLABLE_BATCH_FAST_PATH(ArrowType, ParquetType, CType) \
template <> \
Status FlatColumnReader::Impl::ReadNonNullableBatch<ArrowType, ParquetType>( \
TypedColumnReader<ParquetType> * reader, int64_t values_to_read, \
int64_t * levels_read) { \
int64_t values_read; \
CType* out_ptr = reinterpret_cast<CType*>(data_buffer_ptr_); \
PARQUET_CATCH_NOT_OK(*levels_read = reader->ReadBatch(values_to_read, nullptr, \
nullptr, out_ptr + valid_bits_idx_, &values_read)); \
\
valid_bits_idx_ += values_read; \
\
return Status::OK(); \
}
NONNULLABLE_BATCH_FAST_PATH(::arrow::Int32Type, Int32Type, int32_t)
NONNULLABLE_BATCH_FAST_PATH(::arrow::Int64Type, Int64Type, int64_t)
NONNULLABLE_BATCH_FAST_PATH(::arrow::FloatType, FloatType, float)
NONNULLABLE_BATCH_FAST_PATH(::arrow::DoubleType, DoubleType, double)
template <>
Status FlatColumnReader::Impl::ReadNonNullableBatch<::arrow::TimestampType, Int96Type>(
TypedColumnReader<Int96Type>* reader, int64_t values_to_read, int64_t* levels_read) {
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(Int96Type), false));
auto values = reinterpret_cast<Int96*>(values_buffer_.mutable_data());
int64_t values_read;
PARQUET_CATCH_NOT_OK(*levels_read = reader->ReadBatch(
values_to_read, nullptr, nullptr, values, &values_read));
int64_t* out_ptr = reinterpret_cast<int64_t*>(data_buffer_ptr_);
for (int64_t i = 0; i < values_read; i++) {
*out_ptr++ = impala_timestamp_to_nanoseconds(values[i]);
}
valid_bits_idx_ += values_read;
return Status::OK();
}
template <>
Status FlatColumnReader::Impl::ReadNonNullableBatch<::arrow::BooleanType, BooleanType>(
TypedColumnReader<BooleanType>* reader, int64_t values_to_read,
int64_t* levels_read) {
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(bool), false));
auto values = reinterpret_cast<bool*>(values_buffer_.mutable_data());
int64_t values_read;
PARQUET_CATCH_NOT_OK(*levels_read = reader->ReadBatch(
values_to_read, nullptr, nullptr, values, &values_read));
for (int64_t i = 0; i < values_read; i++) {
if (values[i]) { ::arrow::BitUtil::SetBit(data_buffer_ptr_, valid_bits_idx_); }
valid_bits_idx_++;
}
return Status::OK();
}
template <typename ArrowType, typename ParquetType>
Status FlatColumnReader::Impl::ReadNullableFlatBatch(
TypedColumnReader<ParquetType>* reader, int16_t* def_levels, int64_t values_to_read,
int64_t* levels_read) {
using ArrowCType = typename ArrowType::c_type;
using ParquetCType = typename ParquetType::c_type;
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(ParquetCType), false));
auto values = reinterpret_cast<ParquetCType*>(values_buffer_.mutable_data());
int null_count;
PARQUET_CATCH_NOT_OK(*levels_read =
reader->ReadBatchSpaced(values_to_read, def_levels, nullptr,
values, &null_count, valid_bits_ptr_, valid_bits_idx_));
auto data_ptr = reinterpret_cast<ArrowCType*>(data_buffer_ptr_);
INIT_BITSET(valid_bits_ptr_, valid_bits_idx_);
for (int64_t i = 0; i < *levels_read; i++) {
if (bitset & (1 << bit_offset)) { data_ptr[valid_bits_idx_ + i] = values[i]; }
READ_NEXT_BITSET(valid_bits_ptr_);
}
null_count_ += null_count;
valid_bits_idx_ += *levels_read;
return Status::OK();
}
#define NULLABLE_BATCH_FAST_PATH(ArrowType, ParquetType, CType) \
template <> \
Status FlatColumnReader::Impl::ReadNullableFlatBatch<ArrowType, ParquetType>( \
TypedColumnReader<ParquetType> * reader, int16_t * def_levels, \
int64_t values_to_read, int64_t * levels_read) { \
auto data_ptr = reinterpret_cast<CType*>(data_buffer_ptr_); \
int null_count; \
PARQUET_CATCH_NOT_OK(*levels_read = reader->ReadBatchSpaced(values_to_read, \
def_levels, nullptr, data_ptr + valid_bits_idx_, \
&null_count, valid_bits_ptr_, valid_bits_idx_)); \
\
valid_bits_idx_ += *levels_read; \
null_count_ += null_count; \
\
return Status::OK(); \
}
NULLABLE_BATCH_FAST_PATH(::arrow::Int32Type, Int32Type, int32_t)
NULLABLE_BATCH_FAST_PATH(::arrow::Int64Type, Int64Type, int64_t)
NULLABLE_BATCH_FAST_PATH(::arrow::FloatType, FloatType, float)
NULLABLE_BATCH_FAST_PATH(::arrow::DoubleType, DoubleType, double)
template <>
Status FlatColumnReader::Impl::ReadNullableFlatBatch<::arrow::TimestampType, Int96Type>(
TypedColumnReader<Int96Type>* reader, int16_t* def_levels, int64_t values_to_read,
int64_t* levels_read) {
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(Int96Type), false));
auto values = reinterpret_cast<Int96*>(values_buffer_.mutable_data());
int null_count;
PARQUET_CATCH_NOT_OK(*levels_read =
reader->ReadBatchSpaced(values_to_read, def_levels, nullptr,
values, &null_count, valid_bits_ptr_, valid_bits_idx_));
auto data_ptr = reinterpret_cast<int64_t*>(data_buffer_ptr_);
INIT_BITSET(valid_bits_ptr_, valid_bits_idx_);
for (int64_t i = 0; i < *levels_read; i++) {
if (bitset & (1 << bit_offset)) {
data_ptr[valid_bits_idx_ + i] = impala_timestamp_to_nanoseconds(values[i]);
}
READ_NEXT_BITSET(valid_bits_ptr_);
}
null_count_ += null_count;
valid_bits_idx_ += *levels_read;
return Status::OK();
}
template <>
Status FlatColumnReader::Impl::ReadNullableFlatBatch<::arrow::BooleanType, BooleanType>(
TypedColumnReader<BooleanType>* reader, int16_t* def_levels, int64_t values_to_read,
int64_t* levels_read) {
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(bool), false));
auto values = reinterpret_cast<bool*>(values_buffer_.mutable_data());
int null_count;
PARQUET_CATCH_NOT_OK(*levels_read =
reader->ReadBatchSpaced(values_to_read, def_levels, nullptr,
values, &null_count, valid_bits_ptr_, valid_bits_idx_));
INIT_BITSET(valid_bits_ptr_, valid_bits_idx_);
for (int64_t i = 0; i < *levels_read; i++) {
if (bitset & (1 << bit_offset)) {
if (values[i]) { ::arrow::BitUtil::SetBit(data_buffer_ptr_, valid_bits_idx_ + i); }
}
READ_NEXT_BITSET(valid_bits_ptr_);
}
valid_bits_idx_ += *levels_read;
null_count_ += null_count;
return Status::OK();
}
template <typename ArrowType>
Status FlatColumnReader::Impl::InitDataBuffer(int batch_size) {
using ArrowCType = typename ArrowType::c_type;
data_buffer_ = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(data_buffer_->Resize(batch_size * sizeof(ArrowCType), false));
data_buffer_ptr_ = data_buffer_->mutable_data();
return Status::OK();
}
template <>
Status FlatColumnReader::Impl::InitDataBuffer<::arrow::BooleanType>(int batch_size) {
data_buffer_ = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(data_buffer_->Resize(::arrow::BitUtil::CeilByte(batch_size) / 8, false));
data_buffer_ptr_ = data_buffer_->mutable_data();
memset(data_buffer_ptr_, 0, data_buffer_->size());
return Status::OK();
}
template <typename ArrowType, typename ParquetType>
Status FlatColumnReader::Impl::TypedReadBatch(
int batch_size, std::shared_ptr<Array>* out) {
using ArrowCType = typename ArrowType::c_type;
int values_to_read = batch_size;
RETURN_NOT_OK(InitDataBuffer<ArrowType>(batch_size));
valid_bits_idx_ = 0;
if (descr_->max_definition_level() > 0) {
int valid_bits_size = ::arrow::BitUtil::CeilByte(batch_size + 1) / 8;
valid_bits_buffer_ = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(valid_bits_buffer_->Resize(valid_bits_size, false));
valid_bits_ptr_ = valid_bits_buffer_->mutable_data();
memset(valid_bits_ptr_, 0, valid_bits_size);
null_count_ = 0;
}
while ((values_to_read > 0) && column_reader_) {
if (descr_->max_definition_level() > 0) {
RETURN_NOT_OK(def_levels_buffer_.Resize(values_to_read * sizeof(int16_t), false));
}
auto reader = dynamic_cast<TypedColumnReader<ParquetType>*>(column_reader_.get());
int64_t levels_read;
int16_t* def_levels = reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
if (descr_->max_definition_level() == 0) {
RETURN_NOT_OK((ReadNonNullableBatch<ArrowType, ParquetType>(
reader, values_to_read, &levels_read)));
} else {
// As per the defintion and checks for flat columns:
// descr_->max_definition_level() == 1
RETURN_NOT_OK((ReadNullableFlatBatch<ArrowType, ParquetType>(
reader, def_levels, values_to_read, &levels_read)));
}
values_to_read -= levels_read;
if (!column_reader_->HasNext()) { NextRowGroup(); }
}
if (descr_->max_definition_level() > 0) {
// TODO: Shrink arrays in the case they are too large
if (valid_bits_idx_ < batch_size * 0.8) {
// Shrink arrays as they are larger than the output.
// TODO(PARQUET-761/ARROW-360): Use realloc internally to shrink the arrays
// without the need for a copy. Given a decent underlying allocator this
// should still free some underlying pages to the OS.
auto data_buffer = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(data_buffer->Resize(valid_bits_idx_ * sizeof(ArrowCType), false));
memcpy(data_buffer->mutable_data(), data_buffer_->data(), data_buffer->size());
data_buffer_ = data_buffer;
auto valid_bits_buffer = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(valid_bits_buffer->Resize(
::arrow::BitUtil::CeilByte(valid_bits_idx_) / 8, false));
memcpy(valid_bits_buffer->mutable_data(), valid_bits_buffer_->data(),
valid_bits_buffer->size());
valid_bits_buffer_ = valid_bits_buffer;
}
*out = std::make_shared<ArrayType<ArrowType>>(
field_->type, valid_bits_idx_, data_buffer_, null_count_, valid_bits_buffer_);
// Relase the ownership
data_buffer_.reset();
valid_bits_buffer_.reset();
return Status::OK();
} else {
*out = std::make_shared<ArrayType<ArrowType>>(
field_->type, valid_bits_idx_, data_buffer_);
data_buffer_.reset();
return Status::OK();
}
}
template <>
Status FlatColumnReader::Impl::TypedReadBatch<::arrow::BooleanType, BooleanType>(
int batch_size, std::shared_ptr<Array>* out) {
int values_to_read = batch_size;
RETURN_NOT_OK(InitDataBuffer<::arrow::BooleanType>(batch_size));
valid_bits_idx_ = 0;
if (descr_->max_definition_level() > 0) {
valid_bits_buffer_ = std::make_shared<PoolBuffer>(pool_);
int valid_bits_size = ::arrow::BitUtil::CeilByte(batch_size + 1) / 8;
RETURN_NOT_OK(valid_bits_buffer_->Resize(valid_bits_size, false));
valid_bits_ptr_ = valid_bits_buffer_->mutable_data();
memset(valid_bits_ptr_, 0, valid_bits_size);
null_count_ = 0;
}
while ((values_to_read > 0) && column_reader_) {
if (descr_->max_definition_level() > 0) {
RETURN_NOT_OK(def_levels_buffer_.Resize(values_to_read * sizeof(int16_t), false));
}
auto reader = dynamic_cast<TypedColumnReader<BooleanType>*>(column_reader_.get());
int64_t levels_read;
int16_t* def_levels = reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
if (descr_->max_definition_level() == 0) {
RETURN_NOT_OK((ReadNonNullableBatch<::arrow::BooleanType, BooleanType>(
reader, values_to_read, &levels_read)));
} else {
// As per the defintion and checks for flat columns:
// descr_->max_definition_level() == 1
RETURN_NOT_OK((ReadNullableFlatBatch<::arrow::BooleanType, BooleanType>(
reader, def_levels, values_to_read, &levels_read)));
}
values_to_read -= levels_read;
if (!column_reader_->HasNext()) { NextRowGroup(); }
}
if (descr_->max_definition_level() > 0) {
// TODO: Shrink arrays in the case they are too large
if (valid_bits_idx_ < batch_size * 0.8) {
// Shrink arrays as they are larger than the output.
// TODO(PARQUET-761/ARROW-360): Use realloc internally to shrink the arrays
// without the need for a copy. Given a decent underlying allocator this
// should still free some underlying pages to the OS.
auto data_buffer = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(data_buffer->Resize(valid_bits_idx_ * sizeof(bool)));
memcpy(data_buffer->mutable_data(), data_buffer_->data(), data_buffer->size());
data_buffer_ = data_buffer;
auto valid_bits_buffer = std::make_shared<PoolBuffer>(pool_);
RETURN_NOT_OK(
valid_bits_buffer->Resize(::arrow::BitUtil::CeilByte(valid_bits_idx_) / 8));
memcpy(valid_bits_buffer->mutable_data(), valid_bits_buffer_->data(),
valid_bits_buffer->size());
valid_bits_buffer_ = valid_bits_buffer;
}
*out = std::make_shared<::arrow::BooleanArray>(
field_->type, valid_bits_idx_, data_buffer_, null_count_, valid_bits_buffer_);
// Relase the ownership
data_buffer_.reset();
valid_bits_buffer_.reset();
return Status::OK();
} else {
*out = std::make_shared<::arrow::BooleanArray>(
field_->type, valid_bits_idx_, data_buffer_);
data_buffer_.reset();
return Status::OK();
}
}
template <typename ArrowType>
Status FlatColumnReader::Impl::ReadByteArrayBatch(
int batch_size, std::shared_ptr<Array>* out) {
using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
int values_to_read = batch_size;
BuilderType builder(pool_, field_->type);
while ((values_to_read > 0) && column_reader_) {
RETURN_NOT_OK(values_buffer_.Resize(values_to_read * sizeof(ByteArray), false));
if (descr_->max_definition_level() > 0) {
RETURN_NOT_OK(def_levels_buffer_.Resize(values_to_read * sizeof(int16_t), false));
}
auto reader = dynamic_cast<TypedColumnReader<ByteArrayType>*>(column_reader_.get());
int64_t values_read;
int64_t levels_read;
int16_t* def_levels = reinterpret_cast<int16_t*>(def_levels_buffer_.mutable_data());
auto values = reinterpret_cast<ByteArray*>(values_buffer_.mutable_data());
PARQUET_CATCH_NOT_OK(levels_read = reader->ReadBatch(
values_to_read, def_levels, nullptr, values, &values_read));
values_to_read -= levels_read;
if (descr_->max_definition_level() == 0) {
for (int64_t i = 0; i < levels_read; i++) {
RETURN_NOT_OK(
builder.Append(reinterpret_cast<const char*>(values[i].ptr), values[i].len));
}
} else {
// descr_->max_definition_level() == 1
int values_idx = 0;
for (int64_t i = 0; i < levels_read; i++) {
if (def_levels[i] < descr_->max_definition_level()) {
RETURN_NOT_OK(builder.AppendNull());
} else {
RETURN_NOT_OK(
builder.Append(reinterpret_cast<const char*>(values[values_idx].ptr),
values[values_idx].len));
values_idx++;
}
}
}
if (!column_reader_->HasNext()) { NextRowGroup(); }
}
return builder.Finish(out);
}
template <>
Status FlatColumnReader::Impl::TypedReadBatch<::arrow::BinaryType, ByteArrayType>(
int batch_size, std::shared_ptr<Array>* out) {
return ReadByteArrayBatch<::arrow::BinaryType>(batch_size, out);
}
template <>
Status FlatColumnReader::Impl::TypedReadBatch<::arrow::StringType, ByteArrayType>(
int batch_size, std::shared_ptr<Array>* out) {
return ReadByteArrayBatch<::arrow::StringType>(batch_size, out);
}
#define TYPED_BATCH_CASE(ENUM, ArrowType, ParquetType) \
case ::arrow::Type::ENUM: \
return TypedReadBatch<ArrowType, ParquetType>(batch_size, out); \
break;
Status FlatColumnReader::Impl::NextBatch(int batch_size, std::shared_ptr<Array>* out) {
if (!column_reader_) {
// Exhausted all row groups.
*out = nullptr;
return Status::OK();
}
switch (field_->type->type) {
TYPED_BATCH_CASE(BOOL, ::arrow::BooleanType, BooleanType)
TYPED_BATCH_CASE(UINT8, ::arrow::UInt8Type, Int32Type)
TYPED_BATCH_CASE(INT8, ::arrow::Int8Type, Int32Type)
TYPED_BATCH_CASE(UINT16, ::arrow::UInt16Type, Int32Type)
TYPED_BATCH_CASE(INT16, ::arrow::Int16Type, Int32Type)
TYPED_BATCH_CASE(UINT32, ::arrow::UInt32Type, Int32Type)
TYPED_BATCH_CASE(INT32, ::arrow::Int32Type, Int32Type)
TYPED_BATCH_CASE(UINT64, ::arrow::UInt64Type, Int64Type)
TYPED_BATCH_CASE(INT64, ::arrow::Int64Type, Int64Type)
TYPED_BATCH_CASE(FLOAT, ::arrow::FloatType, FloatType)
TYPED_BATCH_CASE(DOUBLE, ::arrow::DoubleType, DoubleType)
TYPED_BATCH_CASE(STRING, ::arrow::StringType, ByteArrayType)
TYPED_BATCH_CASE(BINARY, ::arrow::BinaryType, ByteArrayType)
case ::arrow::Type::TIMESTAMP: {
::arrow::TimestampType* timestamp_type =
static_cast<::arrow::TimestampType*>(field_->type.get());
switch (timestamp_type->unit) {
case ::arrow::TimeUnit::MILLI:
return TypedReadBatch<::arrow::TimestampType, Int64Type>(batch_size, out);
break;
case ::arrow::TimeUnit::NANO:
return TypedReadBatch<::arrow::TimestampType, Int96Type>(batch_size, out);
break;
default:
return Status::NotImplemented("TimeUnit not supported");
}
break;
}
default:
return Status::NotImplemented(field_->type->ToString());
}
}
void FlatColumnReader::Impl::NextRowGroup() {
if (next_row_group_ < reader_->metadata()->num_row_groups()) {
column_reader_ = reader_->RowGroup(next_row_group_)->Column(column_index_);
next_row_group_++;
} else {
column_reader_ = nullptr;
}
}
FlatColumnReader::FlatColumnReader(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
FlatColumnReader::~FlatColumnReader() {}
Status FlatColumnReader::NextBatch(int batch_size, std::shared_ptr<Array>* out) {
return impl_->NextBatch(batch_size, out);
}
} // namespace arrow
} // namespace parquet
|
801b1ac30d6406674c2770cf311039d261e47db3
|
[
"C++"
] | 2
|
C++
|
meox/parquet-cpp
|
d1f774e141f2b20390b5a5f2a0c86141f91e666f
|
eb70b91a91d0f2cc6a0ee8c4c73bba06a18c74d4
|
refs/heads/master
|
<repo_name>jewarner57/Few2.1-Final-Assessment<file_sep>/index.ts
const EasyDate = require('@jewarner57/easydate')
type User = {
id: number
first_name: string
last_name: string
purchased: Date
lastpayment: Date
phone: string
make: string
model: string
city: string
};
// Challenge 0
const userData: User[] = require('./data.json')
function printUserData(userData: User[]): void {
userData.forEach((user: User): void => {
// Challenge 1
const firstName: string = capitalize(user.first_name)
const lastName: string = capitalize(user.last_name)
console.log(`${firstName} ${lastName}`)
// Make and Model
const make: string = titleCase(user.make)
const model: string = titleCase(user.model)
console.log(`${make} ${model}`)
// Challenge 2
const purchasedDate: typeof EasyDate = new EasyDate(user.purchased)
console.log(purchasedDate.format('Purchased: %B %D, %Y'))
// Challenge 3
const lastPaymentDate: typeof EasyDate = new EasyDate(user.lastpayment)
const timeAgo: string = new EasyDate().when(lastPaymentDate)
console.log(`Last Payment: ${timeAgo}`)
// Challenge 4
console.log(`Phone: ${formatPhoneNumer(user.phone)}`)
// City name
console.log(`City: ${titleCase(user.city)}`)
// Add trailing newline
console.log()
})
}
// Uppercase the first letter of a string
function capitalize(str: string): string {
return `${str[0].toUpperCase()}${str.slice(1)}`
}
// Uppercase the first letter in each word of a string
function titleCase(str: string): string {
// split words into array
const words: string[] = str.split(' ')
// capitalize each word
const titledWords: string[] = words.map((word: string): string => {
return capitalize(word)
})
// return the new string
return titledWords.join(' ')
}
// Takes a 10 digit phone number string and formats it into (000) 000-0000 format
function formatPhoneNumer(phoneNum: string): string {
if (phoneNum.length != 10) {
return `Phone number: ${phoneNum} is not valid.`
}
const AreaCode: string = phoneNum.substring(0, 3)
const Prefix: string = phoneNum.substring(3, 6)
const Subscriber: string = phoneNum.substring(6, 10)
return `(${AreaCode}) ${Prefix}-${Subscriber}`
}
// printUserData(userData)
module.exports = { formatPhoneNumer, printUserData, capitalize, titleCase }<file_sep>/index.js
var EasyDate = require('@jewarner57/easydate');
// Challenge 0
var userData = require('./data.json');
function printUserData(userData) {
userData.forEach(function (user) {
// Challenge 1
var firstName = capitalize(user.first_name);
var lastName = capitalize(user.last_name);
console.log(firstName + " " + lastName);
// Make and Model
var make = titleCase(user.make);
var model = titleCase(user.model);
console.log(make + " " + model);
// Challenge 2
var purchasedDate = new EasyDate(user.purchased);
console.log(purchasedDate.format('Purchased: %B %D, %Y'));
// Challenge 3
var lastPaymentDate = new EasyDate(user.lastpayment);
var timeAgo = new EasyDate().when(lastPaymentDate);
console.log("Last Payment: " + timeAgo);
// Challenge 4
console.log("Phone: " + formatPhoneNumer(user.phone));
// City name
console.log("City: " + titleCase(user.city));
// Add trailing newline
console.log();
});
}
// Uppercase the first letter of a string
function capitalize(str) {
return "" + str[0].toUpperCase() + str.slice(1);
}
// Uppercase the first letter in each word of a string
function titleCase(str) {
// split words into array
var words = str.split(' ');
// capitalize each word
var titledWords = words.map(function (word) {
return capitalize(word);
});
// return the new string
return titledWords.join(' ');
}
// Takes a 10 digit phone number string and formats it into (000) 000-0000 format
function formatPhoneNumer(phoneNum) {
if (phoneNum.length != 10) {
return "Phone number: " + phoneNum + " is not valid.";
}
var AreaCode = phoneNum.substring(0, 3);
var Prefix = phoneNum.substring(3, 6);
var Subscriber = phoneNum.substring(6, 10);
return "(" + AreaCode + ") " + Prefix + "-" + Subscriber;
}
// printUserData(userData)
module.exports = { formatPhoneNumer: formatPhoneNumer, printUserData: printUserData, capitalize: capitalize, titleCase: titleCase };
<file_sep>/tests/index.test.js
/* eslint-disable no-undef */
const index = require('../index.js')
// Challenge 5
test('All Zeros', () => {
expect(index.formatPhoneNumer('0000000000')).toBe('(000) 000-0000')
})
test('Various Correct Numbers', () => {
expect(index.formatPhoneNumer('2484345508')).toBe('(248) 434-5508')
expect(index.formatPhoneNumer('6788675309')).toBe('(678) 867-5309')
})
test('Badly formatted numbers', () => {
expect(index.formatPhoneNumer('248-4345-508')).toBe('Phone number: 248-4345-508 is not valid.')
expect(index.formatPhoneNumer('(678) 867-5309')).toBe('Phone number: (678) 867-5309 is not valid.')
})
test('Empty String', () => {
expect(index.formatPhoneNumer('')).toBe('Phone number: is not valid.')
})
test('Too Short', () => {
expect(index.formatPhoneNumer('100')).toBe('Phone number: 100 is not valid.')
})
test('Too Long', () => {
expect(index.formatPhoneNumer('18003983982463')).toBe('Phone number: 18003983982463 is not valid.')
})
|
68b725a3f832583faa264e375235403ff75aec9d
|
[
"JavaScript",
"TypeScript"
] | 3
|
TypeScript
|
jewarner57/Few2.1-Final-Assessment
|
0246fef9ebf4a6f36098e108c69a693511995601
|
1260b2b4c3f51156715f0231e1da64c198151606
|
refs/heads/main
|
<file_sep><?php
/**
* Plugin Family Id: dangoodman/wc-weight-based-shipping
* Plugin Name: WooCommerce Weight Based Shipping
* Plugin URI: https://wordpress.org/plugins/weight-based-shipping-for-woocommerce/
* Description: Simple yet flexible shipping method for WooCommerce.
* Version: 5.3.12
* Author: <EMAIL>
* Author URI: https://weightbasedshipping.com
* Requires PHP: 5.6
* Requires at least: 4.0
* Tested up to: 5.7
* WC requires at least: 3.2
* WC tested up to: 5.3
*/
if (!class_exists('WbsVendors_DgmWpPluginBootstrapGuard', false)) {
require_once(__DIR__ .'/server/vendor/dangoodman/wp-plugin-bootstrap-guard/DgmWpPluginBootstrapGuard.php');
}
WbsVendors_DgmWpPluginBootstrapGuard::checkPrerequisitesAndBootstrap(
'WooCommerce Weight Based Shipping',
'5.6', '4.0', '3.2',
__DIR__ .'/bootstrap.php'
);<file_sep><?php
namespace WbsVendors\Dgm\Shengine\Grouping;
use Dgm\Shengine\Interfaces\IGrouping;
use Dgm\Shengine\Interfaces\IItem;
use Dgm\Shengine\Interfaces\IPackage;
class NoopGrouping implements \WbsVendors\Dgm\Shengine\Interfaces\IGrouping
{
public function getPackageIds(\WbsVendors\Dgm\Shengine\Interfaces\IItem $item)
{
return ['noop'];
}
public function multiplePackagesExpected()
{
return false;
}
}
|
1f3d25ee8206e358d34df2e886a22803f5bd8991
|
[
"PHP"
] | 2
|
PHP
|
com0t/50K-100K-xba
|
19871f56b3aa0c0dd893790217c2081e4571d4df
|
1cde959e9bb32d1fc132b614314648b37ad16a5b
|
refs/heads/master
|
<file_sep>//
// any.hpp
// any
//
// Created by <NAME> on 22.03.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
#include <cstdio>
#include <utility>
#include <cstdio>
#include <type_traits>
#include <cstdlib>
namespace my_any {
template <typename T>
static void get_copier(void* dst, void const* src) {
new(dst) T(*(T const*) src);
}
template <typename T>
static void get_big_deleter(void *raw) {
delete((T*) raw);
}
template <typename T>
static void get_small_deleter(void *raw) {
((T*) raw) -> ~T();
}
template <typename T>
static void get_mover(void *dst, void *src) {
new(dst) T(std::move(*(T*) src));
}
template <typename T>
static void* get_allocator() {
return new typename std::aligned_storage < sizeof(T), alignof(T) > ::type;
}
}
struct any {
any() {
status = 0;
storage = {};
deleter = [](void*) {};
copier = [](void*, void const*) {};
mover = [](void*, void*){};
allocator = []() -> void* {return nullptr;}; {};
}
any(any const &other) {
status = other.status;
deleter = other.deleter;
copier = other.copier;
mover = other.mover;
allocator = other.allocator;
if (status == 1) {
copier(&storage, &other.storage);
}
else if (status == 2) {
void *tmp = allocator();
copier(tmp, *(void**) &other.storage);
*(void**) & storage = tmp;
}
}
any(any &&other) {
status = other.status;
deleter = other.deleter;
copier = other.copier;
mover = other.mover;
allocator = other.allocator;
if (status == 1) {
mover(&storage, &other.storage);
} else if (status == 2) {
void * tmp = allocator();
mover(tmp, *(void**) & other.storage);
}
}
template < typename T, typename TMP = typename std::enable_if <!std::is_same <std::decay_t<T>, any>::value>::type>
any(T&& val) {
using T_decay_t = std::decay_t <T> ;
if (sizeof(T_decay_t) > SMALL_SIZE) {
status = 2;
void* tmp = new T_decay_t(std::forward <T> (val));
*(void**)& storage = tmp;
deleter = my_any::get_big_deleter <T_decay_t> ;
} else {
status = 1;
new(&storage) T_decay_t(std::forward <T> (val));
deleter = my_any::get_small_deleter <T_decay_t> ;
}
copier = my_any::get_copier <T_decay_t>;
mover = my_any::get_mover <T_decay_t>;
allocator = my_any::get_allocator <T_decay_t>;
}
any& operator = (any const &other) {
any(other).swap(*this);
return *this;
}
any& operator = (any &&other) {
any(std::move(other)).swap(*this);
return *this;
}
template <typename T, typename TMP = typename std::enable_if <!std::is_same <std::decay_t<T>, any>::value>::type>
any& operator = (T&& other) {
any(std::forward <T> (other)).swap(*this);
return *this;
}
~any() {
clear();
}
void swap(any& other) {
std::aligned_storage<SMALL_SIZE, SMALL_SIZE>::type swap_var;
if (status == 1 && other.status == 1) {
mover (&swap_var, &storage);
deleter (&storage);
other.mover (&storage, &other.storage);
other.deleter (&other.storage);
mover (&other.storage, &swap_var);
deleter (&swap_var);
} else if (status == 1 && other.status == 2) {
mover (&swap_var, &storage);
deleter (&storage);
std::swap (*(void**)&storage, *(void**)&other.storage);
mover (&other.storage, &swap_var);
deleter (&swap_var);
} else if (status == 2 && other.status == 1) {
std::aligned_storage<SMALL_SIZE, SMALL_SIZE>::type swap_var;
other.mover (&swap_var, &other.storage);
other.deleter (&storage);
std::swap (*(void**)&other.storage, *(void**)&storage);
other.mover (&storage, &swap_var);
other.deleter (&swap_var);
} else if (status == 2 && other.status == 2) {
std::swap(*(void**)&storage, *(void**)&other.storage);
}
std::swap(status, other.status);
std::swap(deleter, other.deleter);
std::swap(copier, other.copier);
std::swap(mover, other.mover);
std::swap(allocator, other.allocator);
}
template <typename T>
friend T any_cast(const any& _any);
template <typename T>
friend T any_cast(any& _any);
template <typename T>
friend T any_cast(any&& _any);
template <typename T>
friend T
const* any_cast(any const* _any);
template <typename T>
friend T* any_cast(any* _any);
private:
static constexpr size_t SMALL_SIZE = 16;
size_t status;
std::aligned_storage <SMALL_SIZE, SMALL_SIZE> ::type storage;
void(*deleter) (void*);
void(*copier) (void*, void const*);
void(*mover) (void*, void*);
void*(*allocator) (void);
void clear() {
switch (status) {
case 1:
deleter(& storage);
status = 0;
break;
case 2:
deleter(*(void**) & storage);
status = 0;
break;
default:
break;
}
}
void* get_storage() const {
switch (status) {
case 0:
return nullptr;
case 1:
return (void*) & storage;
default:
return *(void**) & storage;
}
}
};
template <typename T >
T any_cast(const any &_any) {
void * result = _any.get_storage();
return *(std::add_const_t < std::remove_reference_t <T>> * ) result;
}
template <typename T>
T any_cast(any &_any) {
void * result = _any.get_storage();
return *(std::remove_reference_t <T> * ) result;
}
template <typename T>
T any_cast(any &&_any) {
void * result = _any.get_storage();
return *(std::remove_reference_t <T> * ) result;
}
template <typename T>
T const * any_cast(any const *_any) {
const T * result = _any -> get_storage();
return result;
}
template <typename T>
T * any_cast(any *_any) {
T * result = _any -> get_storage();
return result;
}
|
ae44d4e34589449ab78439f86a8100ddc0807dab
|
[
"C++"
] | 1
|
C++
|
kekcik/any
|
d2826a2d3acca7fffcb11f93107b587321bd7ac8
|
ebb1487dac28afba91020c31f5de74edb695d233
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.