blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
57d8977b110ecf05339c91cc08180c419a296f6c | 6243026351c5bb42a52c3c5e0a028f278e378471 | /Minigin/TextureManager.h | e9cc1fa78a94d11dddd06a021753b68ebe07781c | [] | no_license | jsilva96/Exam_Assignment | aceef5bf6dbff420956dbd9df53dbb0f7c26e0cc | 5fbc5cf418ca3378672e9ea8a067926911cab74e | refs/heads/master | 2022-01-14T14:22:25.328627 | 2019-05-26T20:35:23 | 2019-05-26T20:35:23 | 186,192,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | h | TextureManager.h | #pragma once
#include "Singleton.h"
#include <map>
namespace dae
{
class Texture2D;
}
class TextureManager : public dae::Singleton<TextureManager>
{
public:
TextureManager() = default;
~TextureManager();
dae::Texture2D* GetTexture(const std::string& path);
private:
dae::Texture2D* CreateNewTexture(const std::string& path);
std::map<std::string, dae::Texture2D*> m_Textures;
};
|
a2683eacc8b034f6f2246d242b8e310c86b7cb50 | 6c49d899439d3decf463c553fbc1038f6aade1cb | /Soar-SC/Source/Soar_Link.h | 369ea26c69302a9ed78a77a9dd368b0bb00dc476 | [] | no_license | Sonophoto/Soar-SC | 668ef6634ada1d0525e3994aa539cf66fdff46d0 | 8c6e6752de57df172d813d036700c5bc555c32a9 | refs/heads/master | 2021-01-12T22:07:47.031277 | 2013-06-04T20:47:33 | 2013-06-04T20:47:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,872 | h | Soar_Link.h | #ifndef SOAR_LINK_H
#define SOAR_LINK_H 1
//SDL Headers
#include "SDL/SDL_thread.h"
#include "SDL/SDL_mutex.h"
//SML Headers
#include "sml_Client.h"
//C++ Standard Library Headers
#include <iostream>
#include <fstream>
#include <vector>
//Windows Headers
#include <windows.h> //For windows related fuctions
//C Standard Library Headers
#include <time.h>
//Soar SC Headers
#include "Terrain.h"
#include <BWAPI.h>
class Soar_SC;
class Soar_Unit;
class Soar_Link //The AI class. Inherits from AIModule to use BWAPI functions.
{
public:
//Class stuff
Soar_Link(Soar_SC* soar_sc_link);
~Soar_Link();
//Soar agent thread
int soar_agent_thread();
//Soar agent handlers
void print_soar(sml::smlPrintEventId id, void *d, sml::Agent *a, char const *m);
void output_handler(sml::smlRunEventId id, void* d, sml::Agent *a, sml::smlPhase phase);
void misc_handler(sml::smlRunEventId id, void* d, sml::Agent *a, sml::smlPhase phase);
void update_fogOfWar(float x_start, float y_start, float size_x, float size_y);
//BWAPI Link Stuff
//Getters & Setters
void SendSVSInput(std::string input);
void ExecuteCommandLine(std::string input);
sml::Identifier* GetOutputLink();
sml::Identifier* GetInputLink();
sml::Kernel* GetKernel() { return kernel; }
sml::Agent* GetAgent() { return agent; }
//Soar Handlers
void add_resource(int bw_id, int count, BWAPI::Position position, BWAPI::UnitType type);
void delete_resource(int bw_id);
void update_resource_count(int minerals, int gas, int total_supplies, int used_supplies);
void update_update_unit_count(std::map<BWAPI::UnitType, unsigned int> unit_counts);
void start_soar_run();
void send_base_input(sml::Agent* agent, bool wait_for_analyzer);
int get_decisions();
void set_decisions(int new_count);
Soar_Unit* soar_unit_from_svsobject_id(std::string svsobject_id);
private:
std::vector<Soar_Unit*> fog_tiles;
std::vector<Soar_Unit*> terrain_corners;
int decisions; //Should use #pragma omp atomic for this
Soar_SC* soar_sc_link;
sml::Kernel* kernel; //Pointer to the soar kernel created
sml::Agent* agent; //Pointer to the soar agent created
SDL_Thread* soar_thread; //Variable for the thread for initially running the agent
SDL_mutex* mu; //Variable for holding the mutex used by this classes's threads and event calls
bool kill_threads;
bool had_interrupt; //Used for detecting when the agent is stopped, set to true when it is by the misc handler, then it tells the event queue to update forever
Terrain* terrain; //Terrain analyzer thread, analyzes the map and puts everything into SVS
//Soar Helper Functions
static sml::WMElement* get_child(std::string name, sml::Identifier* parent);
static sml::WMElement* find_child_with_attribute_value(std::string attribute_name, std::string value, sml::Identifier* parent);
static sml::WMElement* find_child_with_attribute_value(std::string child_name, std::string attribute_name, std::string value, sml::Identifier* parent);
};
//Global stuff, all just calls the respective Soar_Link function
extern void output_global_handler(sml::smlRunEventId id, void* d, sml::Agent *a, sml::smlPhase phase); //Handle for the output phase of Soar
extern void printcb(sml::smlPrintEventId id, void *d, sml::Agent *a, char const *m); //Print handler for Soar
extern void misc_global_handler(sml::smlRunEventId id, void* d, sml::Agent *a, sml::smlPhase phase); //Misc handler for Soar
//Thread globals, calls the Soar_Link function
extern int thread_runner_soar(void* link); //Initial thread for running the agent
extern void send_base_input_global(sml::smlAgentEventId id, void* pUserData, sml::Agent* pAgent); //Called at agent creation and agent reinit
extern void SetThreadName(const char *threadName, DWORD threadId);
#endif
|
7273e13dbbe5b22c3b0285f2285211c1baef011b | 5f02aa5e3449c9d3002c8a248b67e965d377cedf | /Source-32-Bit/Page512.cpp | ade829bd414efe4203a3f6f165624afba55459df | [] | no_license | YYGYYGyy/LSPC-Loading-Simulation-Program | bb94fe04d4b620d6afd30b9d40eb582b84283a0b | 2f846c6719088642178a636ed3ae7630d8df9afd | refs/heads/master | 2021-09-24T04:46:44.649224 | 2018-03-07T19:05:35 | 2018-03-07T19:05:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,263 | cpp | Page512.cpp | // Page512.cpp: implementation of the CPage512 class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "lspc.h"
#include "Page512.h"
#include "MainFrm.h"
#include "LSPCView.h"
#include "LSPCDoc.h"
#include "LSPCMODEL.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPage512::CPage512()
{
}
CPage512::CPage512(UINT nID) : CPageAdd(nID)
{
}
CPage512::~CPage512()
{
}
void CPage512::InitGrid()
{
m_Grid.SetRowCount(1);
m_Grid.SetColumnCount(7);
m_Grid.SetFixedRowCount(1);
m_Grid.SetFixedColumnCount(0);
CString str[] ={"rgid","benod","tcben","expod","brbod","brbod_inc","exprel"}; // column name
GV_ITEM Item;
Item.mask = GVIF_TEXT|GVIF_FORMAT;
Item.row = 0;
Item.nFormat = DT_RIGHT|DT_VCENTER|DT_SINGLELINE;
for (int col = 0; col < m_Grid.GetColumnCount(); col++)
{
Item.col = col;
Item.szText = str[col];
m_Grid.SetItem(&Item);
}
m_Grid.AutoSize();
}
BOOL CPage512::UpdateData( BOOL bSaveAndValidate)
{
CMainFrame *pMain = (CMainFrame *)AfxGetMainWnd();
CLSPCView *pView = (CLSPCView *)pMain->m_wndSplitter.GetPane(0,1);
if(pView == NULL)
return false;
CLSPCDoc *pDoc = pView->GetDocument();
if(pDoc == NULL)
return false;
int nNum = pDoc->lspc.nrgroup;
if(bSaveAndValidate)
{
if(pDoc->lspc.oxfg != 1)
return true;
int nRow = m_Grid.GetRowCount() - 1;
if(nRow != nNum)
{
AfxMessageBox("Card 512: Number of rows should be equal to the number of stream groups in Card 512!");
Log("Card 512: Number of rows should be equal to nrgroup in Card 512!");
return false;
}
// delete the old one
if(pDoc->lspc.ox_parm2 != NULL)
delete [](pDoc->lspc.ox_parm2);
if (nNum > 0)
pDoc->lspc.ox_parm2 = new OX_PARA2[nNum];
for(int i = 0; i < nNum; ++i)
{
pDoc->lspc.ox_parm2[i].gid = m_Grid.GetItemInt(i+1, 0);
pDoc->lspc.ox_parm2[i].benod = m_Grid.GetItemFloat(i+1,1);
pDoc->lspc.ox_parm2[i].tcben = m_Grid.GetItemFloat(i+1,2);
pDoc->lspc.ox_parm2[i].expod = m_Grid.GetItemFloat(i+1,3);
pDoc->lspc.ox_parm2[i].brbod = m_Grid.GetItemFloat(i+1,4);
pDoc->lspc.ox_parm2[i].brbod_inc = m_Grid.GetItemFloat(i+1,5);
pDoc->lspc.ox_parm2[i].exprel = m_Grid.GetItemFloat(i+1,6);
}
}
else
{
InitGrid();
if(pDoc->lspc.ox_parm2 == NULL)
return true;
CSize size = m_Grid.GetTextExtent(" ");
for(int i =0; i < nNum; ++i)
{
m_Grid.InsertRow(_T(""), -1);
int nRow = m_Grid.GetRowCount() - 1;
m_Grid.SetRowHeight(nRow,size.cy);
m_Grid.SetItemInt(nRow, 0, pDoc->lspc.ox_parm2[i].gid);
m_Grid.SetItemFloat(nRow,1, pDoc->lspc.ox_parm2[i].benod);
m_Grid.SetItemFloat(nRow,2, pDoc->lspc.ox_parm2[i].tcben);
m_Grid.SetItemFloat(nRow,3, pDoc->lspc.ox_parm2[i].expod);
m_Grid.SetItemFloat(nRow,4, pDoc->lspc.ox_parm2[i].brbod);
m_Grid.SetItemFloat(nRow,5, pDoc->lspc.ox_parm2[i].brbod_inc);
m_Grid.SetItemFloat(nRow,6, pDoc->lspc.ox_parm2[i].exprel);
}
m_Grid.Invalidate();
m_Grid.AutoSize();
}
return TRUE;
}
|
16bad6d458bb43db33857d8fa946abd425c09688 | f5303bee9003fe3ace6f82fa69de0377cea45cd8 | /cli/src/list.cpp | 608f2008920ef87405a68c0218474dcd1e1aa319 | [
"MIT"
] | permissive | rdmenezes/exodusdb | 82c55d8c43934c30821dd2a752e83c1d792e154a | f732e366b74ff4697890ec0682bc3697b8cb0bfb | refs/heads/master | 2021-01-16T00:27:49.522747 | 2014-12-24T18:01:51 | 2014-12-24T18:01:51 | 32,968,924 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,244 | cpp | list.cpp | /*
//Exodus Copyright (c) 2009 Stephen Bush
//Licence http://www.opensource.org/licenses/mit-license.php
This is a complete ACCESS/ENGLISH/LIST replacement that can output in DOS or HTML format.
It is an attempt to show a substantial program written in Exodus's reincarnation of Multivalue Basic.
The original Pick Basic version was in heavy production usage for many years.
It is written using Exodus OO flavour syntax not traditional flavour.
Traditional - honed by usage over the decades. function names on the left and parameters on the right.
printl(oconv(field(extract(xx,6),"/",2),"D2"));
OO flavour - does exactly the same thing but is perhaps easier to read from left to right in one pass:
xx.a(6).field(L"/",2).oconv(L"D2").outputl();
xx.a(6) stands for "xx<6>" in mv/pick. <> brackets cannot be used for functions in c++. "a" stands for "attribute".
Hybrid:
printl(xx.a(6).field(L"/",2).oconv(L"D2"));
Comments about style:
1. Decided to stick with wordier "xx.a(99)" instead exodus's "xx(99)" for now because
a. Exodus lack of xx<99> syntax makes it harder to understand what xx(99) means
*especially* because list also makes liberal use of dim arrays which have the same round brackets
b. It makes LIST marginally more portable into languages like java which are slightly less flexible syntaxwise
2. Using "int" instead of "var" for "for loop" index variables despite the fact that int doesnt always behave
precisely like pick integers, speed is important in this program and C++ allows us access to raw power when we need it.
3. Note the familiar "goto" statement which considerably eases porting of mv basic to Exodus.
This can be a major point scorer for Exodus because "goto" is banished from almost all other languages.
Exodus's "goto" cannot jump over "var" statements or into/out of subroutines some code refactoring
may be still be required during porting.
4. L prefix to all strings is not required but faster for utility programs *unbenchmarked
usage
list ads brand_code brand_name with brand_code 'XYZ'
NB if using from shells like bash then double quotes must be prefixed by \ and () should be done with {}
Type just list by itself to get a summary of its syntax
*/
#include <exodus/program.h>
//For normal programs, global variables that should be generally available to all subroutines
//should be declared, and optionally *simply* initialised, before the programinit() line.
//"simply initialised" means set to expressons using raw numbers and strings.
//eg 'var xx="xyz";' or 'var xx=100.5;' etc.
//NB FOLLOWING SECTION is only declaration and optional *simple* initialisation of global variables.
//In Exodus, all programming proper is to be done inside the main or other functions and subroutines
//AFTER the "programinit()" line which can be found below.
//these global variables are not thread safe
//unless they are put as MEMBER variables
//ie after the programinit() and before the programexit line
//and outside the main and other functions (which are c++ inline member functions)
//but then they cannot be simply initialised
//and would have to be initialised in the main() or other function
var datafile;
var quotes=DQ^SQ;
//var crlf="\r\n";
//put() on standard out (on windows at least) converts \n to 0d 0a automatically
//and manually outputing 0d 0a results in 0d 0d 0a in the file
var crlf="\n";
//some identifying name (from environment?)
var company="";
var wordn;
//var sentencex=COMMAND;//only const exodus system variables can be used before programinit()
var sentencex="";
var ignorewords="";
var html;
var printing;//only prefers @lptr to @crt if no columns specified
var tx;
var ncols;
var breakleveln;
var breakcolns="";
var blockn=0;
var nblocks=0;
var orighead;
var detsupp="";
var nbreaks=0;
var anytotals=0;
var recn;
var bodyln;
var breakoptions="";
var pagebreakcoln="";
var topmargin = 0;
var totalflag = 0;
var breakonflag = 0;
//use <COL> for hiding non-totalled cols in det-supp (slow)
var usecols = 0;
var startcharn;
var newmarklevel;
var previousmarklevel;
var lastid;
var crtx="";
var idsupp="";
var dblspc="";
var maxnrecs=0;
var keylist="";
var gtotsupp="";
var gtotreq="";
var nobase="";
var limits="";
var nlimits=0;
int coln=0;
var head = L"";
var foot = L"";
var tr;
var trx;
var td;
var tdx;
var tt;
var nbsp;
var dictmd;
var decimalchar;
//when exodus gets a non-destructive redim then this max columns restriction will be removed
#define maxncols 1000
dim colname(maxncols);
//dim colfile(maxncols);
dim coldict(maxncols);
dim mcol(maxncols);
dim pcol(maxncols);
dim ccol(maxncols);
dim scol(maxncols);
dim icol(maxncols);
dim wcol(maxncols);
//the following will be redim'ed to the required size further down
//once the number of BREAK-ON statements is determined
dim breakcount;
dim breaktotal;
dim breakvalue;
dim oldbreakvalue;
var word;
var filename;
var dictfilename;
var xx;
var printtxmark;
var nextword;
var dictrec;
var charn;//num
var underline;
var colunderline;
var bar;
var srcfile;
var clientmark;
var readerr;//num
var temp;
var cursor;
var str1;
var str2;
var str3;
var searchchar;
var underline2;
var cell;//num
var colbreakn;
var char3;
//TODO maybe implement printtext as normal exodus internal or external subroutine
//although it is a good example how you can use objects in Exodus.
#include "printtext.h"
//programinit() is required AFTER program globals and BEFORE all local functions and subroutines including main()
//in MV terms, "programinit" indicates the start of a set of functions and variables that form a single "program"
//in OO terms, "programinit()" indicates the start of a "class"
programinit()
//all programs must have a "function main()" that returns an integer - usually 0 to indicate success.
/////////////////
function main() {
/////////////////
USER0="";
printer1.init(mv);
//@sentence='LIST 10 SCHEDULES BY VEHICLE_CODE with vehicle_code "kjh kjh" VEHICLE_NAME BREAK-ON VEHICLE_CODE BREAK-ON VEHICLE_CODE TOTAL PRICE (SX)'
//@sentence='list markets code name'
if (dcount(COMMAND,FM)==1)
abort(
"Syntax is :"
"\nlist {n} (filename) {fieldnames} {selectionclause} {orderclause} {modifiers} (options)"
"\n"
"\nlist {n} (filename)"
"\n {using (filename) }"
"\n"
"\n { {total|break-on} (fieldname)"
"\n {justlen \"(L|R|Tnnn)\" }"
"\n {colhead \"(title)\" }"
"\n {oconv \"(oconvcode)\" }"
"\n } ..."
"\n"
"\n { {by|by-dsnd} (fieldname) } ..."
"\n"
"\n { {with|without|limit} {not|no|every} (fieldname)"
"\n | {eq|ne|gt|lt|ge||le|starting|ending|containing}"
"\n [value] ...}"
"\n | {between"
"\n [value] and [value]}"
"\n } {and|or|(|) with|without|limit etc...}"
"\n"
"\n { \"(keyvalue)\" } ..."
"\n"
"\n {heading {\"(headingtext&options)\"} }"
"\n {footing {\"(footingtext&options)\"} }"
"\n {grand-total {\"(titletext&options)\"} }"
"\n"
"\n {det-supp|det-supp2}"
"\n {gtot-supp}"
"\n {id-supp}"
"\n"
"\n {(options)}"
"\n"
"\nOptions: (H)tml (P)rint"
"\n"
"\nOn Unix prefix special characters like \" ' etc. with \\. Use {} instead of ()."
"\nOn Windows use ' instead of \". Use the word GT instead of the > character."
);
/*
BREAK-ON fieldname/no
GRAND-TOTAL grandtotaltext
TOTAL fieldname/no
HEADING headingtext
FOOTING footingtext
JUSTLEN justificationlengthcode
COLHEAD columntitletext
OCONV oconvcode
DET-SUPP
DET-SUPP2
GTOT-SUPP
DBL-SPC
IGNOREWORD
NO-BASE
{{WITH|WITHOUT|LIMIT} {NOT|NO|EVERY} fieldname|fieldno {NOT} {{EQUAL|EQ|NE|GT|LT|GE|LE|=|<>|>|<|>=|<=|STARTING|ENDING|CONTAINING|MATCHING} value ...|BETWEEN value AND value}
*/
sentencex=COMMAND.convert(FM," ");
var options=OPTIONS.ucase();
//declare function get.cursor,put.cursor
if (USER2[2] eq L"C")
decimalchar = L",";
else
decimalchar = ".";
DICT = L"";
html = index(options,"H");
printing = index(options,"P");
if (html) {
tr = L"<tr>";
trx = L"</tr>" ^ crlf;
td = L"<td>";
tdx = L"</td>";
nbsp = L" ";
tt = SYSTEM.a(2);
tt.swapper(L".txt", L".htm");
SYSTEM.r(2, tt);
printer1.html=1;
} else {
tr = L"";
trx = crlf;
td = L"";
tdx = L" ";
nbsp = L"";
}
//automatically create dict_md if it is not present so you can list dictionaries
if (not open(L"dict_md",dictmd)) {
createfile(L"dict_md");
if (open(L"dict_md",dictmd)) {
//prepare some dictionary records
var dictrecs = L"";
dictrecs = L"@id |F|0 |Id |S|||||L|20";
dictrecs ^= FM ^ L"type |F|1 |Type |S|||||L|4";
dictrecs ^= FM ^ L"fmc |F|2 |Field |S|||||R|3";
dictrecs ^= FM ^ L"title |F|3 |Title |M|||||T|20";
dictrecs ^= FM ^ L"sm |F|4 |SM |S|||||L|1";
dictrecs ^= FM ^ L"part |F|5 |Part |S|||||R|2";
dictrecs ^= FM ^ L"conv |F|7 |Convert|S|||||T|20";
dictrecs ^= FM ^ L"just |F|9 |Justify|S|||||L|3";
dictrecs ^= FM ^ L"length|F|10|Length |S|||||R|6";
dictrecs ^= FM ^ L"master|F|28|Master |S|||||L|1";
dictrecs ^= FM ^ L"@crt |G| |"
"type fmc part title sm conv just length master"
" by type by fmc by part by @id";
//write the dictionary records to the dictionary
var nrecs=dictrecs.dcount(FM);
for (var recn = 1; recn <= nrecs; recn++) {
var dictrec=dictrecs.a(recn);
while (dictrec.index(L" |"))
dictrec.swapper(L" |","|");
var key=field(dictrec,"|",1);
var rec=field(dictrec,"|",2,9999);
if (key.a(1)=="F")
rec.r(28,0,0,1);//master
//printl(key ^ L": " ^ rec);
write(rec.convert(L"|",FM), dictmd, key);
}
}
}
////////
//init1:
////////
var thcolor = SYSTEM.a(46, 1);
var tdcolor = SYSTEM.a(46, 2);
var reportfont = SYSTEM.a(46, 3);
if (not tdcolor)
tdcolor = L"#FFFFC0";
if (not thcolor)
thcolor = L"#FFFF80";
if (sentencex.index(L" det-supp", 1))
detsupp = 1;
if (sentencex.index(L" det-supp2", 1))
detsupp = 2;
if (not open(L"dict_md", dictmd))
//stop(L"Cannot open dict_md");
dictmd="";
//initphrase:
/////////////
var ss = L"";
wordn = 0;
///////////
nextphrase:
///////////
gosub getword();
if (word eq L"")
goto x1exit;
phraseinit:
///////////
if (word.substr(1, 4) eq L"sort" or word.substr(1, 4) eq L"list") {
if (word.index(L"sort"))
ss ^= L"s";
ss ^= L"select";
//filename:
gosub getword();
if (not word)
abort(L"FILE NAME IS REQUIRED");
//limit number of records
if (word.match(L"\\d+","r")) {
maxnrecs = word;
ss ^= L" " ^ maxnrecs;
gosub getword();
}
//get the filename (or dict filename as dict_filename)
if (word eq L"dict") {
gosub getword();
word = L"dict_" ^ word;
}
filename = word;
if (not srcfile.open(filename))
abort(filename^" file does not exist");
if (filename.substr(1, 5).lcase() eq L"dict_")
dictfilename = L"md";
else
dictfilename = filename;
if (not DICT.open(L"dict_"^dictfilename)) {
dictfilename = L"dict_md";
DICT = dictmd;
}
//add the filename to the sort/select command
ss ^= L" " ^ word;
//get any specific keys (numbers or quoted words)
while (nextword ne L"" and (nextword.isnum() or nextword[1] eq SQ or nextword[1] eq DQ)) {
gosub getword();
keylist = 1;
ss ^= L" " ^ word;
}
} else if (word eq L"getlist") {
gosub getword(); //var(L"GETLIST " ^ word).perform();
perform(L"getlist "^word);
} else if (word eq L"and" or word eq L"or") {
ss ^= L" " ^ word;
} else if (word eq L"(" or word eq L")") {
ss ^= L" " ^ word;
} else if (word eq L"by" or word eq L"by-dsnd") {
ss ^= L" " ^ word;
gosub getword();
ss ^= L" " ^ word;
} else if (word eq L"with not" or word eq L"with" or word eq L"without" or word eq L"limit") {
ss ^= L" " ^ word;
var limit = word eq L"limit";
if (limit)
nlimits += 1;
gosub getword();
//NO/EVERY
if (word eq L"not" or word eq L"no" or word eq L"every") {
ss ^= L" " ^ word;
gosub getword();
}
//field or NO
ss ^= L" " ^ word;
if (limit)
limits.r(1, nlimits, word);
//negate next comparision
if (var(L"not,ne,<>").locateusing(nextword, L",", xx)) {
nextword = L"not";
gosub getword();
ss ^= L" " ^ word;
}
//comparision
if (var(L"match,eq,ne,gt,lt,ge,le,[,],[]").locateusing(nextword, L",", xx)) {
gosub getword();
ss ^= L" " ^ word;
if (limit)
limits.r(2, nlimits, word);
}
//with x between y and z
//with x from y to z
if (nextword eq L"between" or nextword eq L"from") {
gosub getword();
ss ^= L" " ^ word;
gosub getword();
ss ^= L" " ^ word;
gosub getword();
ss ^= L" " ^ word;
gosub getword();
ss ^= L" " ^ word;
} else {
//parameters
while (true) {
///BREAK;
if (not (nextword ne L"" and (nextword.isnum() or nextword[1] eq DQ or nextword[1] eq SQ)))
break;
gosub getword();
ss ^= L" " ^ word;
if (limit) {
word.unquoter();
if (word eq L"")
word = L"\"\"";
//append a subvalue
limits.r(3, nlimits, -1, word);
}
}//loop;
}
} else if (word eq L"break-on") {
breakcolns.splicer(1, 0, (coln + 1) ^ FM);
breakoptions.splicer(1, 0, FM);
nbreaks += 1;
breakonflag = 1;
} else if (word eq L"grand-total") {
//zzz throw away the grand total options for the time being
gosub getword();
gtotreq = 1;
} else if (word eq L"no-base") {
nobase = 1;
//"DET-SUPP"
} else if (word eq L"det-supp") {
detsupp = 1;
//"DET-SUPP"
} else if (word eq L"det-supp2") {
detsupp = 2;
//"GTOT-SUPP"
} else if (word eq L"gtot-supp") {
gtotsupp = 1;
//case dictrec
} else if (word eq L"total") {
totalflag = 1;
} else if (word eq L"using") {
gosub getword();
dictfilename = word;
if (not DICT.open(L"dict_"^dictfilename)) {
fsmsg();
abort(L"");
}
} else if (word eq L"heading") {
gosub getword();
head = word;
if (html) {
head.swapper(L"Page \'P\'", L"");
head.swapper(L"Page \'P", SQ);
}
head.splicer(1, 1, L"");
head.splicer(-1, 1, L"");
} else if (word eq L"footing") {
gosub getword();
foot = word;
foot.splicer(1, 1, L"");
foot.splicer(-1, 1, L"");
//justlen
} else if (word eq L"justlen") {
if (not coln) {
mssg(L"justlen/jl must follow a column name");
abort(L"");
}
gosub getword();
word.splicer(1, 1, L"");
word.splicer(-1, 1, L"");
coldict(int(coln)).r(9, word[1]);
coldict(coln).r(10, word[3]);
coldict(coln).r(11, word);
//colhead
} else if (word eq L"colhead") {
gosub getword();
//skip if detsupp2 and column is being skipped
if (coldict(coln).assigned()) {
word.unquoter();
word.converter(L"|", VM);
coldict(coln).r(3, word);
}
} else if (word eq L"oconv") {
gosub getword();
word.splicer(1, 1, L"");
word.splicer(-1, 1, L"");
if (html)
word.swapper(L"[DATE]", L"[DATE,*]");
coldict(coln).r(7, word);
} else if (word eq L"id-supp") {
idsupp = 1;
} else if (word eq L"dbl-spc") {
dblspc = 1;
} else if (dictrec) {
if (var(L"FSDIA").index(dictrec.a(1), 1)) {
var nn;
//pick items
if (var(L"DI").index(dictrec.a(1), 1))
dicti2a(dictrec);
//pick A equ F
if (dictrec.a(1) eq L"A")
dictrec.r(1, L"F");
//suppress untotalled columns if doing detsupp2
if (detsupp eq 2) {
//if (var(L"JL,JUSTLEN,CH,COL,HEAD,OC,OCONV").locateusing(nextword, L",", xx)) {
if (var(L"justlen,colhead,oconv").locateusing(nextword, L",", xx)) {
gosub getword();
gosub getword();
}
if (not (totalflag or breakonflag))
goto dictrecexit;
}
coln += 1;
colname(coln) = word;
//increase column width if column title needs it
nn = (dictrec.a(3)).dcount(VM);
for (var ii = 1; ii <= nn; ii++) {
tt = dictrec.a(3, ii);
var f10=dictrec.a(10);
if (f10=="" or (f10 and tt.length() > f10))
dictrec.r(10, tt.length());
};//ii;
if (detsupp < 2) {
if (not (totalflag or breakonflag)) {
tt = L" id=\"BHEAD\"";
if (detsupp)
tt ^= L" style=\"display:none\"";
dictrec.r(14, tt);
}
}
//total required ?
if (totalflag) {
totalflag = 0;
dictrec.r(12, 1);
anytotals = 1;
} else
dictrec.r(12, 0);
if (html) {
tt = dictrec.a(7);
tt.swapper(L"[DATE]", L"[DATE,*]");
if (tt eq L"[DATE,4]")
tt = L"[DATE,4*]";
dictrec.r(7, tt);
if (tt eq L"[DATE,*]")
dictrec.r(9, L"R");
}
coldict(coln) = dictrec;
//store the format in a convenient place
if (html)
tt = L"";
else {
tt = coldict(coln).a(9);
if (tt)
tt ^= L"#" ^ coldict(coln).a(10);
}
coldict(coln).r(11, tt);
//this could be a break-on column and have break-on options
//if coln=breakcolns<1> then
if (breakonflag) {
coldict(coln).r(13, 1);
breakonflag = 0;
if (nextword[1] eq DQ) {
gosub getword();
//zzz break options
if (word.index(L"B", 1))
pagebreakcoln = coln;
breakoptions.r(1, word);
}
}
}
} else if (word eq L"ignoreword") {
gosub getword();
ignorewords.r(1, -1, word);
//@LPTR word is skipped if not located in MD/DICT.MD
} else if (word eq L"@lptr" or word eq L"@crt") {
} else {
//sys.messages W156
//tt = L"\"%1%\" is an unrecognized word.Please correct the word by retyping it|or pressing (F4] to edit it.Press [Esc) to re-start.";
tt = L"\"%1%\" is an unrecognized word.";
tt.swapper(L"%1%", word);
mssg(tt, L"RCE", word, word);
//if (word eq var().chr(27))
abort(L"");
gosub getwordexit();
goto phraseinit;
}
dictrecexit:
////////////
/////////////
//phraseexit:
/////////////
goto nextphrase;
///////
x1exit:
///////
//if no columns selected then try to use default @crt or @lptr group item
//if (not (coln or crtx) and (DICT ne dictmd or datafile eq L"md" or datafile eq L"dict_md")) {
if (not (coln or crtx) and DICT) {
// and ((DICT.ucase() ne dictmd.ucase()) or (filename.ucase() eq L"MD") or (filename.ucase() eq L"DICT_MD"))) {
var words=printing ? L"@lptr,@crt" : L"@crt,@lptr";
for (int ii=1;ii<=2;++ii) {
word = words.field(L",",ii);
if (not xx.read(DICT, word)) {
//word.ucaser().outputl();
if (not xx.read(DICT, word)) {
//word.outputl("word not found:");
word = L"";
}
} //else word.outputl("word found:");
if (word) {
crtx = 1;
sentencex ^= L" " ^ word;
charn = sentencex.length() - word.length();
goto nextphrase;
}
}
}
ncols = coln;
//insert the @id column
if (not idsupp) {
ncols += 1;
//move the columns up by one to make space for a new column 1
for (int coln = ncols; coln >= 2; coln--) {
coldict(coln) = coldict(coln - 1);
colname(coln) = colname(coln - 1);
};//coln;
//set column 1 @ID
colname(1) = L"@" L"id";
if (not DICT or not coldict(1).read(DICT, L"@" L"id")) {
if (not dictmd or not coldict(1).read(dictmd, L"@" L"ID"))
coldict(1) = L"F" ^ FM ^ L"0" ^ FM ^ L"Ref" ^ FM ^ FM ^ FM ^ FM ^ FM ^ FM ^ L"L" ^ FM ^ 15;
}
if (html)
tt = L"";
else
tt = coldict(1).a(9) ^ L"#" ^ coldict(1).a(10);
coldict(1).r(11, tt);
//increment the list of breaking columns by one as well
for (var breakn = 1; breakn <= nbreaks; breakn++)
breakcolns.r(breakn, breakcolns.a(breakn) + 1);
pagebreakcoln += 1;
}
//work out column "widths". zero suppresses a column. blank or anything else allows it.
for (int coln=1; coln<=ncols; ++coln) {
var tt=coldict(coln).a(10);
if (tt eq L"")
tt="10";
wcol(coln)=tt;
}
if (breakcolns[-1] eq FM)
breakcolns.splicer(-1, 1, L"");
if (breakoptions[-1] eq FM)
breakoptions.splicer(-1, 1, L"");
//make underline and column title underline
if (not html) {
underline = L"";
colunderline = L"";
for (int coln = 1; coln <= ncols; coln++) {
if (wcol(coln)) {
if (coldict(coln).a(12)) {
tt = L"-";
} else {
tt = L" ";
}
underline ^= tt.str(wcol(coln)) ^ L" ";
colunderline ^= var(L"-").str(wcol(coln)) ^ L" ";
}
};//coln;
bar = var(L"-").str(colunderline.length() - 1);
}
////////
//init2:
////////
tx = "";
if (filename.unassigned()||not filename)
abort(L"Filename not specified");
if (not open(filename, srcfile))
abort(L"Cannot open file L" ^ filename);
//reserve breaks and set all to ""
breakcount.redim(nbreaks + 1);
breaktotal.redim(maxncols, nbreaks+1);
breakvalue.redim(maxncols);
oldbreakvalue.redim(maxncols);
breakvalue="";
oldbreakvalue="";
breakcount="";
breaktotal="";
//build the column headings
var colheading = L"";
var coltags = L"";
var coln2 = 0;
for (int coln = 1; coln <= ncols; coln++) {
//suppress drilldown if no totals or breakdown
if (not anytotals or not nbreaks)
coldict(coln).r(14, L"");
if (wcol(coln)) {
if (html) {
coln2 += 1;
//t='<th bgcolor=':thcolor
tt = L"<th ";
//if detsupp=1 then t:=coldict(coln)<14>
if (not usecols)
tt ^= coldict(coln).a(14);
tt ^= L">" ^ coldict(coln).a(3) ^ L"</th>";
colheading.r(coln2, tt);
colheading.swapper(VM, L"<br />");
coltags.r(-1, L"<col");
var align = coldict(coln).a(9);
if (align eq L"R") {
//if index(coldict(coln)<7>,'[NUMBER',1) then
// *http://www.w3.org/TR/html401/struct/tables.html#adef-align-TD
// coltags:=' align="char" char="':decimalchar:'"'
//end else
//coltags:=' align="right"'
coltags ^= L" style=\"text-align:right\"";
// end
} else if (align eq L"T")
//coltags:=' align="left"'
coltags ^= L" style=\"text-align:left\"";
if (usecols)
coltags ^= coldict(coln).a(14);
coltags ^= L" />";
} else {
for (var ii = 1; ii <= 9; ++ii)
colheading.r(ii, colheading.a(ii) ^ (coldict(coln).a(3, ii)).oconv(coldict(coln).a(11)) ^ L" ");
}
}
}
//change all "(Base)" in dictionary column headings to the base currency
//unless the keyword NO-BASE is present in which case replace with blank
//this is useful if all the columns are base and no need to see the currency
//c language family conditional assign is fairly commonly understood
//and arguably quite readable if the alternatives are simple
//compare to (if (nobase) ... " a little below
tt = html ? L"" : L"C#6";
var t2 = company.a(3);
if (t2) {
if (nobase)
t2 = L"";
else
t2 = L"(" ^ t2 ^ L")";
colheading.swapper(L"(Base)", t2.oconv(tt));
colheading.swapper(L"%BASE%", company.a(3));
}
//trim off blank lines (due to the 9 above)
if (html) {
tt = L"";
gosub getmark(L"CLIENT", html, clientmark);
tt ^= clientmark;
//tt ^= L"<table class=\"maintable\" border=\"1\" cellspacing=\"0\" cellpadding=\"2\"";
tt ^= L"<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\"";
tt ^= L" align=\"center\" ";
tt ^= L" style=\"font-size:66%;font-family:arial,sans-serif";
tt ^= L";background-color:" ^ tdcolor;
tt ^= L";page-break-after:avoid";
tt ^= L"\">";
tt ^= FM ^ L"<colgroup>" ^ coltags ^ L"</colgroup>";
tt ^= FM ^ L"<thead>";
//t:=fm:coltags
tt ^= tr ^ colheading ^ trx ^ FM ^ L"</thead>";
tt ^= FM ^ L"<tbody>";
tt.transfer(colheading);
//allow for single quotes
colheading.swapper(SQ, L"\'\'");
} else
colheading.trimmerb(L" "^FM);
//heading options
if (head eq L"")
head = filename ^ space(10) ^ L" \'T\'";
if (html) {
//
// //get the letterhead
// newpagetag='<div style="page-break-before:always">';
// call gethtml('head',letterhead,'');
// //insert the letterhead
// swap newpagetag with newpagetag:letterhead in tx;
// call readcss(css);
// swap '</head>' with crlf:field(css,char(26),1):crlf:'</head>' in tx;
// //remove the first pagebreak
// stylecode='page-break-before';
// t=index(ucase(tx),stylecode,1);
// if t then tx(t,len(stylecode))='XXX';
//
head.swapper(FM, L"<br />");
head = L"<h2~style=\"text-align:center\">" ^ head ^ L"</h2>";
}
//footing options
if (dblspc)
head ^= FM;
if (not html)
head ^= FM ^ colunderline;
head ^= FM ^ colheading;
if (not html)
head ^= FM ^ colunderline;
if (dblspc)
head ^= FM;
orighead = head;
printer1.setheadfoot(mv,head,foot);
//required before select()
begintrans();
//////////
//initrec:
//////////
var selectedok;
if (ss.count(L" ") > 2 or keylist) {
//call mssg('Selecting records, please wait.||(Press Esc or F10 to interrupt)','UB',buffer,'')
//perform ss:' (S)'
//call perf(ss:' (S)')
selectedok=filename.select(ss);
} else {
if (LISTACTIVE)
selectedok=true;
else
selectedok=srcfile.select(ss);
}
if (not selectedok) {
call mssg(L"No records found");
abort(L"");
/*
if (html)
tx ^= L"</tbody></table>";
tx ^= L"No records listed";
printer1.printtx(mv,tx);
*/
} else {
recn = L"";
lastid = L"%EXODUS_%%%%%_NONE%";
gosub process_all_records();
}
//x2bexit:
//////////
//remove while no header being output
if (html)
tx ^= L"</tbody></table></div></body></html>";
printer1.printtx(mv, tx);
printer1.close(mv);
return 0;
}
//////////////////////////////
subroutine process_all_records()
//////////////////////////////
{
//returns true if completes or false if interrupted
while (true) {
if (esctoexit()) {
tx = L"";
if (html)
tx ^= L"</tbody></table>";
tx ^= L"*** incomplete - interrupted ***";
printer1.printtx(mv,tx);
clearselect();
//goto x2bexit;
return;
}
//limit number of records (allow one more to avoid double closing since nrecs limited in select clause as well
if (maxnrecs and recn >= (maxnrecs+1))
filename.clearselect();
//readnext key
FILEERRORMODE = 1;
FILEERROR = L"";
if (not filename.readnext(ID, MV)) {
FILEERRORMODE = 0;
/* treat all errors as just "no more records"
if (_STATUS) {
tx = L"*** Fatal Error " ^ FILEERROR.a(1) ^ L" reading record " ^ ID ^ L" ***";
printer1.printtx(mv,tx);
abort(L"");
}
if (FILEERROR.a(1) eq 421) {
tx = L"Operation aborted by user.";
printer1.printtx(mv,tx);
abort(L"");
}
if (FILEERROR and FILEERROR.a(1) ne 111) {
tx = L"*** Error " ^ FILEERROR.a(1) ^ L" reading record " ^ ID ^ L" ***";
printer1.printtx(mv,tx);
readerr += 1;
abort(L"");
}
*/
return;
}
//skip record keys starting with "%" (control records)
if (ID[1] eq L"%")
continue;
//read the actual record (TODO sb modify select statement to return the actual columns required)
//or skip if disappeared
if (not RECORD.read(srcfile, ID))
continue;
//designed to filter multivalues which are not selected properly
//unless sorted "by"
if (limits) {
var nfns = RECORD.dcount(FM);
//find maximum var number
var nvars = 1;
for (var fn = 1; fn <= nfns; fn++) {
temp = RECORD.a(fn);
if (temp.length()) {
temp = temp.dcount(VM);
if (temp > nvars)
nvars = temp;
}
};//fn;
//for each limit pass through record deleting all unwanted multivalues
for (var limitn = 1; limitn <= nlimits; limitn++) {
//calculate() accesses data via dictionary keys
var limitvals = calculate(var(limits.a(1, limitn)));
for (var varx = nvars; varx >= 1; varx--) {
temp = limitvals.a(1, varx);
if (temp eq L"")
temp = L"\"\"";
//locate temp in (limits<3,limitn>)<1,1> using sm setting x else
if (not limits.a(3, limitn).locateusing(temp, SVM, xx)) {
for (var fn = 1; fn <= nfns; fn++) {
var varalues = RECORD.a(fn);
if (varalues.count(VM))
RECORD.eraser(fn, varx, 0);
};//fn;
}
};//varx;
};//limitn;
}
recn += 1;
//process/output one record
gosub process_one_record();
}//readnext
//print the closing subtotals
breakleveln = nbreaks;
if (not gtotsupp and (not pagebreakcoln or gtotreq))
breakleveln += 1;
gosub printbreaks();
bodyln = 1;
if (html)
tx ^= L"<p style=\"text-align:center\">";
tx ^= FM ^ (recn + 0) ^ L" record";
if (recn ne 1)
tx ^= L"s";
if (html)
tx ^= L"</p>";
if (not detsupp)
tx ^= L"<script type=\"text/javascript\"><!--" ^ FM ^ L" togglendisplayed+=" ^ nblocks ^ FM ^ L"--></script>";
return;
}
///////////////////////////////
subroutine process_one_record()
///////////////////////////////
{
//visible progress indicator
//var().getcursor();
//if (not SYSTEM.a(33)) {
// print(AW.a(30), var().cursor(36, CRTHIGH / 2));
//}else{
// print(var().cursor(0));
//}
//print(recn, L" ");
//cursor.setcursor();
var fieldno;
var keypart;
var cell;
//get the data from the record into an array of columns
for (int coln = 1; coln <= ncols; coln++) {
//dont call calculate except for S items because some F items
//are constructed and/or exist in dict_md
dictrec=coldict(coln);
if (dictrec.a(1) eq L"F") {
fieldno=dictrec.a(2);
if (not fieldno) {
cell=ID;
keypart=dictrec.a(5);
if (keypart)
cell=cell.field(L'*',keypart);
} else {
if (dictrec.a(4)[1] eq L"M")
cell=RECORD.a(fieldno,MV);
else
cell=RECORD.a(fieldno);
}
//calculate() accesses data via dictionary keys
} else
cell=calculate(colname(coln));
if (not html and dictrec.a(9) == L"T")
mcol(coln)=cell.oconv(dictrec.a(11));
else
mcol(coln)=cell;
if (html)
mcol(coln).swapper(TM, L"<br />");
pcol(coln) = 1;
ccol(coln) = 7;
scol(coln) = mcol(coln);
}//coln;
//break subtotals
//detect most major level to break
if (recn eq 1) {
//print breaks will not actually print before the first record
// but it needs to set the various break values
breakleveln = nbreaks;
} else {
int coln;
int leveln;//used after loop so cant declare in the "for" statement
for (leveln = nbreaks; leveln >= 1; leveln--) {
coln = breakcolns.a(leveln);
///BREAK;
if (scol(coln) ne breakvalue(coln))
break;
};//leveln;
breakleveln = leveln;
}
gosub printbreaks();
//oldbreakvalue.init(breakvalue);
oldbreakvalue=breakvalue;
previousmarklevel = 0;
while (true) {
//remove appropriate value from multi-valued column(s)
newmarklevel = 0;
for (int coln = 1; coln <= ncols; coln++) {
if (ccol(coln) >= previousmarklevel) {
//"remove" is a rarely used pick function that extracts text from a given character
//number up to the next pick field, value, subvalue or other separator character.
//It doesnt actually "remove" any text but it does also move the pointer up
//ready for the next extraction and tells you what the next separator character is
icol(coln)=mcol(coln).remove(pcol(coln), ccol(coln));
scol(coln) = icol(coln);
}
if (ccol(coln) > newmarklevel)
newmarklevel = ccol(coln);
};//coln;
//break totals - add at the bottom level (1)
for (int coln = 1; coln <= ncols; coln++) {
//only totalled columns
if (coldict(coln).a(12)) {
if (icol(coln)) {
if (html) {
//breaktotal(coln,1)+=i.col(coln)
addunits(icol(coln), breaktotal(coln,1));
} else {
if ((breaktotal(coln,1)).isnum() and (icol(coln)).isnum()) {
breaktotal(coln,1) += icol(coln);
} else {
if (colname(coln) eq L"DATEGRID") {
str1 = icol(coln);
str2 = breaktotal(coln,1);
gosub addstr();
breaktotal(coln,1) = str3;
}
}
}
}
breakcount(1) += 1;
icol(coln) = L"";
}
};//coln;
if (detsupp < 2) {
if (anytotals and not blockn) {
nblocks += 1;
blockn = nblocks;
//tx:='<span style="display:none" id="B':blockn:'">'
tx ^= FM;
}
//print one row of text
//html rows can be hidden until subtotal is is clicked
if (html) {
tx ^= L"<tr";
if (blockn) {
if (detsupp eq 1)
tx ^= L" style=\"display:none\"";
tx ^= L" id=\"B" ^ blockn ^ DQ;
//clicking expanded det-supped details collapses it
if (detsupp)
tx ^= L" style=\"cursor:pointer\" onclick=\"toggle(B" ^ blockn ^ L")\"";
}
tx ^= L">";
}
//output the columns
for (int coln = 1; coln <= ncols; coln++) {
tt = scol(coln);
//oconv
var oconvx = coldict(coln).a(7);
if (oconvx) {
tt = tt.oconv(oconvx);
//prevent html folding of numbers on minus sign
if (html) {
if (tt[1] eq L"-") {
if (oconvx.substr(1, 7) eq L"[NUMBER")
tt = L"<nobr>" ^ tt ^ L"</nobr>";
}
}
}
//non-zero width columns
if (wcol(coln)) {
//non-html format to fixed with with spaces
if (not html)
tt = tt.oconv(coldict(coln).a(11));
//html blank is nbsp
if (tt eq L"")
tt = nbsp;
//add one column
tx ^= td ^ tt ^ tdx;
}
};//coln;
//terminate the row and output it
//tx ^= trx;
printer1.printtx(mv,tx);
//loop back if any multivalued lines/folded text
if (newmarklevel) {
for (int coln = 1; coln <= ncols; coln++)
scol(coln) = L"";
previousmarklevel = newmarklevel;
continue;
}
//double space
if (dblspc)
printer1.printtx(mv,tx);
}//detsupp < 2
break;
}//loop while folding text or multivalued lines
return;
}
////////////////////
subroutine getword()
////////////////////
{
while (true) {
gosub getword2();
if (word.length() and ignorewords.locateusing(word, VM)) {
continue;
}
break;
}
if (word eq L"") {
nextword = L"";
} else {
var storewordn = wordn;
var storecharn = charn;
var storeword = word;
var storedictrec = dictrec;
gosub getword2();
nextword = word;
word = storeword;
dictrec = storedictrec;
wordn = storewordn;
charn = storecharn;
}
// call note(quote(word):' ':quote(nextword))
//if (not quotes.index(word[1]))
// word.ucaser();
//if (not quotes.index(nextword[1]))
// nextword.ucaser();
return;
}
/////////////////////
subroutine getword2()
/////////////////////
{
while (true) {
/////////
wordn += 1;
if (wordn eq 1)
charn = 0;
// call note(wordn:' ':charn)
word = L"";
charn += 1;
while (true) {
///BREAK;
if (sentencex[charn] ne L" ")
break;
charn += 1;
if (charn > sentencex.length())
return;
}//loop;
startcharn = charn;
var charx = sentencex[charn];
if (quotes.index(charx, 1)) {
searchchar = charx;
} else {
searchchar = L" ";
}
word ^= charx;
while (true) {
charn += 1;
charx = sentencex[charn];
///BREAK;
if (charx eq L"" or charx eq searchchar)
break;
word ^= charx;
}
if (searchchar ne L" ") {
word ^= searchchar;
charn += 1;
} else {
//word.ucaser();
word.trimmerf().trimmerb();
}
//options
if (word[1] eq L"(" and word[-1] eq L")") {
var commandoptions = word;
continue;
}
break;
}
gosub getwordexit();
}
////////////////////////
subroutine getwordexit()
////////////////////////
{
//standardise
if (DICT ne L"" and dictrec.read(DICT, word)) {
if (dictrec.a(1) eq L"G") {
tt = dictrec.a(3);
tt.converter(VM, L" ");
sentencex.splicer(startcharn, word.length(), tt);
charn = startcharn - 1;
wordn -= 1;
//goto getword2;
gosub getword2();
return;
}
} else {
dictrec = L"";
if (dictmd and dictrec.read(dictmd, word)) {
if (dictrec.a(1) eq L"RLIST") {
if (dictrec.a(4))
word = dictrec.a(4);
dictrec = L"";
}
}
}
dictrec.converter(L"|", VM);
if (word eq L"=")
word = L"EQ";
else if (word eq L"EQUAL")
word = L"EQ";
else if (word eq L"<>")
word = L"NE";
else if (word eq L">")
word = L"GT";
else if (word eq L"<")
word = L"LT";
else if (word eq L">=")
word = L"GE";
else if (word eq L"<=")
word = L"LE";
/*
if (word eq L"CONTAINING")
word = L"()";
if (word eq L"ENDING")
word = L"[";
if (word eq L"STARTING")
word = L"]";
*/
return;
}
////////////////////////
subroutine printbreaks()
////////////////////////
{
if (not breakleveln)
return;
var newhead = L"";
//print breaks from minor level (1) up to required level
//required level can be nbreaks+1 (ie the grand total)
//for leveln=1 to breakleveln
//for leveln=breakleveln to 1 step -1
for (var leveln = 1; leveln <= breakleveln; leveln++) {
var breakcoln = breakcolns.a(leveln);
var storetx = tx;
//output any prior tx is this level is suppressed
//if index(breakoptions<leveln>,'X',1) and tx then
// if recn>1 then gosub printtx
// end
var lastblockn = blockn;
blockn = 0;
if (detsupp) {
if (tx and tx[-1] ne FM)
tx ^= FM;
if (leveln > 1 and not html)
tx ^= underline ^ FM;
} else {
if (not html) {
//underline2=if breakleveln>=nbreaks then bar else underline
underline2 = (leveln eq 1) ? (underline) : (bar);
if (not tx.substr(-2, 2).index(L"-", 1)) {
if (tx[-1] ne FM)
tx ^= FM;
tx ^= underline2;
}
}
tx ^= FM;
}
//print one row of totals
if (html) {
tx ^= tr;
if (lastblockn)
tx ^= L" style=\"cursor:pointer\" onclick=\"toggle(B" ^ lastblockn ^ L")\"";
if (detsupp < 2 or (nbreaks > 1 and leveln > 1))
tx ^= L" style=\"font-weight:bold\"";
tx ^= L">";
}
for (int coln = 1; coln <= ncols; coln++) {
//total column
if (coldict(coln).a(12)) {
cell = breaktotal(coln,leveln);
//add into the higher level
if (leveln <= nbreaks) {
if (cell) {
if (html) {
//breaktotal(coln,leveln+1)+=cell
gosub addunits(cell, breaktotal(coln,leveln + 1));
} else {
if ((breaktotal(coln,leveln + 1)).isnum() and cell.isnum()) {
breaktotal(coln,leveln + 1) += cell;
} else {
str1 = cell;
str2 = breaktotal(coln,leveln + 1);
gosub addstr();
breaktotal(coln,leveln + 1) = str3;
}
}
}
breakcount(leveln + 1) += breakcount(leveln);
}
//format it
var oconvx = coldict(coln).a(7);
if (oconvx)
cell = cell.oconv(oconvx);
if (html) {
if (cell eq L"")
cell = nbsp;
else
cell.swapper(VM, L"<br />");
}
//and clear it
breaktotal(coln,leveln) = L"";
//break column
} else if (coln eq breakcoln) {
//print the old break value
cell = breakvalue(coln);
var oconvx = coldict(coln).a(7);
if (oconvx)
cell = cell.oconv(oconvx);
//store the new break value
breakvalue(coln) = scol(coln);
if (coln eq pagebreakcoln) {
newhead = orighead;
temp = scol(coln);
if (oconvx)
temp = temp.oconv(oconvx);
temp.swapper(SQ, L"\'\'");
newhead.swapper(L"\'B\'", temp);
}
if (detsupp < 2 and not anytotals)
cell = L" ";
//other columns are blank
} else {
cell = L"";
if (1 or detsupp < 2) {
cell = oldbreakvalue(coln);
if (breakcolns.locateusing(coln, FM, colbreakn)) {
if (colbreakn < leveln)
cell = L"Total";
}
}
}
if (wcol(coln)) {
if (not html) {
cell = cell.substr(1, wcol(coln));
cell = cell.oconv(coldict(coln).a(11));
tx ^= cell ^ tdx;
} else {
tx ^= L"<td";
if (not usecols)
tx ^= coldict(coln).a(14);
if (coldict(coln).a(9) eq L"R")
tx ^= L" style=\"text-align:right\"";
tx ^= L">";
tx ^= cell ^ tdx;
}
}
};//coln;
//breakrowexit:
if (html)
tx ^= trx;
if (detsupp < 2) {
if (leveln > 1 and not html)
tx ^= FM ^ underline;
} else {
if (not html)
tx ^= FM ^ underline2;
}
//option to suppress the current level
//or if this is the first record cannot be any totals before it.
if ((breakoptions.a(leveln)).index(L"X", 1) or recn eq 1)
tx = storetx;
};//leveln;
//force new page and new heading
//if newhead and detsupp<2 then
//if newhead then
// head=newhead
// bodyln=999
// end
//if recn>1 then
//if only one record found then avoid skipping printing totals for det-supp
if (detsupp < 2 or recn > 1) {
if (not html) {
if (not anytotals)
tx = bar;
}
if (newhead and html and tx)
tx ^= L"</tbody></table>";
if (tx)
printer1.printtx(mv,tx);
} else {
tx = L"";
}
//force new page and new heading
//if newhead and detsupp<2 then
if (newhead) {
head = newhead;
bodyln = 999999;
}
return;
}
///////////////////
subroutine addstr()
///////////////////
{
str3 = str2;
if (str3.length() < str1.length())
str3 ^= space(str1.length() - str2.length());
for (var ii = 1; ii <= str1.length(); ii++) {
var char1 = str1[ii].trim();
if (char1 ne L"") {
var char2 = str3[ii];
if (char2 eq L" ") {
str3.splicer(ii, 1, char1);
} else {
//if num(char1) else char1=1
//if num(char2) else char2=1
if (char1.isnum() and char2.isnum()) {
char3 = char1 + char2;
if (char3 > 9)
char3 = L"*";
} else
char3 = char1;
str3.splicer(ii, 1, char3);
}
}
};//ii;
return;
}
//following are stubs to old external functions that may or may not be reimplemented in exodus.
subroutine getmark(in mode, in html, out mark)
{
mark="";
return;
//prevent "warning unused" until properly implemented
if (mode or html){};
}
subroutine addunits(in newunits, out totunits)
{
return;
//prevent "warning unused" until properly implemented
if (newunits or totunits){};
}
subroutine dicti2a(out dictrec)
{
return;
}
function esctoexit()
{
return false;
}
//all exodus programs need to finish up with "programexit"
//in MV terms, this simply corresponds to the final END statement of a program except that it is mandatory.
//in OO terms, this
//1. defines a contructor that sets up the "mv" exodus global variable that provides RECORD etc.
//2. closes the class that programinit opened
//3. sets up the required global main() function that will instantiate the class run its main() function
//debugprogramexit()
programexit()
|
545f992fcbe4ffee7b263e2627d834bb633ab1cb | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /CodesNew/4167.cpp | d3948e7eb405adf5c761700ea632cbdb9b8b261e | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 983 | cpp | 4167.cpp | #include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define pii pair<int,int>
#define pll pair<ll,ll>
#define fo(i,a,b) for(ll i=a;i<b;i++)
#define fo_(i,a,b) for(ll i=a;i>b;i--)
#define M(a) memset(a,0,sizeof a)
#define M_(a) memset(a ,-1,sizeof a)
#define pb push_back
#define PI 3.14159265
#define nmax 200100
const ll inf = 9999999999;
using namespace std;
ll a[nmax],k[nmax],acc[nmax];
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n,q;
cin >> n >> q;
fo(i,0,n) cin >> a[i];
fo(i,0,q) cin >> k[i];
acc[0] = a[0];
fo(i,1,n) acc[i] = acc[i-1] + a[i];
ll last = 0;
fo(i,0,q){
last += k[i];
if (last >= acc[n-1]){
last = 0;
cout << n << endl;
continue;
}
int pl = upper_bound(acc,acc+n,last)-acc;
cout << n-pl << endl;
}
return 0;
}
|
acf34b871980d0a2511bcc3169b401572a6682a6 | d225fe9be015f259e83309bf59cfab11fed4db9d | /src/dll/mono_api.inl | 5aa734ed90816990aa18df77d9df79ad2140dbab | [] | no_license | juntalis/uniject | ccf9edef17c7d9bd130b1f44b80dfdb37c8c0f49 | 7f3cef728798b1266e7afb450c5c1fa262374da9 | refs/heads/master | 2021-06-08T20:20:56.921603 | 2021-04-10T07:12:21 | 2021-04-10T07:12:21 | 157,262,626 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | inl | mono_api.inl | /**
* Included multiple times with different implementations of MONO_API.
*/
#ifndef MONO_API
#error MONO_API must be defined prior to including mono_api.inl!
#endif
MONO_API(void, mono_trace_set_level_string, const char*level)
MONO_API(void, mono_trace_set_mask_string, const char *mask)
MONO_API(void, mono_set_commandline_arguments, int, const char* argv[], const char*)
MONO_API(void, mono_jit_parse_options, int argc, char* argv[])
MONO_API(void, mono_debug_init, int format)
MONO_API(MonoDomain*, mono_get_root_domain, void)
MONO_API(MonoThread*, mono_thread_attach, MonoDomain*)
MONO_API(MonoThread*, mono_thread_current, void)
MONO_API(void, mono_thread_detach, MonoThread*)
MONO_API(MonoAssembly*, mono_domain_assembly_open, MonoDomain*, const char*)
MONO_API(MonoImage*, mono_assembly_get_image, MonoAssembly*)
MONO_API(MonoMethodDesc*, mono_method_desc_new, const char*, gboolean)
MONO_API(MonoMethod*, mono_method_desc_search_in_image, MonoMethodDesc*, MonoImage*)
MONO_API(void, mono_method_desc_free, MonoMethodDesc*)
MONO_API(MonoObject*, mono_runtime_invoke, MonoMethod*, void*, void**, MonoObject**)
/** Save us some lines in the including file */
#undef MONO_API
|
b45a8ed694b6058815bbaad042d3691eb1fbb1e3 | 29769bfa865b0c2ccdd7c958116d84c4e2e55130 | /day19/part1.cpp | 4bc52a06411702b2abdd8ab8a506e8a2493516cc | [] | no_license | CJosephides/AOC2020 | a39752fd4858fe1df62f6552154cc3d472c8f9dd | 4b0b83ff0e5cdab57e98435241ba32247bb214e8 | refs/heads/master | 2023-08-13T07:04:11.603605 | 2021-09-26T00:29:49 | 2021-09-26T00:29:49 | 390,152,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,821 | cpp | part1.cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <unordered_map>
#include <cctype>
class Rule {
public:
int number;
std::vector<std::vector<int>> children_set;
char emits;
public:
Rule(int number, std::vector<std::vector<int>> children_set, char emits)
: number(number), children_set(children_set), emits(emits) {};
Rule(int number, char emits)
: number(number), emits(emits), children_set({}) {};
Rule(int number, std::vector<std::vector<int>> children_set)
: number(number), children_set(children_set), emits(0) {};
Rule() {};
friend std::ostream& operator<<(std::ostream&, Rule);
};
std::ostream& operator<<(std::ostream& os, Rule rule) {
os << rule.number << ": ";
if (rule.children_set.empty())
os << rule.emits;
else {
for (auto children : rule.children_set) {
for (auto child : children) {
os << child << " ";
}
os << "| ";
}
}
return os;
}
class Ruleset {
public:
std::unordered_map<int, Rule> rules;
public:
Ruleset(std::ifstream& fs) {
// Create Ruleset from a file of rules.
std::string line;
while (std::getline(fs, line)) {
if (isdigit(line[0])) {
// We have a rule.
Rule rule = rule_from_line(line);
rules[rule.number] = rule;
} else
break; // reached end of rules (assuming all rules come before any messages
}
}
Ruleset() {}
private:
Rule rule_from_line(std::string line) {
int number;
char emits;
size_t index;
// Get the rule number.
index = line.find(':');
number = std::stoi(line.substr(0, index));
// Start reading children or emitted character.
index += 1;
while (line[index] == ' ') index++;
// Check if this rule simply emits a char.
if (line[index] == '"') {
emits = line[index+1]; // assume single emitted char
return Rule(number, emits);
}
// Otherwise, rule has children.
std::vector<std::vector<int>> children_set;
std::vector<int> children;
int child_number;
size_t n_chars;
char c;
while (index < line.size()) {
c = line[index];
if (c == ' ') {
// Nothing to do here.
index++;
} else if (isdigit(c)) {
// Read until next whitespace.
n_chars = 1;
while (index + n_chars < line.size()) {
if (line[index + n_chars] == ' ') break;
n_chars++;
}
child_number = std::stoi(line.substr(index, n_chars));
// Add this child to the current vector of children.
children.push_back(child_number);
// Increment index to one past the child number.
index += n_chars;
continue;
} else if (c == '|') {
// Start a new vector of children and save the current one into the set of children.
children_set.push_back(children);
children.clear();
index++;
}
}
// Push the final children to the set of children.
children_set.push_back(children);
// Done reading children.
return Rule(number, children_set);
}
private:
std::vector<size_t> check_rule(int rule_number, const std::string& message, std::vector<size_t> positions) {
// Checks if a rule, with number rule_number, is satisfied with the message at various index positions.
// Returns a vector of new positions for future checks.
//
Rule rule = rules[rule_number];
if (rule.children_set.empty()) {
// Rule has no children, so check if it emits the correct character from each position.
std::vector<size_t> new_positions;
for (auto position : positions) {
if (rule.emits == message[position]) {
new_positions.push_back(position + 1);
}
}
return new_positions;
}
// Otherwise the rule has at least one set of children. We want to check each sequence of children and
// combine the valid positions from each to return to our caller.
std::vector<size_t> combined_positions;
for (auto children : rule.children_set) {
// This is the same as the above single-sequence case.
std::vector<size_t> tmp_positions = positions;
for (auto child_number : children) {
tmp_positions = check_rule(child_number, message, tmp_positions);
}
// Copy any valid positions.
for (auto position : tmp_positions) combined_positions.push_back(position);
}
return combined_positions;
}
public:
bool is_valid_message(const std::string& message) {
// Checks if a message is valid given the ruleset, starting with rule 0 (at position 0).
std::vector<size_t> initial_positions = {0};
std::vector<size_t> final_positions;
final_positions = check_rule(0, message, initial_positions);
// Check if any final position has reached the end (one past) of the message.
for (auto fp : final_positions) {
if (fp == message.size()) return true;
}
return false;
}
};
int main(int argc, char** argv) {
std::ifstream fs(argv[1]);
std::string line;
Ruleset ruleset(fs);;
std::cout << "Ruleset" << std::endl;
std::cout << "=======" << std::endl;
for (auto [number, rule] : ruleset.rules) {
std::cout << rule << std::endl;
}
std::cout << "=======" << std::endl;
int n_matches = 0;
while (std::getline(fs, line)) {
if (line.empty()) continue;
std::cout << line << " : ";
if (ruleset.is_valid_message(line)) {
std::cout << "is valid!";
n_matches++;
}
else
std::cout << "not valid.";
std::cout << std::endl;
}
std::cout << n_matches << " valid messages." << std::endl;
}
|
5aee4e45d989b8190fa7fbabb3f93a45255aa1a2 | c19e0fad02849a09cb0e8a74b6481db2d7c285f0 | /Intel-Computer-Vision-SDK/TASS-PVL/Windows/Webcam/ConsoleApp/TASS-PVL-Windows-Console/TASS-PVL-Windows-Console.cpp | 8bab707f6d743e203b753359bd0feabafdc2bfa8 | [] | no_license | iotJumpway/Intel-Examples | dbc203dd73ba8bc085ac708c29a4cba227fbf52f | 6c557721f993545a30cc4b4edd116bc3d7429677 | refs/heads/master | 2021-09-18T13:01:30.904426 | 2018-07-14T11:21:07 | 2018-07-14T11:21:07 | 79,503,274 | 37 | 24 | null | null | null | null | UTF-8 | C++ | false | false | 19,910 | cpp | TASS-PVL-Windows-Console.cpp | /*
* Copyright 2016 Intel Corporation.
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*/
/*
* TASS-PVL WINDOWS WEBCAM CONSOLE APP
*
* Developed by Adam Milton-Barker
* TechBubble Technologies
* https://eu.techbubbletechnologies.com
*
* IoT Connectivity Powered By IoT JumpWay
* https://iot.techbubbletechnologies.com
*
*/
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/pvl.hpp"
#include "MQTTAsync.h"
#include "nlohmann/json.hpp"
using namespace cv;
using namespace std;
using namespace cv::pvl;
using json = nlohmann::json;
#define QOS 1
#define TIMEOUT 10000L
std::string IntelliLanMQTT = "ssl://iot.techbubbletechnologies.com:8883";
int IntelliLanLocation = 0;
int IntelliLanZone = 0;
int IntelliLanDevice = 0;
int IntelliLanSensor = 0;
std::string IntelliLanDeviceN = "YourIoTJumpWayDeviceNameHere";
std::string IntelliLanDeviceU = "YourIoTJumpWayDeviceUsernameHere";
std::string IntelliLanDeviceP = "YourIoTJumpWayDevicePasswordHere";
std::string knownDB = "known.xml";
int timeBetweenAPICalls = 0.5 * 60;
time_t lastTimeOfKnownAPICall = time(NULL);
time_t lastTimeOfUnknownAPICall = time(NULL);
int camera = 1;
int disc_finished = 0;
int subscribed = 0;
int finished = 0;
bool bRegist = false;
bool readScreen = false;
int userFaceID = 0;
volatile MQTTAsync_token deliveredtoken;
void processFrames();
bool displayAndNotify(
MQTTAsync client,
Mat& img,
const std::vector<Face>& faces,
const std::vector<int>& personIDs,
const std::vector<int>& confidence,
double elapsed
);
void drawSmile(
cv::Mat& image,
std::vector<cv::pvl::Face>& results
);
void publishToDeviceSensors(
MQTTAsync client,
int person,
int confidence
);
void publishToDeviceWarnings(
MQTTAsync client,
int person,
int confidence,
std::string value
);
std::vector<std::string> explode(const std::string &delimiter, const std::string &str)
{
std::vector<std::string> arr;
int strleng = str.length();
int delleng = delimiter.length();
if (delleng == 0)
return arr;
int i = 0;
int k = 0;
while (i<strleng)
{
int j = 0;
while (i + j<strleng && j<delleng && str[i + j] == delimiter[j])
j++;
if (j == delleng)
{
arr.push_back(str.substr(k, i - k));
i += delleng;
k = i;
}
else
{
i++;
}
}
arr.push_back(str.substr(k, i - k));
return arr;
}
void onSubscribe(void* context, MQTTAsync_successData* response)
{
printf("Subscribe succeeded\n");
subscribed = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
printf("Subscribe failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
printf("Message Arrived", message);
return 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection from IoT JumpWay\n");
finished = 1;
}
void onSend(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message with token value %d delivery confirmed\n", response->token);
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect to IoT JumpWay failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
printf("Connected to IoT JumpWay\n");
opts.onSuccess = onSend;
opts.context = client;
pubmsg.payload = "ONLINE";
pubmsg.payloadlen = strlen("ONLINE");
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
std::stringstream IntelliLanDeviceStatusTopicS;
IntelliLanDeviceStatusTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Status";
std::string IntelliLanDeviceStatusTopic = IntelliLanDeviceStatusTopicS.str();
std::stringstream IntelliLanDeviceCommandsTopicS;
IntelliLanDeviceCommandsTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Commands";
std::string IntelliLanDeviceCommandsTopic = IntelliLanDeviceCommandsTopicS.str();
if ((rc = MQTTAsync_sendMessage(client, IntelliLanDeviceStatusTopic.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
if ((rc = MQTTAsync_subscribe(client, IntelliLanDeviceCommandsTopic.c_str(), QOS, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start subscribe, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void connlost(void *context, char *cause)
{
int rc;
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
std::stringstream IntelliLanDeviceStatusTopicS;
IntelliLanDeviceStatusTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Status";
std::string IntelliLanDeviceStatusTopic = IntelliLanDeviceStatusTopicS.str();
MQTTAsync_create(&client, IntelliLanMQTT.c_str(), IntelliLanDeviceN.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
conn_opts.username = IntelliLanDeviceU.c_str();
conn_opts.password = IntelliLanDeviceP.c_str();
conn_opts.will = &will_opts;
will_opts.topicName = IntelliLanDeviceStatusTopic.c_str();
will_opts.message = "OFFLINE";
conn_opts.ssl = &ssl_opts;
ssl_opts.enableServerCertAuth = 0;
ssl_opts.trustStore = "ca.pem";
ssl_opts.enabledCipherSuites = "TLSv1";
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
int main(int argc, char* argv[])
{
processFrames();
return 1;
}
void processFrames()
{
const char* WINDOW_NAME = "TASS PVL Windows Console App";
Ptr<FaceDetector> pvlFD;
Ptr<FaceRecognizer> pvlFR;
Mat imgIn;
Mat imgGray;
VideoCapture capture;
capture.open(camera);
if (!capture.isOpened())
{
cerr << "Error: fail to capture video." << endl;
return;
}
pvlFR = FaceRecognizer::create();
if (pvlFR.empty())
{
cerr << "Error: fail to create PVL face recognizer" << endl;
return;
}
pvlFD = FaceDetector::create();
if (pvlFD.empty())
{
cerr << "Error: fail to create PVL face detector" << endl;
return;
}
capture >> imgIn;
if (imgIn.empty())
{
cerr << "Error: no input image" << endl;
return;
}
cvtColor(imgIn, imgGray, COLOR_BGR2GRAY);
if (imgGray.empty())
{
cerr << "Error: get gray image()" << endl;
return;
}
int keyDelay = 1;
namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE);
bool bTracking = true;
pvlFD->setTrackingModeEnabled(bTracking);
pvlFR->setTrackingModeEnabled(bTracking);
std::vector<Face> faces;
std::vector<Face> validFaces;
std::vector<int> personIDs;
std::vector<int> confidence;
int64 startTick = getTickCount();
try
{
bTracking = pvlFR->isTrackingModeEnabled();
pvlFR = Algorithm::load<FaceRecognizer>(knownDB);
pvlFR->setTrackingModeEnabled(bTracking);
}
catch (...)
{
}
int rc;
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
std::stringstream IntelliLanDeviceStatusTopicS;
IntelliLanDeviceStatusTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Status";
std::string IntelliLanDeviceStatusTopic = IntelliLanDeviceStatusTopicS.str();
MQTTAsync_create(&client, IntelliLanMQTT.c_str(), IntelliLanDeviceN.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
conn_opts.username = IntelliLanDeviceU.c_str();
conn_opts.password = IntelliLanDeviceP.c_str();
conn_opts.will = &will_opts;
will_opts.topicName = IntelliLanDeviceStatusTopic.c_str();
will_opts.message = "OFFLINE";
conn_opts.ssl = &ssl_opts;
ssl_opts.enableServerCertAuth = 0;
ssl_opts.trustStore = "ca.pem";
ssl_opts.enabledCipherSuites = "TLSv1";
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
}
for (;;)
{
faces.clear();
personIDs.clear();
confidence.clear();
pvlFD->detectFaceRect(imgGray, faces);
if (faces.size() > 0)
{
validFaces.clear();
int validFaceCount = 0;
if (bTracking)
{
validFaceCount = MIN(static_cast<int>(faces.size()), pvlFR->getMaxFacesInTracking());
}
else
{
validFaceCount = faces.size();
}
for (int i = 0; i < validFaceCount; i++)
{
validFaces.push_back(faces[i]);
}
pvlFR->recognize(imgGray, validFaces, personIDs, confidence);
for (uint i = 0; i < faces.size(); ++i)
{
pvlFD->detectEye(imgGray, faces[i]);
pvlFD->detectMouth(imgGray, faces[i]);
pvlFD->detectBlink(imgGray, faces[i]);
pvlFD->detectSmile(imgGray, faces[i]);
}
for (uint i = 0; i < faces.size(); ++i)
{
const Face& face = faces[i];
Rect faceRect = face.get<Rect>(Face::FACE_RECT);
Point leftEyePos = face.get<Point>(Face::LEFT_EYE_POS);
Point rightEyePos = face.get<Point>(Face::RIGHT_EYE_POS);
Point mouthPos = face.get<Point>(Face::MOUTH_POS);
bool closingLeft = face.get<bool>(Face::CLOSING_LEFT_EYE);
bool closingRight = face.get<bool>(Face::CLOSING_RIGHT_EYE);
bool smiling = face.get<bool>(Face::SMILING);
}
if (bRegist)
{
bRegist = false;
for (uint i = 0; i < personIDs.size(); i++)
{
if (personIDs[i] == FACE_RECOGNIZER_UNKNOWN_PERSON_ID)
{
int personID = pvlFR->createNewPersonID();
pvlFR->registerFace(imgGray, validFaces[i], personID, true);
pvlFR->save(knownDB);
userFaceID = 0;
}
}
if (!bTracking)
{
pvlFR->recognize(imgGray, validFaces, personIDs, confidence);
}
}
}
double elasped = static_cast<double>(getTickCount() - startTick) / getTickFrequency();
startTick = getTickCount();
displayAndNotify(client, imgIn, faces, personIDs, confidence, elasped);
drawSmile(imgIn, faces);
imshow(WINDOW_NAME, imgIn);
char key = static_cast<char>(waitKey(keyDelay));
if (key == 'q' || key == 'Q')
{
std::cout << "Quit." << std::endl;
break;
}
else if (key == 'r' || key == 'R')
{
bRegist = true;
}
else if (key == 's' || key == 'S')
{
std::cout << "Save. " << knownDB << std::endl;
pvlFR->save(knownDB);
}
capture >> imgIn;
if (imgIn.empty()) { break; }
cvtColor(imgIn, imgGray, COLOR_BGR2GRAY);
}
destroyWindow(WINDOW_NAME);
}
static void roundedRectangle(Mat& src, const Point& topLeft, const Point& bottomRight,
const Scalar lineColor, const int thickness, const int lineType, const int cornerRadius)
{
Point p1 = topLeft;
Point p2 = Point(bottomRight.x, topLeft.y);
Point p3 = bottomRight;
Point p4 = Point(topLeft.x, bottomRight.y);
line(src, Point(p1.x + cornerRadius, p1.y), Point(p2.x - cornerRadius, p2.y), lineColor, thickness, lineType);
line(src, Point(p2.x, p2.y + cornerRadius), Point(p3.x, p3.y - cornerRadius), lineColor, thickness, lineType);
line(src, Point(p4.x + cornerRadius, p4.y), Point(p3.x - cornerRadius, p3.y), lineColor, thickness, lineType);
line(src, Point(p1.x, p1.y + cornerRadius), Point(p4.x, p4.y - cornerRadius), lineColor, thickness, lineType);
ellipse(src, p1 + Point(cornerRadius, cornerRadius), Size(cornerRadius, cornerRadius), 180.0, 0, 90, lineColor, thickness, lineType);
ellipse(src, p2 + Point(-cornerRadius, cornerRadius), Size(cornerRadius, cornerRadius), 270.0, 0, 90, lineColor, thickness, lineType);
ellipse(src, p3 + Point(-cornerRadius, -cornerRadius), Size(cornerRadius, cornerRadius), 0.0, 0, 90, lineColor, thickness, lineType);
ellipse(src, p4 + Point(cornerRadius, -cornerRadius), Size(cornerRadius, cornerRadius), 90.0, 0, 90, lineColor, thickness, lineType);
}
static void putTextCenter(InputOutputArray img, const String& text, Point& point, int fontFace,
double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8)
{
int baseline;
Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline);
Point center = point;
center.x -= (textSize.width / 2);
putText(img, text, center, fontFace, fontScale, color, thickness, lineType);
}
void drawSmile(cv::Mat& image, std::vector<cv::pvl::Face>& results)
{
for (uint i = 0; i < results.size(); i++)
{
cv::pvl::Face& r = results[i];
cv::Rect faceRect = r.get<cv::Rect>(cv::pvl::Face::FACE_RECT);
int x = faceRect.x + 5;
int y = faceRect.y + faceRect.height + 15;
std::stringstream smile(std::ios_base::app | std::ios_base::out);
smile << r.get<int>(cv::pvl::Face::SMILE_SCORE);
if (r.get<int>(cv::pvl::Face::SMILE_SCORE) >= 35)
{
cv::putText(image, "HAPPY", cv::Point(x, y + 10), cv::FONT_HERSHEY_PLAIN, 2, cv::Scalar(0, 0, 255.0));
}
}
}
void publishToDeviceSensors(
MQTTAsync client,
int person,
int confidence
)
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
opts.onSuccess = onSend;
opts.context = client;
std::stringstream IntelliLanDeviceDataS;
IntelliLanDeviceDataS << "{ \"Sensor\": \"CCTV\", \"SensorID\": " << IntelliLanSensor << ", \"SensorValue\": " << person << " }";
std::string IntelliLanDeviceData = IntelliLanDeviceDataS.str();
std::cout << IntelliLanDeviceData << std::endl;
pubmsg.payload = (char*)IntelliLanDeviceData.c_str();
pubmsg.payloadlen = IntelliLanDeviceData.size();
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
std::stringstream IntelliLanDeviceSensorsTopicS;
IntelliLanDeviceSensorsTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Sensors";
std::string IntelliLanDeviceSensorsTopic = IntelliLanDeviceSensorsTopicS.str();
std::cout << IntelliLanDeviceSensorsTopic;
if ((rc = MQTTAsync_sendMessage(client, IntelliLanDeviceSensorsTopic.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void publishToDeviceWarnings(
MQTTAsync client,
int person,
int confidence,
std::string value
)
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
std::stringstream IntelliLanDeviceDataS;
IntelliLanDeviceDataS << "{ \"WarningType\": \"CCTV\", \"WarningOrigin\": " << IntelliLanSensor << ", \"WarningValue\": \"" << value << "\", \"WarningMessage\": " << person << " }";
std::string IntelliLanDeviceData = IntelliLanDeviceDataS.str();
std::cout << IntelliLanDeviceData << std::endl;
pubmsg.payload = (char*)IntelliLanDeviceData.c_str();
pubmsg.payloadlen = IntelliLanDeviceData.size();
opts.onSuccess = onSend;
opts.context = client;
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
std::stringstream IntelliLanDeviceSensorsTopicS;
IntelliLanDeviceSensorsTopicS << IntelliLanLocation << "/Devices/" << IntelliLanZone << "/" << IntelliLanDevice << "/Warnings";
std::string IntelliLanDeviceSensorsTopic = IntelliLanDeviceSensorsTopicS.str();
std::cout << IntelliLanDeviceSensorsTopic;
if ((rc = MQTTAsync_sendMessage(client, IntelliLanDeviceSensorsTopic.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
bool displayAndNotify(MQTTAsync client, Mat& img, const std::vector<Face>& faces, const std::vector<int>& personIDs, const std::vector<int>& confidence, double elapsed)
{
const int FONT = FONT_HERSHEY_PLAIN;
const Scalar GREEN = Scalar(0, 255, 0, 255);
const Scalar BLUE = Scalar(255, 0, 0, 255);
Point pointLT, pointRB;
String string;
for (uint i = 0; i < faces.size(); i++)
{
const Face& face = faces[i];
Rect faceRect = face.get<Rect>(Face::FACE_RECT);
pointLT.x = faceRect.x;
pointLT.y = faceRect.y;
pointRB.x = faceRect.x + faceRect.width;
pointRB.y = faceRect.y + faceRect.height;
roundedRectangle(img, pointLT, pointRB, GREEN, 1, 8, 5);
if (i < personIDs.size())
{
string.clear();
if (personIDs[i] > 0)
{
string = format("Person:%d(%d)", personIDs[i], confidence[i]);
if (time(NULL) - lastTimeOfKnownAPICall >= timeBetweenAPICalls) {
publishToDeviceSensors(client, personIDs[i], confidence[i]);
publishToDeviceWarnings(client, personIDs[i], confidence[i], "Recognised");
lastTimeOfKnownAPICall = time(NULL);
}
}
else if (personIDs[i] == FACE_RECOGNIZER_UNKNOWN_PERSON_ID)
{
string = "UNKNOWN";
if (time(NULL) - lastTimeOfUnknownAPICall >= timeBetweenAPICalls) {
publishToDeviceSensors(client, 0, 0);
publishToDeviceWarnings(client, 0, 0, "Not Recognised");
lastTimeOfUnknownAPICall = time(NULL);
}
}
else
{
//do nothing
}
pointLT.x += faceRect.width / 2;
pointLT.y -= 2;
putTextCenter(img, string, pointLT, FONT, 1.2, GREEN, 2);
}
}
pointLT.x = 2;
pointLT.y = 16;
string = "(Q)Quit";
putText(img, string, pointLT, FONT, 1, BLUE, 1, 8);
pointLT.y += 16;
string = "(R)Register current unknown faces";
putText(img, string, pointLT, FONT, 1, BLUE, 1, 8);
pointLT.y += 16;
string = "(L)load faces from xml";
putText(img, string, pointLT, FONT, 1, BLUE, 1, 8);
pointLT.y += 16;
string = "(S)save faces into xml";
putText(img, string, pointLT, FONT, 1, BLUE, 1, 8);
const int FPS_MEASURE_INTERVAL = 30;
static int fpsInterval = 0;
static double fpsSum = 0;
static double fps = 0;
fpsSum += elapsed;
if (fpsInterval++ == FPS_MEASURE_INTERVAL)
{
fps = 1.f / fpsSum * FPS_MEASURE_INTERVAL;
fpsInterval = 0;
fpsSum = 0;
}
pointLT.y = img.size().height - 7;
string = format("fps:%.1f", fps);
putText(img, string, pointLT, FONT, 1.2, BLUE, 2, 8);
return true;
} |
79ecbf06a2680a452cc0faaab0857039d5d8c3e0 | e70718bc25c8c64a256c35d26321c47c84b3859a | /Ntupler/src/TDielectron.cc | a01f98420d90cff360d99e0f85c1716e12c5c227 | [] | no_license | ksung25/EWKAna | ae36ea9d63cc853ebfa73fc3f42da26e48dbda2b | 4458781d181e6fdc5364a2e25dd70e79d5c24079 | refs/heads/master | 2021-01-10T19:33:09.205898 | 2014-01-16T17:43:02 | 2014-01-16T17:43:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 81 | cc | TDielectron.cc | #include "EWKAna/Ntupler/interface/TDielectron.hh"
ClassImp(mithep::TDielectron)
|
c1b0b1abe04c791b637db2c48c7941f9b3937704 | 278d4d79484f3ceae7406b0e1f9f84ad31b972ea | /Pause_menu.cpp | 9fd7799a14ddae2a30f1d50bee9937f6639282c4 | [] | no_license | Rlk81/CS3398-cardassians-S2019 | cac63550332fba898277e383e2b88d7c9cad8471 | 05297e7b63d113278fd626ff40b4620e6312d513 | refs/heads/master | 2021-01-04T21:48:24.155166 | 2019-05-02T05:11:32 | 2019-05-02T05:11:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,947 | cpp | Pause_menu.cpp | #include "Pause_menu.h"
void Pause_menu::Pause_Menu(IO startIO, Board &b, Game &g, Difficulty &difficulty, int& lines_cleared, int& temp_score, int& score) {
//Images for menu
SDL_Surface* start_background = SDL_LoadBMP("Start_menu_background.bmp");
SDL_Surface* start_screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
SDL_Surface* start_button = SDL_LoadBMP("Resume_button.bmp");
SDL_Surface* start_button_mouse_over = SDL_LoadBMP("Resume_button_mouseover.bmp");
SDL_Surface* options_button = NULL;
SDL_Surface* reset_button = SDL_LoadBMP("Reset_button.bmp");
SDL_Surface* reset_button_mouseover = SDL_LoadBMP("Reset_button_mouseover.bmp");
SDL_Surface* return_to_start = SDL_LoadBMP("MainMenu_button.bmp");
SDL_Surface* return_to_start_mouseover = SDL_LoadBMP("MainMenu_button_mouseover.bmp");
//Start SDL
SDL_Init(SDL_INIT_EVERYTHING);
//Apply image to screen
SDL_BlitSurface(start_background, NULL, start_screen, NULL);
SDL_Rect srcrect;
srcrect.x = 0;
srcrect.y = 0;
SDL_Rect start_rect;
start_rect.x = 550 / 2; //275
start_rect.y = 400 / 2; //200
SDL_Rect options_rect;
options_rect.x = 550 / 2; //265
options_rect.y = 600 / 2; //300
SDL_Rect reset_rect;
reset_rect.x = 480 / 2; //240
reset_rect.y = 600 / 2; //300
SDL_Rect return_to_start_rect;
return_to_start_rect.x = 550 / 2; //275
return_to_start_rect.y = 800 / 2; //300
//SDL_BlitSurface( start_button, &start_button_Rect, start_screen, NULL );
SDL_BlitSurface(start_button, NULL, start_screen, &start_rect);
//Add options button
SDL_BlitSurface(options_button, NULL, start_screen, &options_rect);
//Add reset button
SDL_BlitSurface(reset_button, NULL, start_screen, &reset_rect);
//Add Return to Start button
SDL_BlitSurface(return_to_start, NULL, start_screen, &return_to_start_rect);
//Coordinates for mouse
int Mx = 0;
int My = 0;
bool play1 = false;
//Update Screen
SDL_Flip(start_screen);
while (!startIO.IsKeyDown(SDLK_ESCAPE)) {
////////////////////
//Pause Button
//if over start button, button turns white
SDL_GetMouseState(&Mx, &My);
if ((Mx > 275) && (Mx < 375))
if ((My < 258)& (My > 200)) {
SDL_Flip(start_screen);
SDL_BlitSurface(start_button_mouse_over, NULL, start_screen, &start_rect);
}
//Click start button
if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT) &(Mx > 275) && (Mx < 375)
& (My < 258)& (My > 200)) {
SDL_Delay(100);
break;
}
//if mouse not over button, turns back to original
SDL_GetMouseState(&Mx, &My);
if ((Mx < 275) || (Mx > 375) || (My > 258) || (My < 200)) {
SDL_Flip(start_screen);
SDL_BlitSurface(start_button, NULL, start_screen, &start_rect);
}
////////////////
//Reset Button
//Add reset
if ((Mx > 275) && (Mx < 375))
if ((My < 358)& (My > 300)) {
SDL_Flip(start_screen);
SDL_BlitSurface(reset_button_mouseover, NULL, start_screen, &reset_rect);
}
//Click reset button
if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT) &(Mx > 275) && (Mx < 375)
& (My < 358)& (My > 300)) {
SDL_Delay(100);
//resets score
lines_cleared = 0;
temp_score = 0;
score = 0;
Reset_Option(b, g, difficulty);
break;
}
//if mouse not over button, turns back to original
SDL_GetMouseState(&Mx, &My);
if ((Mx < 275) || (Mx > 375) || (My > 358) || (My < 300)) {
SDL_Flip(start_screen);
SDL_BlitSurface(reset_button, NULL, start_screen, &reset_rect);
}
////////////////////
//Return to Main Button
if ((Mx > 275) && (Mx < 375))
if ((My < 458)& (My > 400)) {
SDL_Flip(start_screen);
SDL_BlitSurface(return_to_start_mouseover, NULL, start_screen, &return_to_start_rect);
}
//Click reset button
if (SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT) &(Mx > 275) && (Mx < 375)
& (My < 458)& (My > 400)) {
SDL_Delay(100);
//resets score
lines_cleared = 0;
temp_score = 0;
score = 0;
Return_to_Start(startIO, b, g, difficulty);
break;
}
//if mouse not over button, turns back to original
SDL_GetMouseState(&Mx, &My);
if ((Mx < 275) || (Mx > 375) || (My > 458) || (My < 400)) {
SDL_Flip(start_screen);
SDL_BlitSurface(return_to_start, NULL, start_screen, &return_to_start_rect);
}
}
SDL_FreeSurface(start_background);
}
void Pause_menu::Return_to_Start(IO mIO, Board &b, Game &g, Difficulty &difficulty) {
Start_menu s;
//s.set_index(1);
s.Start_Menu(mIO, difficulty);
Reset_Option(b, g, difficulty);
}
//To be used in resetting game
void Pause_menu::Reset_Option(Board &b, Game &g, Difficulty &difficulty)
{
//resets board
b.ResetBoard();
//Creates new pieces/piece queue
g.resetHold();
g.CreateNewPiece(difficulty);
}
|
808242a30c04880d936588b1c99ba38d2c3aeb19 | 310992385f9d9acf0c4fe97cd215025985d11bec | /components.cpp | e0956232a2824ef0fbf81cca35da1e8dff791edd | [] | no_license | nimadastmalchi/gravity-simulator | e220e938509dedfd0bd1b1d0ea4f0eb40ba5bf6c | eadad6525197cb0a627650754c451b9b09b40b2c | refs/heads/main | 2023-05-26T11:52:54.634884 | 2023-05-23T03:20:14 | 2023-05-23T03:20:14 | 333,347,022 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | cpp | components.cpp | #ifndef components_cpp
#define components_cpp
#define MASS_RADIUS_MULT 10
#include "components.h"
Vector::Vector() : x(0), y(0) {}
Vector::Vector(const double& ix, const double& iy) : x(ix), y(iy) {}
double Vector::getx() const { return x; }
double Vector::gety() const { return y; }
void Vector::setx(const double& x) {
this->x = x;
}
void Vector::sety(const double& y) {
this->y = y;
}
double Vector::getmag() {
return pow(pow(x, 2.0) + pow(y, 2.0), 0.5);
}
Vector Vector::unit_vector() {
return (*this) / getmag();
}
Vector Vector::operator*(const double& scaler) {
return Vector(this->x * scaler, this->y * scaler);
}
Vector Vector::operator/(const double& scaler) {
return Vector(this->x / scaler, this->y / scaler);
}
Vector Vector::operator+(const Vector& other) {
return Vector(this->x + other.x, this->y + other.y);
}
Vector Vector::operator-(const Vector& other) {
return Vector(this->x - other.x, this->y - other.y);
}
ostream& operator<<(ostream& out, const Vector& v) {
out << "(" + to_string(v.getx()) + ", " + to_string(v.gety()) + ")" << endl;
return out;
}
Point::Point() : loc(Vector()), init_vel(Vector()), rad(0), mass(0), current_time(0) {}
Point::Point(const Vector& iloc, const Vector& i_init_vel, const Vector& iaccel, const double& ir, const double& imass) : loc(iloc), init_vel(i_init_vel), accel(iaccel), rad(ir), mass(imass), current_time(0) {}
Vector& Point::getloc() { return loc; }
Vector& Point::getinitvel() { return init_vel; }
Vector& Point::getaccel() { return accel; }
double Point::getrad() const { return rad; }
double Point::getmass() const { return mass; }
double Point::gettime() const { return current_time; }
void Point::reset_time() {
current_time = 0;
}
void Point::inc_time() {
current_time += TIME_INC;
}
#endif
|
fc44c84422f0394adc317196f9eec5116a9b99f8 | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /HLT/TPCLib/AliHLTTPCAgent.cxx | b552a7d4bec81f0118ba7b236ea048c397621f3d | [
"GPL-1.0-or-later"
] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 26,662 | cxx | AliHLTTPCAgent.cxx | // $Id$
//**************************************************************************
//* This file is property of and copyright by the *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
// @file AliHLTTPCAgent.cxx
// @author Matthias Richter
// @date
// @brief Agent of the libAliHLTTPC library
// @note
#include "AliHLTTPCAgent.h"
#include "AliHLTTPCDefinitions.h"
#include "AliHLTOUT.h"
#include "AliHLTOUTHandlerChain.h"
#include "AliHLTMisc.h"
#include "AliRunLoader.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliTPCParam.h"
#include "AliTPCRecoParam.h"
#include "AliDAQ.h"
#include "TObject.h"
#include "AliHLTPluginBase.h"
#include "AliHLTSystem.h"
/** global instance for agent registration */
AliHLTTPCAgent gAliHLTTPCAgent;
// component headers
#ifdef HAVE_ALIGPU
#include "GPUTPCTrackerComponent.h"
#include "GPUTPCGlobalMergerComponent.h"
#include "AliHLTTPCClusterStatComponent.h"
#include "AliHLTGPUDumpComponent.h"
#endif
#include "AliHLTTPCTrackMCMarkerComponent.h"
#include "AliHLTTPCdEdxComponent.h"
#include "AliHLTTPCdEdxMonitoringComponent.h"
#include "AliHLTTPCDigitPublisherComponent.h"
#include "AliHLTTPCDigitDumpComponent.h"
#include "AliHLTTPCClusterDumpComponent.h"
#include "AliHLTTPCClusterHistoComponent.h"
#include "AliHLTTPCHistogramHandlerComponent.h"
#include "AliHLTTPCDataCheckerComponent.h"
#include "AliHLTTPCHWCFEmulatorComponent.h"
#include "AliHLTTPCHWCFConsistencyControlComponent.h"
#include "AliHLTTPCDataCompressionComponent.h"
#include "AliHLTTPCDataCompressionMonitorComponent.h"
#include "AliHLTTPCDataCompressionUnpackerComponent.h"
#include "AliHLTTPCDataCompressionFilterComponent.h"
#include "AliHLTTPCDataPublisherComponent.h"
#include "AliHLTTPCHWClusterDecoderComponent.h"
#include "AliHLTTPCClusterTransformationComponent.h"
#include "AliHLTTPCClusterTransformationPrepareComponent.h"
#include "AliHLTTPCOfflinePreprocessorWrapperComponent.h"
#include "AliHLTTPCFastdEdxComponent.h"
#include "test/AliHLTTPCRawClusterDumpComponent.h"
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCAgent)
AliHLTTPCAgent::AliHLTTPCAgent()
: AliHLTModuleAgent("TPC")
, fRawDataHandler(NULL)
, fTracksegsDataHandler(NULL)
, fClustersDataHandler(NULL)
, fCompressionMonitorHandler(NULL)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTTPCAgent::~AliHLTTPCAgent()
{
// see header file for class documentation
}
UInt_t AliHLTTPCAgent::GetDetectorMask() const
{
return AliDAQ::kTPC;
}
int AliHLTTPCAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
AliRawReader* rawReader,
AliRunLoader* runloader) const
{
// see header file for class documentation
if (handler) {
// AliSimulation: use the AliRawReaderPublisher if the raw reader is available
// AliReconstruction: indicated by runloader==NULL, run always on raw data
bool bPublishRaw=rawReader!=NULL || runloader==NULL;
AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();
bool isRawHLTOUT = 1;
int tpcInputMode = 0;
TString transformArg;
if( pHLT ){
TString hltoptions = pHLT->GetConfigurationString();
TObjArray* pTokens=hltoptions.Tokenize(" ");
if( pTokens ){
int iEntries=pTokens->GetEntriesFast();
for (int i=0; i<iEntries; i++) {
if (!pTokens->At(i)) continue;
TString token = pTokens->At(i)->GetName();
if (token.CompareTo("ignore-hltout")==0) {
isRawHLTOUT = 0;
} else if (token.CompareTo("run-online-config")==0) {
isRawHLTOUT = 0;
} else if (token.Contains("TPC-transform:")) {
transformArg = token.ReplaceAll("TPC-transform:", "");
} else if (token.Contains("TPC-input=")) {
TString param=token.ReplaceAll("TPC-input=", "");
if (param == "default") {
tpcInputMode = 0;
} else if (param == "raw") {
tpcInputMode = 1;
} else if (param == "compressed") {
tpcInputMode = 2;
} else {
HLTWarning("wrong parameter \'%s\' for option \'TPC-input=\', expected \'default\'/\'raw\'/\'compressed\'",param.Data() );
}
}
}
delete pTokens;
}
}
// This the tracking configuration for the full TPC
// - 216 clusterfinders (1 per partition)
// - 36 slice trackers
// - one global merger
// - the esd converter
// The ESD is shipped embedded into a TTree
int iMinSlice=0;
int iMaxSlice=35;
int iMinPart=0;
int iMaxPart=5;
TString arg;
TString mergerInput;
TString sinkRawData;
TString sinkHWClusterInput;
TString dEdXInput;
TString hwcfemuInput;
TString hwclustOutput;
TString compressorInput;
TString trackerInput;
// Default TPC input: raw data or compressed clusters
if( isRawHLTOUT ){
// Compressed clusters are already copied from the raw file to the HLTOUT.
// The system should only reconstruct raw data for the sectors where the compressed clusters are missing
arg.Form("-publish-clusters off -publish-raw filtered");
} else {
// HLTOUT is initially empty, therefore the HLT system reconstructs everything
// The prefered input data is compressed clusters. TPC raw data is only published when the clusters are not present.
arg.Form("-publish-clusters all -publish-raw filtered");
}
// Overwrite the default input when "TPC-input=.." option is set by user
if( tpcInputMode==1 ){
arg.Form("-publish-clusters off -publish-raw all");
} else if ( tpcInputMode==2 ){
arg.Form("-publish-clusters all -publish-raw off");
}
handler->CreateConfiguration("TPC-DP", "TPCDataPublisher", NULL , arg.Data());
if (bPublishRaw) {
hwcfemuInput = "TPC-DP";
}
for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
for (int part=iMinPart; part<=iMaxPart; part++) {
TString publisher;
// digit publisher components
publisher.Form("TPC-DP_%02d_%d", slice, part);
if (bPublishRaw) {
// AliSimulation: use the AliRawReaderPublisher if the raw reader is available
// AliReconstruction: indicated by runloader==NULL, run always on raw data
int ddlno=768;
if (part>1) ddlno+=72+4*slice+(part-2);
else ddlno+=2*slice+part;
// arg.Form("-datatype 'DDL_RAW ' 'TPC ' -dataspec 0x%02x%02x%02x%02x", slice, slice, part, part);
arg.Form("-dataspec 0x%02x%02x%02x%02x", slice, slice, part, part); // publish also unpacked clusters, not only raw data
handler->CreateConfiguration(publisher.Data(), "BlockFilter", "TPC-DP" , arg.Data());
if (sinkRawData.Length()>0) sinkRawData+=" ";
sinkRawData+=publisher;
} else {
//arg.Form("-slice %d -partition %d", slice, part);
arg.Form("-slice %d -partition %d -late-fill", slice, part);
handler->CreateConfiguration(publisher.Data(), "TPCDigitPublisher", NULL , arg.Data());
if (hwcfemuInput.Length()>0) hwcfemuInput+=" ";
hwcfemuInput+=publisher;
}
}
}
// Hardware CF emulator
TString hwcfemu;
hwcfemu.Form("TPC-HWCFEmu");
arg="";
if (!bPublishRaw) arg+=" -do-mc 1";
handler->CreateConfiguration(hwcfemu.Data(), "TPCHWClusterFinderEmulator", hwcfemuInput.Data(), arg.Data());
if (hwclustOutput.Length()>0) hwclustOutput+=" ";
hwclustOutput+=hwcfemu;
TString hwcfDecoder = "TPC-HWCFDecoder";
handler->CreateConfiguration(hwcfDecoder.Data(), "TPCHWClusterDecoder",hwclustOutput.Data(), "");
arg = transformArg;
arg+=" -offline-mode";
if (!bPublishRaw) arg+=" -do-mc -offline-keep-initial-timestamp";
TString clusterTransformation = "TPC-ClusterTransformation";
handler->CreateConfiguration(clusterTransformation.Data(), "TPCClusterTransformation",hwcfDecoder.Data(), arg.Data() );
if (trackerInput.Length()>0) trackerInput+=" ";
trackerInput+=clusterTransformation;
if (dEdXInput.Length()>0) dEdXInput+=" ";
dEdXInput+=clusterTransformation;
if (sinkHWClusterInput.Length()>0) sinkHWClusterInput+=" ";
sinkHWClusterInput+=clusterTransformation;
// tracker finder component
// 2012-01-05 changing the configuration according to online setup
// the tracking strategy has been changed in the online system in Sep 2011
// the tracker now processes all clusters, and several of this 'global' trackers
// run in parallel. The GlobalMerger is still in the chain as it produces the final
// fit.
TString tracker;
tracker.Form("TPC-TR");
handler->CreateConfiguration(tracker.Data(), "TPCCATracker", trackerInput.Data(), "-GlobalTracking");
if (mergerInput.Length()>0) mergerInput+=" ";
mergerInput+=tracker;
// GlobalMerger component
handler->CreateConfiguration("TPC-globalmerger","TPCCAGlobalMerger",mergerInput.Data(),"");
// dEdx component
if (dEdXInput.Length()>0) dEdXInput+=" ";
dEdXInput+="TPC-globalmerger";
handler->CreateConfiguration("TPC-dEdx","TPCdEdx",dEdXInput.Data(),"");
handler->CreateConfiguration("TPC-FastdEdx","FastTPCdEdx",dEdXInput.Data(),"");
// compression component
if (compressorInput.Length()>0) compressorInput+=" ";
//compressorInput+=hwclustOutput;
compressorInput+=hwcfDecoder;
// special configuration to run the emulation automatically if the compressed clusters
// of a particular partition is missing. This configuration is announced for reconstruction
// of raw data if the HLT mode of the TPC reconstruction is enabled. Compression component
// always needs to run in mode 1. Even if the recorded data is mode 3 (optimized partition
// clusters), 2 (track model compression), or 4. The emulation can not be in mode 2 or 4,
// since the track model block can not be identified with a partition. Have to duplicate the
// configuration of the compression component
handler->CreateConfiguration("TPC-compression-emulation", "TPCDataCompressor", compressorInput.Data(), "-mode 1");
handler->CreateConfiguration("TPC-compression-only", "TPCDataCompressor", compressorInput.Data(), "");
if (compressorInput.Length()>0) compressorInput+=" ";
compressorInput+="TPC-globalmerger";
handler->CreateConfiguration("TPC-compression", "TPCDataCompressor", compressorInput.Data(), "-cluster-ids 1");
handler->CreateConfiguration("TPC-compression-huffman-trainer", "TPCDataCompressor", compressorInput.Data(),"-deflater-mode 3");
handler->CreateConfiguration("TPC-compression-monitoring-component", "TPCDataCompressorMonitor", "TPC-compression TPC-hwcfdata","-pushback-period=30");
handler->CreateConfiguration("TPC-compression-monitoring", "ROOTFileWriter", "TPC-compression-monitoring-component","-concatenate-events -overwrite -datafile HLT.TPCDataCompression-statistics.root");
// compressed cluster ids
handler->CreateConfiguration("TPC-compressed-cluster-ids", "BlockFilter" , "TPC-compression", "-datatype 'CLIDSTRK' 'TPC ' -datatype 'REMCLIDS' 'TPC '");
handler->CreateConfiguration("TPC-compressed-clusters-no-ids", "BlockFilter" , "TPC-compression", "-datatype 'COMPDESC' 'TPC ' -datatype 'CLUSNOTC' 'TPC ' -datatype 'REMCLSCM' 'TPC ' -datatype 'CLSTRKCM' 'TPC ' -datatype 'CLSFLAGS' 'TPC '");
// the esd converter configuration
TString converterInput="TPC-globalmerger";
if (!bPublishRaw) {
// propagate cluster info to the esd converter in order to fill the MC information
handler->CreateConfiguration("TPC-clustermc-info", "BlockFilter" , sinkHWClusterInput.Data(), "-datatype 'CLMCINFO' 'TPC '");
handler->CreateConfiguration("TPC-mcTrackMarker","TPCTrackMCMarker","TPC-globalmerger TPC-clustermc-info","" );
converterInput+=" ";
converterInput+="TPC-mcTrackMarker";
}
handler->CreateConfiguration("TPC-esd-converter", "TPCEsdConverter" , converterInput.Data(), "");
// cluster dump collection
handler->CreateConfiguration("TPC-clusters", "BlockFilter" , sinkHWClusterInput.Data(), "-datatype 'CLUSTERS' 'TPC ' -datatype 'CLMCINFO' 'TPC '");
handler->CreateConfiguration("TPC-raw-clusters", "BlockFilter" , sinkHWClusterInput.Data(), "-datatype 'CLUSTRAW' 'TPC ' -datatype 'CLMCINFO' 'TPC '");
handler->CreateConfiguration("TPC-hwclusters", "BlockFilter" , sinkHWClusterInput.Data(), "-datatype 'CLUSTERS' 'TPC ' -datatype 'CLMCINFO' 'TPC '");
handler->CreateConfiguration("TPC-raw-hwclusters", "BlockFilter" , sinkHWClusterInput.Data(), "-datatype 'CLUSTRAW' 'TPC ' -datatype 'CLMCINFO' 'TPC '");
// raw data
handler->CreateConfiguration("TPC-raw-data", "BlockFilter" , sinkRawData.Data(), "");
handler->CreateConfiguration("TPC-hwcfdata", "BlockFilter" , hwclustOutput.Data(), "-datatype 'HWCLUST1' 'TPC '");
/////////////////////////////////////////////////////////////////////////////////////
//
// dumps on the ALTRO digit level
//
// selected channel dump
arg.Form("-datafile selected-channel.dump -specfmt=_0x%%08x -subdir -blcknofmt= -idfmt=");
handler->CreateConfiguration("TPC-selected-altro-digits", "TPCDigitDump", "RCU-channelselect", arg.Data());
// raw channel dump
arg.Form("-datafile channel.dump -specfmt=_0x%%08x -subdir -blcknofmt= -idfmt=");
handler->CreateConfiguration("TPC-raw-altro-digits", "TPCDigitDump", "TPC-raw-data", arg.Data());
/////////////////////////////////////////////////////////////////////////////////////
//
// a kChain HLTOUT configuration for processing of {'TRAKSEGS':'TPC '} data blocks
// collects the data blocks, merges the tracks and produces an ESD object
// publisher component
handler->CreateConfiguration("TPC-hltout-tracksegs-publisher", "AliHLTOUTPublisher" , NULL, "");
// GlobalMerger component
handler->CreateConfiguration("TPC-hltout-tracksegs-merger", "TPCGlobalMerger", "TPC-hltout-tracksegs-publisher", "");
// the esd converter configuration
handler->CreateConfiguration("TPC-hltout-tracksegs-esd-converter", "TPCEsdConverter", "TPC-hltout-tracksegs-merger", "");
/////////////////////////////////////////////////////////////////////////////////////
//
// a kChain HLTOUT configuration for processing of {'TRACKS ':'TPC '} data blocks
// produces an ESD object from the track structure
// publisher component
handler->CreateConfiguration("TPC-hltout-tracks-publisher", "AliHLTOUTPublisher" , NULL, "");
// the esd converter configuration
handler->CreateConfiguration("TPC-hltout-tracks-esd-converter", "TPCEsdConverter", "TPC-hltout-tracks-publisher", "");
/////////////////////////////////////////////////////////////////////////////////////
//
// a kChain HLTOUT configuration for processing of {'CLUSTERS':'TPC '} data blocks
// stores the blocks in file HLT.TPC.Clusters.root in HOMER format
// publisher component
handler->CreateConfiguration("TPC-hltout-cluster-publisher", "AliHLTOUTPublisher" , NULL, "");
// the HLTOUT component collects the blocks and stores the file
handler->CreateConfiguration("TPC-hltout-cluster-dump", "HLTOUT", "TPC-hltout-cluster-publisher", "-digitfile HLT.TPC.Clusters.root -rawout=off -links 2");
/////////////////////////////////////////////////////////////////////////////////////
//
// monitoring of compressed TPC data {CLUSTRAW:TPC }, {REMCLSCM,TPC }, {CLSTRKCM,TPC }
//
// publisher component
handler->CreateConfiguration("TPC-hltout-compressionmonitor-publisher", "AliHLTOUTPublisher" , NULL,
"-datatype HWCLUST1 'TPC ' "
"-datatype CLUSTRAW 'TPC ' "
"-datatype REMCLSCM 'TPC ' "
"-datatype CLSTRKCM 'TPC ' "
"-datatype REMCLIDS 'TPC ' "
"-datatype CLIDSTRK 'TPC ' "
);
// the HLTOUT component collects the blocks and stores the file
handler->CreateConfiguration("TPC-hltout-compressionmonitor", "TPCDataCompressorMonitor", "TPC-hltout-compressionmonitor-publisher", "-histogram-file HLT.TPC-compression-statistics.root -publishing-mode off");
}
return 0;
}
const char* AliHLTTPCAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
AliRunLoader* runloader) const
{
// see header file for class documentation
if (runloader) {
// reconstruction chains for AliRoot simulation
return "TPC-compression";
} else {
return "TPC-compression-emulation";
}
return NULL;
}
const char* AliHLTTPCAgent::GetRequiredComponentLibraries() const
{
// see header file for class documentation
// actually, the TPC library has dependencies to Util and RCU
// so the two has to be loaded anyhow before we get here
//return "libAliHLTUtil.so libAliHLTRCU.so";
return "libAliHLTUtil.so";
}
int AliHLTTPCAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
// see header file for class documentation
if (!pHandler) return -EINVAL;
#ifdef HAVE_ALIGPU
pHandler->AddComponent(new GPUTPCTrackerComponent);
pHandler->AddComponent(new GPUTPCGlobalMergerComponent);
pHandler->AddComponent(new AliHLTTPCClusterStatComponent);
pHandler->AddComponent(new AliHLTGPUDumpComponent);
#endif
pHandler->AddComponent(new AliHLTTPCTrackMCMarkerComponent);
pHandler->AddComponent(new AliHLTTPCdEdxComponent);
pHandler->AddComponent(new AliHLTTPCFastdEdxComponent);
pHandler->AddComponent(new AliHLTTPCdEdxMonitoringComponent);
pHandler->AddComponent(new AliHLTTPCDigitPublisherComponent);
pHandler->AddComponent(new AliHLTTPCDigitDumpComponent);
pHandler->AddComponent(new AliHLTTPCClusterDumpComponent);
pHandler->AddComponent(new AliHLTTPCClusterHistoComponent);
pHandler->AddComponent(new AliHLTTPCHistogramHandlerComponent);
pHandler->AddComponent(new AliHLTTPCDataCheckerComponent);
pHandler->AddComponent(new AliHLTTPCHWCFEmulatorComponent);
// pHandler->AddComponent(new AliHLTTPCHWCFConsistencyControlComponent); //FIXME: Causes crash: https://savannah.cern.ch/bugs/?83677
pHandler->AddComponent(new AliHLTTPCDataCompressionComponent);
pHandler->AddComponent(new AliHLTTPCDataCompressionMonitorComponent);
pHandler->AddComponent(new AliHLTTPCDataCompressionUnpackerComponent);
pHandler->AddComponent(new AliHLTTPCDataCompressionFilterComponent);
pHandler->AddComponent(new AliHLTTPCDataPublisherComponent);
pHandler->AddComponent(new AliHLTTPCHWClusterDecoderComponent);
pHandler->AddComponent(new AliHLTTPCClusterTransformationComponent);
pHandler->AddComponent(new AliHLTTPCClusterTransformationPrepareComponent);
pHandler->AddComponent(new AliHLTTPCOfflinePreprocessorWrapperComponent);
pHandler->AddComponent(new AliHLTTPCRawClusterDumpComponent);
return 0;
}
int AliHLTTPCAgent::GetHandlerDescription(AliHLTComponentDataType dt,
AliHLTUInt32_t spec,
AliHLTOUTHandlerDesc& desc) const
{
// see header file for class documentation
// raw data blocks to be fed into offline reconstruction
if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginTPC)) {
int slice=AliHLTTPCDefinitions::GetMinSliceNr(spec);
int part=AliHLTTPCDefinitions::GetMinPatchNr(spec);
if (slice==AliHLTTPCDefinitions::GetMaxSliceNr(spec) &&
part==AliHLTTPCDefinitions::GetMaxPatchNr(spec)) {
desc=AliHLTOUTHandlerDesc(kRawReader, dt, GetModuleId());
return 1;
} else {
HLTWarning("handler can not process merged data from multiple ddls:"
" min slice %d, max slice %d, min part %d, max part %d",
slice, AliHLTTPCDefinitions::GetMaxSliceNr(spec),
part, AliHLTTPCDefinitions::GetMaxPatchNr(spec));
return 0;
}
}
// dump for {'CLUSTERS':'TPC '} blocks stored in a 'digit' file
if (dt==AliHLTTPCDefinitions::fgkClustersDataType) {
desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());
return 1;
}
// define handlers for all blocks related to compression, flag if the
// cluster id blocks are existing, this will be used to decide
// whether to create the handler or not
// {'CLUSTRAW':'TPC '}
// {'HWCLUST1':'TPC '}
// {'REMCLSCM':'TPC '}
// {'CLSTRKCM':'TPC '}
// {'REMCLIDS':'TPC '}
// {'CLIDSTRK':'TPC '}
// {'CLSFLAGS':'TPC '}
// {'COMPDESC':'TPC '}
if (dt==AliHLTTPCDefinitions::RawClustersDataType() ||
dt==AliHLTTPCDefinitions::RawClustersDataTypeNotCompressed() ||
dt==AliHLTTPCDefinitions::HWClustersDataType() ||
dt==AliHLTTPCDefinitions::RemainingClustersCompressedDataType() ||
dt==AliHLTTPCDefinitions::ClusterTracksCompressedDataType() ||
dt==AliHLTTPCDefinitions::ClustersFlagsDataType() ||
dt==AliHLTTPCDefinitions::DataCompressionDescriptorDataType()) {
desc=AliHLTOUTHandlerDesc(kProprietary, dt, GetModuleId());
return 1;
}
if (dt==AliHLTTPCDefinitions::RemainingClusterIdsDataType() ||
dt==AliHLTTPCDefinitions::ClusterIdTracksDataType()) {
desc=AliHLTOUTHandlerDesc(kProprietary, dt, GetModuleId());
const_cast<AliHLTTPCAgent*>(this)->SetBit(kHaveCompressedClusterIdDataBlock);
return 1;
}
// {'CLMCINFO':'TPC '}
if (dt==AliHLTTPCDefinitions::fgkAliHLTDataTypeClusterMCInfo) {
desc=AliHLTOUTHandlerDesc(kProprietary, dt, GetModuleId());
return 1;
}
// afterburner for {'TRAKSEGS':'TPC '} blocks to be converted to ESD format
if (dt==AliHLTTPCDefinitions::fgkTrackSegmentsDataType) {
desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());
return 1;
}
// afterburner for {'TRACKS ':'TPC '} block to be converted to ESD format
// there is only one data block
if (dt==AliHLTTPCDefinitions::fgkTracksDataType) {
desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());
return 1;
}
return 0;
}
AliHLTOUTHandler* AliHLTTPCAgent::GetOutputHandler(AliHLTComponentDataType dt,
AliHLTUInt32_t /*spec*/)
{
// see header file for class documentation
// raw data blocks to be fed into offline reconstruction
if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginTPC)) {
if (!fRawDataHandler) {
fRawDataHandler=new AliHLTTPCAgent::AliHLTTPCRawDataHandler;
}
return fRawDataHandler;
}
// dump for {'CLUSTERS':'TPC '}, stored in a file HLT.TPC.Clusters.root in HOMER format
if (dt==AliHLTTPCDefinitions::fgkClustersDataType) {
if (fClustersDataHandler==NULL)
fClustersDataHandler=new AliHLTOUTHandlerChain("chains=TPC-hltout-cluster-dump libHLTsim.so libAliHLTUtil.so");
return fClustersDataHandler;
}
// afterburner for {'TRAKSEGS':'TPC '} blocks to be converted to ESD format
// in a kChain HLTOUT handler
if (dt==AliHLTTPCDefinitions::fgkTrackSegmentsDataType) {
if (fTracksegsDataHandler==NULL)
fTracksegsDataHandler=new AliHLTOUTHandlerChain("chains=TPC-hltout-tracksegs-esd-converter");
return fTracksegsDataHandler;
}
// afterburner for {'TRACKS ':'TPC '} block to be converted to ESD format
// there is only one data block
if (dt==AliHLTTPCDefinitions::fgkTracksDataType) {
return new AliHLTOUTHandlerChain("chains=TPC-hltout-tracks-esd-converter");
}
// monitoring of compressed data if cluster verification blocks exist
// {'REMCLIDS':'TPC '}
// {'CLIDSTRK':'TPC '}
// FIXME: needs to be commissioned
// if (dt==AliHLTTPCDefinitions::RawClustersDataType() ||
// dt==AliHLTTPCDefinitions::RawClustersDataTypeNotCompressed() ||
// dt==AliHLTTPCDefinitions::HWClustersDataType() ||
// dt==AliHLTTPCDefinitions::RemainingClustersCompressedDataType() ||
// dt==AliHLTTPCDefinitions::ClusterTracksCompressedDataType() ||
// dt==AliHLTTPCDefinitions::RemainingClusterIdsDataType() ||
// dt==AliHLTTPCDefinitions::ClusterIdTracksDataType()) {
// const char* arg="chains=TPC-hltout-compressionmonitor";
// if (!TestBit(kHaveCompressedClusterIdDataBlock))
// arg="chains=TPC-hltout-compressionmonitorpublisher";
// if (!fCompressionMonitorHandler)
// fCompressionMonitorHandler=new AliHLTOUTHandlerChain(arg);
// return fCompressionMonitorHandler;
// }
return NULL;
}
int AliHLTTPCAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
// see header file for class documentation
if (pInstance==NULL) return -EINVAL;
if (pInstance==fRawDataHandler) {
delete fRawDataHandler;
fRawDataHandler=NULL;
}
if (pInstance==fTracksegsDataHandler) {
delete fTracksegsDataHandler;
fTracksegsDataHandler=NULL;
}
if (pInstance==fClustersDataHandler) {
delete fClustersDataHandler;
fClustersDataHandler=NULL;
}
if (pInstance==fCompressionMonitorHandler) {
delete fCompressionMonitorHandler;
fCompressionMonitorHandler=NULL;
}
return 0;
}
AliHLTTPCAgent::AliHLTTPCRawDataHandler::AliHLTTPCRawDataHandler()
{
// see header file for class documentation
}
AliHLTTPCAgent::AliHLTTPCRawDataHandler::~AliHLTTPCRawDataHandler()
{
// see header file for class documentation
}
int AliHLTTPCAgent::AliHLTTPCRawDataHandler::ProcessData(AliHLTOUT* pData)
{
// see header file for class documentation
if (!pData) return -EINVAL;
AliHLTComponentDataType dt=kAliHLTVoidDataType;
AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
int iResult=pData->GetDataBlockDescription(dt, spec);
if (iResult>=0) {
int slice=AliHLTTPCDefinitions::GetMinSliceNr(spec);
int part=AliHLTTPCDefinitions::GetMinPatchNr(spec);
if (slice==AliHLTTPCDefinitions::GetMaxSliceNr(spec) &&
part==AliHLTTPCDefinitions::GetMaxPatchNr(spec)) {
iResult=768;
if (part>1) iResult+=72+4*slice+(part-2);
else iResult+=2*slice+part;
} else {
HLTError("handler can not process merged data from multiple ddls:"
" min slice %d, max slice %d, min part %d, max part %d",
slice, AliHLTTPCDefinitions::GetMaxSliceNr(spec),
part, AliHLTTPCDefinitions::GetMaxPatchNr(spec));
iResult=-EBADMSG;
}
}
return iResult;
}
|
7f414c3815b2d2ee62ac8e36a76e52d51a76ec02 | 08447d0db2c609ddb8a673d9ad29cb95caf0125e | /src/Base.cpp | a7fc11e819f491cc0711c854ca7555b1c6fe72b6 | [] | no_license | geoliveira/cg | 1a786eb464ba34af6f94b8444630957fc8c47f58 | ff49de10987c14d9d32521dfbd1fa0eb73a2bf5a | refs/heads/main | 2023-05-04T02:53:22.890368 | 2021-05-21T21:53:21 | 2021-05-21T21:53:21 | 315,444,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp | Base.cpp | #include "Base.h"
string data_atual() {
struct tm *data;
time_t segundos;
time(&segundos);
data = localtime(&segundos);
return to_string(data->tm_mday)+"-"+
to_string(data->tm_mon+1)+"-"+
to_string(data->tm_year+1900)+"_"+
to_string(data->tm_hour)+"h"+
to_string(data->tm_min)+"m"+
to_string(data->tm_sec)+"s";
}
float graus_em_radianos(float grau) {
return grau * PI / 180.0;
}
float min(float a, float b) {
if (a < b)
return a;
return b;
}
float max(float a, float b) {
if (a > b)
return a;
return b;
}
bool pertence_intervalo(float x, float a, float b) {
return (x >= a && x <= b);
} |
61107bf12ab1d5f94a92239990af36aa5cdcb3db | f6cac62734ad207098db71c7a6c8d01c50b2225c | /myneuralnet.h | 88c8af9a495292ee7bfa862809e692a39149f90e | [] | no_license | khaiit/LTNC | 4a4b2d9eb1d80c1a8e3929a3e78d78c2288dcb1f | 6a01e604ff25dc72af221113b6d83ce6b51ba273 | refs/heads/master | 2021-01-01T04:59:15.867866 | 2017-07-15T01:47:21 | 2017-07-15T01:47:21 | 97,284,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,887 | h | myneuralnet.h | #ifndef BPNET_H
#define BPNET_H
/*********************************Cau truc Neural******************************/
struct neuron
{
float *weights; // Cac trong so dau vao neural
float *deltavalues; //gia tri delta
float output; //output
float gain;//Gain
float wgain;//Weight gain
neuron();//Constructor
~neuron();//Destructor
void create(int inputcount);//Cap phat vung nho va khoi tao cac gia tri
};
/**************************************Cau truc lop******************************/
struct layer
{
neuron **neurons;//dung mang de luu neurons
int neuroncount;//tong so neurons
float *layerinput;//lop input
int inputcount;//So phan tu trong lop input
layer();//Khoi tao cac gi tri =0
~layer();//Giai phong vung nho
void create(int inputsize, int _neuroncount);//Tao lop va phan chia vung nho
void calculate();// Tinh toan cac neural theo cong thuc mong muon
};
/********************************Cau truc mang ********************************/
class myneuralnet
{
private:
layer m_inputlayer;//lop input cua mang
layer m_outputlayer;//lop output : chua ket qua
layer **m_hiddenlayers;//lop an
int m_hiddenlayercount;/// so lop an
public:
//khoi tao Tao mang
myneuralnet();//Construction
~myneuralnet();//Destructo
//Tao mang
void create(int inputcount,int inputneurons,int outputcount,int *hiddenlayers,int hiddenlayercount);
void propagate(const float *input);//Tinh cac gia tri cua mang dua tren input
//Cap nhat gia tri cac trong so dua tren ket qua input va ap dung thuat ttoan lan truyen nguoc
float train(const float *desiredoutput,const float *input,float alpha, float momentum);
//Cap nhat gia tri input o lop sau
void update(int layerindex);
//Tra ve output
inline layer &getOutput()
{
return m_outputlayer;
}
};
#endif
|
e84a791a082942d45f952de5e99ff1a53ac55d0a | 5f62c0d9aea206cdc633e79db8e0b2d801f0a2cf | /gie/include/gie/NodeId.h | 21ab7cb2440eb9c24e1b789d9c243c27db5fbc14 | [
"BSD-3-Clause-Clear"
] | permissive | Kerdek/gie | e681b54ebc17ff15fdd42fdcf8b4da5aaf3123ee | ebcd1aec6dc34de46145e4013afd6d5dad194a9f | refs/heads/master | 2020-12-21T23:08:21.877964 | 2019-07-23T23:44:52 | 2019-07-23T23:44:52 | 236,594,381 | 0 | 0 | BSD-3-Clause-Clear | 2020-01-27T21:03:30 | 2020-01-27T21:03:29 | null | UTF-8 | C++ | false | false | 596 | h | NodeId.h | //
// Created by alex on 7/14/19.
//
#ifndef GIE_NODEID_H
#define GIE_NODEID_H
#include <StrongAlias.h>
#include <functional>
using NodeId = StrongAlias<std::size_t, struct NodeIdTag>;
inline bool operator==(const NodeId& lhs, const NodeId& rhs) { return lhs.get() == rhs.get(); }
namespace std
{
template<> struct hash<NodeId>
{
using argument_type = NodeId;
using result_type = std::size_t;
result_type operator()(const NodeId& id) const noexcept
{
return (std::hash<std::size_t>{})(id.get());
}
};
}
#endif //GIE_NODEID_H
|
72a062e9b203ce042b0aa1849ee05b18924832d1 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/26/1084.c | d53650220edda7601418d391de2b3215841fac30 | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | c | 1084.c | int main()
{
char a[105];
int i;
gets(a);
for(i=0;a[i]!='\0';i++){
if(a[i]!=' '){
printf("%c",a[i]);
}else if((a[i]==' ')&&(a[i+1]!=' ')){
printf(" ");
}
}
return 0;
} |
cda6d0b82666b552029d052477c6fcc0695efd9f | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /MistSlicer/Libs/MRML/vtkMRMLSliceCompositeNode.h | 91843f0614b449c2898284e63808c5fb7eb1b9d6 | [
"LicenseRef-scancode-3dslicer-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,913 | h | vtkMRMLSliceCompositeNode.h | /*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkMRMLSliceCompositeNode.h,v $
Date: $Date: 2006/03/19 17:12:29 $
Version: $Revision: 1.3 $
=========================================================================auto=*/
// .NAME vtkMRMLSliceCompositeNode - MRML node for storing a slice through RAS space
// .SECTION Description
// This node stores the information about how to composite two
// vtkMRMLVolumes into a single display image
//
#ifndef __vtkMRMLSliceCompositeNode_h
#define __vtkMRMLSliceCompositeNode_h
#include "vtkMRML.h"
#include "vtkMRMLScene.h"
#include "vtkMRMLNode.h"
#include "vtkMatrix4x4.h"
class VTK_MRML_EXPORT vtkMRMLSliceCompositeNode : public vtkMRMLNode
{
public:
static vtkMRMLSliceCompositeNode *New();
vtkTypeMacro(vtkMRMLSliceCompositeNode,vtkMRMLNode);
void PrintSelf(ostream& os, vtkIndent indent);
virtual vtkMRMLNode* CreateNodeInstance();
// Description:
// Set node attributes
virtual void ReadXMLAttributes( const char** atts);
// Description:
// Write this node's information to a MRML file in XML format.
virtual void WriteXML(ostream& of, int indent);
// Description:
// Copy the node's attributes to this object
virtual void Copy(vtkMRMLNode *node);
// Description:
// Get node XML tag name (like Volume, Model)
virtual const char* GetNodeTagName() {return "SliceComposite";};
// Description:
// Updates other nodes in the scene depending on this node
// or updates this node if it depends on other nodes when the scene is read in
// This method is called automatically by XML parser after all nodes are created
virtual void UpdateScene(vtkMRMLScene *);
// Description:
// Updates this node if it depends on other nodes
// when the node is deleted in the scene
virtual void UpdateReferences();
// Description:
// Update the stored reference to another node in the scene
virtual void UpdateReferenceID(const char *oldID, const char *newID);
// Description:
// the ID of a MRMLVolumeNode
vtkGetStringMacro (BackgroundVolumeID);
vtkSetReferenceStringMacro (BackgroundVolumeID);
void SetReferenceBackgroundVolumeID(const char *id) { this->SetBackgroundVolumeID(id); }
// Description:
// the ID of a MRMLVolumeNode
// TODO: make this an arbitrary list of layers
vtkGetStringMacro (ForegroundVolumeID);
vtkSetReferenceStringMacro (ForegroundVolumeID);
void SetReferenceForegroundVolumeID(const char *id) { this->SetForegroundVolumeID(id); }
// Description:
// the ID of a MRMLVolumeNode
// TODO: make this an arbitrary list of layers
vtkGetStringMacro (LabelVolumeID);
vtkSetReferenceStringMacro (LabelVolumeID);
void SetReferenceLabelVolumeID(const char *id) { this->SetLabelVolumeID(id); }
// Description:
// opacity of the Foreground for rendering over background
// TODO: make this an arbitrary list of layers
// TODO: make different composite types (checkerboard, etc)
vtkGetMacro (ForegroundOpacity, double);
vtkSetMacro (ForegroundOpacity, double);
// Description:
// opacity of the Label for rendering over background
// TODO: make this an arbitrary list of layers
// TODO: make different composite types (checkerboard, etc)
vtkGetMacro (LabelOpacity, double);
vtkSetMacro (LabelOpacity, double);
// Description:
// toggle that gangs control of slice viewers
vtkGetMacro (LinkedControl, int );
vtkSetMacro (LinkedControl, int );
// Description:
// toggles for grid in different slice layers.
vtkGetMacro (ForegroundGrid, int );
vtkSetMacro (ForegroundGrid, int );
vtkGetMacro (BackgroundGrid, int );
vtkSetMacro (BackgroundGrid, int );
vtkGetMacro (LabelGrid, int );
vtkSetMacro (LabelGrid, int );
// Description:
// toggles fiducial visibility in the slice viewer
vtkGetMacro (FiducialVisibility, int );
vtkSetMacro (FiducialVisibility, int );
vtkGetMacro (FiducialLabelVisibility, int );
vtkSetMacro (FiducialLabelVisibility, int );
// Description:
// configures the annotations
vtkGetMacro ( AnnotationSpace, int );
vtkSetMacro ( AnnotationSpace, int );
vtkGetMacro ( AnnotationMode, int );
vtkSetMacro ( AnnotationMode, int );
// Description:
// configures the crosshair appearance and behavior
vtkGetMacro (CrosshairMode, int );
vtkSetMacro (CrosshairMode, int );
vtkGetMacro (CrosshairBehavior, int );
vtkSetMacro (CrosshairBehavior, int );
// Description:
// Name of the layout
void SetLayoutName(const char *layoutName) {
this->SetSingletonTag(layoutName);
}
char *GetLayoutName() {
return this->GetSingletonTag();
}
//BTX
// Modes for annotation space and mode
enum
{
XYZ = 0,
IJK,
RAS,
IJKAndRAS
};
enum
{
NoAnnotation = 0,
All,
LabelValuesOnly,
LabelAndVoxelValuesOnly
};
// Modes for crosshair display and behavior
enum
{
NoCrosshair = 0,
ShowBasic,
ShowIntersection,
ShowHashmarks,
ShowAll
};
enum
{
Normal = 0,
JumpSlice
};
//ETX
protected:
vtkMRMLSliceCompositeNode();
~vtkMRMLSliceCompositeNode();
vtkMRMLSliceCompositeNode(const vtkMRMLSliceCompositeNode&);
void operator=(const vtkMRMLSliceCompositeNode&);
char *BackgroundVolumeID;
char *ForegroundVolumeID;
char *LabelVolumeID;
double ForegroundOpacity;
double LabelOpacity;
int LinkedControl;
int ForegroundGrid;
int BackgroundGrid;
int LabelGrid;
int FiducialVisibility;
int FiducialLabelVisibility;
int AnnotationSpace;
int AnnotationMode;
int CrosshairMode;
int CrosshairBehavior;
};
#endif
|
0949cb25ba6b04163504d6a476ea90cd738d1b01 | ccd66b3afdb74acaa99400e02dcf7cadf6a8a894 | /prg86 _copycon.cpp | 3119ca25d72c50118637f959c8a7a8bcf2b4ad63 | [] | no_license | Mrkotadiya/nirbhay_cpp | fdf298ec98604c27b62029d3a29646fa2cf69d9f | 678b40f78232f8feb4af3b51939121663f15f541 | refs/heads/master | 2023-08-01T04:20:56.512312 | 2021-09-23T11:18:10 | 2021-09-23T11:18:10 | 402,391,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | prg86 _copycon.cpp | #include<iostream>
using namespace std;
class findage
{
int age;
public:
findage(int n)//comstructor
{
age=n;
cout<<"\n constructor called= "<<age;
}
findage(findage &new_age)//comstructor
{
age=new_age.age;
cout<<"\n constructor called= "<<age;
}
};
int main()
{
findage nirbhay(19);
findage abhi(nirbhay);
} |
3859c9e8336d69e0575742db1fa662eea030b023 | 2d98f202e981b1a49eb37b6697170d803f2d215f | /Src/FM79979Engine/Core/SpineRender/SpineLoader.cpp | 473f3eddf8c4ed022ac547aca7a720142f756553 | [] | no_license | fatmingwang/FM79979 | bb1274241605f490b8e216f930a2c5aaba86f669 | 735f204bd70773c2482e15b3105a8680cf119706 | refs/heads/master | 2023-07-09T00:47:02.782514 | 2023-06-23T10:23:27 | 2023-06-23T10:23:27 | 43,816,834 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 18,245 | cpp | SpineLoader.cpp | #include "SpineLoader.h"
#include <spine/Debug.h>
#include <spine/spine.h>
#include <stdio.h>
#include <functional>
#include <tuple>
#include "SpineExtension.h"
#include "SkeletonRenderer.h"
#include "SkeletonAnimation.h"
#include "pch.h"
#include <filesystem>
using std::filesystem::directory_iterator;
//using std::filesystem::current_path;
#ifdef MSVC
#pragma warning(disable : 4710)
#endif
//https://github.com/GerogeChong/spine-sdl
class cExtensionForSpine : public spine::DefaultSpineExtension
{
public:
cExtensionForSpine() {}
virtual ~cExtensionForSpine() {}
protected:
virtual char* _readFile(const spine::String& path, int* length)override
{
auto l_pData = UT::GetFileContent(path.buffer(), *length, "rb");
auto bytes = SpineExtension::alloc<char>(*length, __FILE__, __LINE__);
memcpy(bytes, l_pData, *length);
delete l_pData;
return bytes;
}
};
class cTextureLoaderForSpine : public spine::TextureLoader, public NamedTypedObject
{
public:
cTextureLoaderForSpine(){}
virtual ~cTextureLoaderForSpine() {}
virtual void load(spine::AtlasPage& page, const spine::String& path)
{
auto l_pTexture = cTextureManager::GetInstance()->GetObject(this, path.buffer());
//CCASSERT(texture != nullptr, "Invalid image");
if (l_pTexture)
{
//texture->setTexParameters(textureParams);
page.setRendererObject(l_pTexture);
page.width = l_pTexture->GetWidth();
page.height = l_pTexture->GetHeight();
}
}
virtual void unload(void* texture)
{
if (texture)
{
cTexture* l_pTexture = (cTexture*)texture;
l_pTexture->Release(this);
}
}
};
cExtensionForSpine* g_pExtensionForSpine = nullptr;
DebugExtension* g_pSpineDebugExtension = nullptr;
cSpineCache::cSpineCache()
{
m_pTextureLoaderForSpine = nullptr;
m_pTextureLoaderForSpine = new cTextureLoaderForSpine();
#ifdef WASM
g_pExtensionForSpine = new cExtensionForSpine();
SpineExtension::setInstance(g_pExtensionForSpine);
#else
#ifdef DEBUG
//g_pSpineDebugExtension = new DebugExtension(SpineExtension::getInstance());
//SpineExtension::setInstance(g_pSpineDebugExtension);
#endif
#endif
}
cSpineCache::~cSpineCache()
{
DELETE_MAP(m_KeyAndSkeletonDataMap);
DELETE_MAP(m_KeyAndAnimationStateDataMap);
DELETE_MAP(m_KeyAndAtlasMap);
SAFE_DELETE(m_pTextureLoaderForSpine);
SAFE_DELETE(g_pExtensionForSpine);
#ifdef DEBUG
if (g_pSpineDebugExtension)
{
g_pSpineDebugExtension->reportLeaks();
delete g_pSpineDebugExtension;
}
#endif
}
spine::Atlas* cSpineCache::GetAtlas(const char* e_strAtlasFile)
{
auto l_IT = m_KeyAndAtlasMap.find(e_strAtlasFile);
if (l_IT == m_KeyAndAtlasMap.end())
{
int l_iFileLength = -1;
char* l_pAtlasContent = GetFileContent(e_strAtlasFile, l_iFileLength, "rb");
if (l_pAtlasContent)
{
//spine::Atlas* l_pAtlas = new (__FILE__, __LINE__) spine::Atlas(l_pAtlasContent, l_iFileLength,UT::GetDirectoryWithoutFileName(e_strAtlasFile).c_str(), m_pTextureLoaderForSpine);
spine::Atlas* l_pAtlas = new (__FILE__, __LINE__) spine::Atlas(e_strAtlasFile, m_pTextureLoaderForSpine);
m_KeyAndAtlasMap[e_strAtlasFile] = l_pAtlas;
delete[] l_pAtlasContent;
return l_pAtlas;
}
}
return l_IT->second;
}
std::tuple<spine::Skeleton*, spine::AnimationState*, spine::Atlas*> cSpineCache::GetSpineData(const char* e_strFileName)
{
spine::Skeleton* l_pSkeleton = nullptr;
spine::AnimationState* l_pAnimationState = nullptr;
std::string l_strAtlasFileName = UT::ChangeFileExtensionName(e_strFileName, "atlas");
auto l_pAtlas = GetAtlas(l_strAtlasFileName.c_str());
if (l_pAtlas)
{
auto l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
auto l_KeyAndAnimationStateDataMapIT = m_KeyAndAnimationStateDataMap.find(e_strFileName);
if (l_KeyAndSkeletonDataMapIT == m_KeyAndSkeletonDataMap.end())
{
bool l_bBinary = !UT::GetFileExtensionName(e_strFileName).compare("json") ? false : true;
spine::SkeletonData*l_pSkeletonData = nullptr;
if(l_bBinary)
{
spine::SkeletonBinary binary(l_pAtlas);
l_pSkeletonData = binary.readSkeletonDataFile(e_strFileName);
}
else
{
spine::SkeletonJson json(l_pAtlas);
l_pSkeletonData = json.readSkeletonDataFile(e_strFileName);
}
m_KeyAndSkeletonDataMap[e_strFileName] = l_pSkeletonData;
l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
}
if (l_KeyAndAnimationStateDataMapIT == m_KeyAndAnimationStateDataMap.end())
{
auto l_pStateData = new (__FILE__, __LINE__) spine::AnimationStateData(l_KeyAndSkeletonDataMapIT->second);
m_KeyAndAnimationStateDataMap[e_strFileName] = l_pStateData;
l_KeyAndAnimationStateDataMapIT = m_KeyAndAnimationStateDataMap.find(e_strFileName);
}
l_pSkeleton = new (__FILE__, __LINE__) spine::Skeleton(l_KeyAndSkeletonDataMapIT->second);
l_pAnimationState = new (__FILE__, __LINE__) spine::AnimationState(l_KeyAndAnimationStateDataMapIT->second);
}
return std::make_tuple(l_pSkeleton, l_pAnimationState, l_pAtlas);
}
spine::SkeletonData* cSpineCache::GetSkeletonData(const char* e_strFileName, const char* e_strAtlasFileName)
{
std::string l_strAtlasFileName;
if (e_strAtlasFileName)
{
l_strAtlasFileName = e_strAtlasFileName;
}
else
{
l_strAtlasFileName = UT::ChangeFileExtensionName(e_strFileName, "atlas");
}
auto l_pAtlas = GetAtlas(l_strAtlasFileName.c_str());
if (l_pAtlas)
{
FMLOG("get atlas %s ok", l_strAtlasFileName.c_str());
auto l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
if (l_KeyAndSkeletonDataMapIT == m_KeyAndSkeletonDataMap.end())
{
bool l_bBinary = !UT::GetFileExtensionName(e_strFileName).compare("json") ? false : true;
spine::SkeletonData* l_pSkeletonData = nullptr;
if (l_bBinary)
{
spine::SkeletonBinary binary(l_pAtlas);
l_pSkeletonData = binary.readSkeletonDataFile(e_strFileName);
}
else
{
spine::SkeletonJson json(l_pAtlas);
l_pSkeletonData = json.readSkeletonDataFile(e_strFileName);
if (json.getError().length())
{
UT::ErrorMsg(json.getError().buffer(), "Error!");
}
}
if (l_pSkeletonData)
{
FMLOG("get skeleton data %s ok", e_strFileName);
}
else
{
FMLOG("get skeleton data %s failed", e_strFileName);
}
m_KeyAndSkeletonDataMap[e_strFileName] = l_pSkeletonData;
l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
}
return l_KeyAndSkeletonDataMapIT->second;
}
FMLOG("get atlas %s failed", l_strAtlasFileName.c_str());
return nullptr;
}
spine::Skeleton* cSpineCache::GetSkeleton(const char* e_strFileName)
{
spine::Skeleton* l_pSkeleton = nullptr;
std::string l_strAtlasFileName = UT::ChangeFileExtensionName(e_strFileName, "atlas");
auto l_pAtlas = GetAtlas(l_strAtlasFileName.c_str());
if (l_pAtlas)
{
auto l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
if (l_KeyAndSkeletonDataMapIT == m_KeyAndSkeletonDataMap.end())
{
bool l_bBinary = !UT::GetFileExtensionName(e_strFileName).compare("json") ? false : true;
spine::SkeletonData* l_pSkeletonData = nullptr;
if (l_bBinary)
{
spine::SkeletonBinary binary(l_pAtlas);
l_pSkeletonData = binary.readSkeletonDataFile(e_strFileName);
}
else
{
spine::SkeletonJson json(l_pAtlas);
l_pSkeletonData = json.readSkeletonDataFile(e_strFileName);
}
m_KeyAndSkeletonDataMap[e_strFileName] = l_pSkeletonData;
l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
}
l_pSkeleton = new (__FILE__, __LINE__) spine::Skeleton(l_KeyAndSkeletonDataMapIT->second);
}
return l_pSkeleton;
}
spine::AnimationState* cSpineCache::GetAnimationState(const char* e_strFileName)
{
spine::AnimationState* l_pAnimationState = nullptr;
std::string l_strAtlasFileName = UT::ChangeFileExtensionName(e_strFileName, "atlas");
auto l_pAtlas = GetAtlas(l_strAtlasFileName.c_str());
if (l_pAtlas)
{
auto l_KeyAndSkeletonDataMapIT = m_KeyAndSkeletonDataMap.find(e_strFileName);
auto l_KeyAndAnimationStateDataMapIT = m_KeyAndAnimationStateDataMap.find(e_strFileName);
if (l_KeyAndAnimationStateDataMapIT == m_KeyAndAnimationStateDataMap.end())
{
auto l_pStateData = new (__FILE__, __LINE__) spine::AnimationStateData(l_KeyAndSkeletonDataMapIT->second);
m_KeyAndAnimationStateDataMap[e_strFileName] = l_pStateData;
l_KeyAndAnimationStateDataMapIT = m_KeyAndAnimationStateDataMap.find(e_strFileName);
}
l_pAnimationState = new (__FILE__, __LINE__) spine::AnimationState(l_KeyAndAnimationStateDataMapIT->second);
}
return l_pAnimationState;
}
cSpineCache* g_pSpineCache = nullptr;
//spine-runtimes-4.0\spine-cocos2dx\src\spine\spine-cocos2dx.cpp
//http://en.esotericsoftware.com/spine-applying-animations#Applying-Animations
void SpineInit()
{
if (!g_pSpineCache)
{
g_pSpineCache = new cSpineCache();
}
}
SkeletonAnimation* g_pSkeletonAnimation = nullptr;
std::vector<std::string>* g_pAllSpineFileNameVector = nullptr;
//testData.add(TestData("spine/goblins/goblins/goblins-pro.json", "spine/goblins/goblins/goblins-pro.skel",
// "spine/goblins/goblins/goblins.atlas"));
int g_iCurrentSpineAnimationIndex = 0;
int g_iCurrentSpineSkinIndex = 0;
int g_iCurrentSpineFileIndex = 0;
std::wstring* g_pstrCurrentSpineInfo = nullptr;
void DoSpineKeyUp(unsigned char e_ucKeyUp);
void ComposeInfo()
{
if (g_pSkeletonAnimation)
{
auto l_AnimationVector = g_pSkeletonAnimation->getSkeleton()->getData()->getAnimations();
auto l_Skins = g_pSkeletonAnimation->getSkeleton()->getData()->getSkins();
auto l_strCurrentFileName = (*g_pAllSpineFileNameVector)[g_iCurrentSpineFileIndex];
auto l_strSkinName = l_Skins[g_iCurrentSpineSkinIndex]->getName().buffer();
auto l_strAnimationName = l_AnimationVector[g_iCurrentSpineAnimationIndex]->getName().buffer();
auto l_strInfo = UT::ComposeMsgByFormat("Q,E change file,A,D change animation,W,S change skin\nFileName:%s(%d/%d)\nSkin:%s(%d/%d)\nAnimation:%s(%d/%d)",
//UT::GetFileNameWithoutFullPath(l_strCurrentFileName).c_str(), g_iCurrentSpineFileIndex + 1, g_AllSpineFileNameVector.size(),
l_strCurrentFileName.c_str(), g_iCurrentSpineFileIndex + 1, g_pAllSpineFileNameVector->size(),
l_strSkinName, g_iCurrentSpineSkinIndex + 1, l_Skins.size(),
l_strAnimationName, g_iCurrentSpineAnimationIndex + 1, l_AnimationVector.size());
*g_pstrCurrentSpineInfo = ValueToStringW(l_strInfo);
}
else
{
*g_pstrCurrentSpineInfo = L"open spine/SpineTestDirectory.txt\n add diectory to this file.";
}
}
void testLoading()
{
//auto l_AllFiles = directory_iterator("spine");
auto l_strTargetFile = "Spine/SpinePreviewer.txt";
if (UT::IsFileExists(l_strTargetFile))
{
if (!g_pAllSpineFileNameVector)
{
g_pAllSpineFileNameVector = new std::vector<std::string>();
}
if (!g_pstrCurrentSpineInfo)
{
g_pstrCurrentSpineInfo = new std::wstring();
}
std::string l_strTestDirectory = GetTxtFileContent(l_strTargetFile);
try
{
auto l_AllFiles = std::filesystem::recursive_directory_iterator(l_strTestDirectory.c_str());
for (const auto& file : l_AllFiles)
{
auto l_strPath = file.path().c_str();
//CarServer_1__log_17_12_2021_10_57_56.txt
auto l_strFileName = UT::GetFileExtensionName(l_strPath);
//win32 use L?
//if (l_strFileName.compare(L"json") == 0 || l_strFileName.compare(L"skel") == 0)
if (l_strFileName.compare("json") == 0 || l_strFileName.compare("skel") == 0)
{
g_pAllSpineFileNameVector->push_back(ValueToString(l_strPath));
}
}
}
catch (std::exception e)
{
l_strTestDirectory = e.what() + l_strTestDirectory;
UT::ErrorMsg(+ l_strTestDirectory.c_str(), "Error");
}
}
if (g_pAllSpineFileNameVector->size())
{
g_iCurrentSpineFileIndex = 1;
DoSpineKeyUp('Q');
}
else
{
//spine::SkeletonData* l_pTestSkeleton = nullptr;
////l_pTestSkeleton = g_pSpineCache->GetSkeletonData("spine/dragon/dragon-ess.skel");
////l_pTestSkeleton = g_pSpineCache->GetSkeletonData("spine/Anim_Main_Rear.json");
//l_pTestSkeleton = g_pSpineCache->GetSkeletonData("spine/goblins/goblins-ess.skel","spine/goblins/goblins.atlas");
////l_pTestSkeleton = g_pSpineCache->GetSkeletonData("spine/10027/Anim_Main.json");
////auto l_pTestSkeleton = g_pSpineCache->GetSkeletonData("spine/10027/Anim_Jackpot_gold_ball_loop.json");
////getError();
////g_pSkeletonRenderer = SkeletonRenderer::createWithSkeleton(l_pTestSkeleton,true,true);
//if (l_pTestSkeleton)
//{
// g_pSkeletonAnimation = SkeletonAnimation::createWithData(l_pTestSkeleton, false);
// auto l_AnimationVector = g_pSkeletonAnimation->getSkeleton()->getData()->getAnimations();
// if (l_AnimationVector.size())
// {
// auto l_strName = l_AnimationVector[0]->getName().buffer();
// g_pSkeletonAnimation->setAnimation(0, l_strName, true);
// auto l_Skins = g_pSkeletonAnimation->getSkeleton()->getData()->getSkins();
// if (l_Skins.size())
// {
// g_pSkeletonAnimation->setSkin(l_Skins[l_Skins.size() > 1 ? 1 : 0]->getName().buffer());
// }
// }
//}
}
ComposeInfo();
}
namespace spine
{
SpineExtension* g_pDefaultExtension = nullptr;
SpineExtension* getDefaultExtension()
{
if (!g_pDefaultExtension)
{
g_pDefaultExtension = new DefaultSpineExtension();
}
return g_pDefaultExtension;
}
}//namespace spine
void SpineDestory()
{
SAFE_DELETE(g_pSkeletonAnimation);
SAFE_DELETE(g_pSpineCache);
SAFE_DELETE(spine::g_pDefaultExtension);
SAFE_DELETE(g_pAllSpineFileNameVector);
SAFE_DELETE(g_pstrCurrentSpineInfo);
}
void DoSpineTest()
{
testLoading();
}
void DoSpineKeyUp(unsigned char e_ucKeyUp)
{
int l_iNumFile = g_pAllSpineFileNameVector->size();
if (l_iNumFile)
//if (1)
{
int l_iPrevious = g_iCurrentSpineFileIndex;
if (e_ucKeyUp == 'Q')
{
g_iCurrentSpineFileIndex -= 1;
if (g_iCurrentSpineFileIndex < 0)
{
g_iCurrentSpineFileIndex = l_iNumFile - 1;
}
}
else
if (e_ucKeyUp == 'E')
{
g_iCurrentSpineFileIndex += 1;
if (g_iCurrentSpineFileIndex >= l_iNumFile)
{
g_iCurrentSpineFileIndex = 0;
}
}
if (g_iCurrentSpineFileIndex == 10)
{
int a = 0;
}
if (l_iPrevious != g_iCurrentSpineFileIndex)
{
SAFE_DELETE(g_pSkeletonAnimation);
auto l_pTestSkeleton = g_pSpineCache->GetSkeletonData((*g_pAllSpineFileNameVector)[g_iCurrentSpineFileIndex].c_str());
if (l_pTestSkeleton)
{
g_pSkeletonAnimation = SkeletonAnimation::createWithData(l_pTestSkeleton, false);
}
g_iCurrentSpineAnimationIndex = 0;
g_iCurrentSpineSkinIndex = 0;
}
}
else
{
return;
}
if (!g_pSkeletonAnimation)
{
return;
}
auto l_AnimationVector = g_pSkeletonAnimation->getSkeleton()->getData()->getAnimations();
auto l_Skins = g_pSkeletonAnimation->getSkeleton()->getData()->getSkins();
int l_iAnimationCount = (int)l_AnimationVector.size();
int l_iSkinCount = (int)l_Skins.size();
if(l_iSkinCount)
{
if (e_ucKeyUp == 'W')
{
g_iCurrentSpineSkinIndex -= 1;
if (g_iCurrentSpineSkinIndex < 0)
{
g_iCurrentSpineSkinIndex = l_iSkinCount - 1;
}
}
else
if (e_ucKeyUp == 'S')
{
g_iCurrentSpineSkinIndex += 1;
if (g_iCurrentSpineSkinIndex >= l_iSkinCount)
{
g_iCurrentSpineSkinIndex = 0;
}
}
g_pSkeletonAnimation->setSkin(l_Skins[g_iCurrentSpineSkinIndex]->getName().buffer());
}
if(l_iAnimationCount)
{
if (e_ucKeyUp == 'A')
{
g_iCurrentSpineAnimationIndex -= 1;
if (g_iCurrentSpineAnimationIndex < 0)
{
g_iCurrentSpineAnimationIndex = l_iAnimationCount - 1;
}
}
else
if (e_ucKeyUp == 'D')
{
g_iCurrentSpineAnimationIndex += 1;
if (g_iCurrentSpineAnimationIndex >= l_iAnimationCount)
{
g_iCurrentSpineAnimationIndex = 0;
}
}
auto l_strName = l_AnimationVector[g_iCurrentSpineAnimationIndex]->getName().buffer();
g_pSkeletonAnimation->setAnimation(0, l_strName, true);
}
auto l_strCurrentFileName = (*g_pAllSpineFileNameVector)[g_iCurrentSpineFileIndex];
auto l_strSkinName = l_Skins[g_iCurrentSpineSkinIndex]->getName().buffer();
auto l_strAnimationName = l_AnimationVector[g_iCurrentSpineAnimationIndex]->getName().buffer();
auto l_strInfo = UT::ComposeMsgByFormat("Q,E change file,A,D change animation,W,S change skin\nFileName:%s(%d/%d)\nSkin:%s(%d/%d)\nAnimation:%s(%d/%d)",
//UT::GetFileNameWithoutFullPath(l_strCurrentFileName).c_str(), g_iCurrentSpineFileIndex+1, g_AllSpineFileNameVector.size(),
l_strCurrentFileName.c_str(), g_iCurrentSpineFileIndex + 1, g_pAllSpineFileNameVector->size(),
l_strSkinName,g_iCurrentSpineSkinIndex+1, l_Skins.size(),
l_strAnimationName,g_iCurrentSpineAnimationIndex+1,l_AnimationVector.size());
*g_pstrCurrentSpineInfo = ValueToStringW(l_strInfo);
}
void DoSpineRender()
{
if (g_pSkeletonAnimation)
{
//g_pSkeletonAnimation->SetWorldPosition(Vector3(1920, 1080, 0));
//g_pSkeletonAnimation->SetWorldPosition(Vector3(500, 500, 0));
//g_pSkeletonAnimation->SetWorldTransform(cMatrix44::TranslationMatrix(Vector3(1920,750, 0))*cMatrix44::ZAxisRotationMatrix(D3DX_PI) * cMatrix44::ScaleMatrix(Vector3(2, 2, 2)));
g_pSkeletonAnimation->SetWorldTransform(cMatrix44::TranslationMatrix(Vector3(1320, 750, 0)) * cMatrix44::ZAxisRotationMatrix(D3DX_PI)* cMatrix44::YAxisRotationMatrix(D3DX_PI) * cMatrix44::ScaleMatrix(Vector3(1,1,1)));//
//g_pSkeletonAnimation->SetWorldTransform(cMatrix44::TranslationMatrix(Vector3(900, 750, 0)) * cMatrix44::ZAxisRotationMatrix(D3DX_PI) * cMatrix44::ScaleMatrix(Vector3(2, 2, 2)));
g_pSkeletonAnimation->Update(0.016f);
g_pSkeletonAnimation->Render();
//g_pSkeletonAnimation->DebugRender();
}
if (cGameApp::m_spGlyphFontRender)
{
cGameApp::m_spGlyphFontRender->SetScale(1.5);
cGameApp::RenderFont(320, 0, ValueToStringW(*g_pstrCurrentSpineInfo));
cGameApp::m_spGlyphFontRender->SetScale(1);
}
} |
3bd981326d103003b158bd546cc08a2bb20f7970 | 015b33912513b609263da043d2f85bb480290175 | /pca_1.0.cpp | 7aad4826e99a30d669821a3ca0f71ea2bbd2c8cd | [
"MIT"
] | permissive | gamer240/pls-cpp-octave | 4614b18ec49ff78ae583dfc3d5487aa967bbeb4e | d288c55490e35bdedb75993392bc304a4ede80b8 | refs/heads/master | 2021-01-20T22:05:13.667768 | 2016-07-12T04:52:16 | 2016-07-12T04:52:16 | 63,126,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,821 | cpp | pca_1.0.cpp | #include<stdio.h>
#include<iostream>
#include<math.h>
#include<Eigen/Eigen>
#define rows 9
#define columns 4
using namespace Eigen;
using namespace std;
float calc_cov (int a, int b,float array_minusmean[rows][columns]) {
float product=0.00000;
float product_sum=0.00000;
for (int i=0;i<rows;i++){
product=array_minusmean[i][a]*array_minusmean[i][b];
product_sum+=product;
product=0;
}
float covariance= product_sum/(rows-1);
return covariance;
}
int main(){
float input_matrix[rows][columns],sum=0,avg=0,mean_diff=0,mean_diff_sq=0,mean_diff_sq_sum=0;
float mean[columns]={0.00000};
float std_dev[columns]={0.00000};
float std_data[rows][columns];
float cov_mat_std[columns][columns];
float std_data_mean[columns]={0.00000};
float std_data_minusmean[rows][columns];
float input_matrix_minusmean[rows][columns];
float cov_mat_input[columns][columns];
// input matrix data
for (int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
cin>>input_matrix[i][j];
}
}
// input data arithimetic mean
for (int j=0;j<columns;j++){
for (int i=0;i<rows;i++){
sum=sum+input_matrix[i][j];
}
avg=sum/rows;
mean[j]=avg;
sum=0;
}
// std dev of input data
for (int j=0;j<columns;j++){
for (int i=0;i<rows;i++){
mean_diff=input_matrix[i][j]-mean[j];
mean_diff_sq= pow(mean_diff,2);
mean_diff_sq_sum+=mean_diff_sq;
}
std_dev[j]=sqrt(mean_diff_sq_sum/(rows-1));
mean_diff_sq_sum=0;
}
// standardize the data
for (int j=0;j<columns;j++){
for (int i=0;i<rows;i++){
mean_diff=input_matrix[i][j]-mean[j];
std_data[i][j]=mean_diff/std_dev[j];
}
}
// mean of std data
for (int j=0;j<columns;j++){
for (int i=0;i<rows;i++){
sum=sum+std_data[i][j];
}
avg=sum/rows;
std_data_mean[j]=avg;
sum=0;
}
// std data minus mean from each observation
for (int j=0;j<columns;j++){
for(int i=0;i<rows;i++){
std_data_minusmean[i][j]=std_data[i][j]-std_data_mean[j];
}
}
// input data minus mean from each obs
for (int j=0;j<columns;j++){
for(int i=0;i<rows;i++){
input_matrix_minusmean[i][j]=input_matrix[i][j]-mean[j];
}
}
// covariance of std data
for (int i=0;i<columns;i++){
for (int j=0;j<columns;j++){
cov_mat_std[i][j]=calc_cov(i,j,std_data_minusmean);
}
}
// covariance of input data
for (int i=0;i<columns;i++){
for (int j=0;j<columns;j++){
cov_mat_input[i][j]=calc_cov(i,j,input_matrix_minusmean);
}
}
typedef float myptr[columns][columns];
myptr*ptr_inputcov;
myptr*ptr_stdcov;
ptr_inputcov=&cov_mat_input;// pointer to 2d array of cov_mat_input
ptr_stdcov=&cov_mat_std;//pointer to 2d array of cov_mat_std
MatrixXf eigen_inputcov(columns,columns);
memcpy(eigen_inputcov.data(),ptr_inputcov, sizeof(float)*columns*columns);
MatrixXf eigen_stdcov(columns,columns);
memcpy(eigen_stdcov.data(),ptr_stdcov, sizeof(float)*columns*columns);
EigenSolver<MatrixXf> es(eigen_stdcov);
MatrixXcf eigenvectors_std =es.eigenvectors();
VectorXcf eigenvalues_std = es.eigenvalues();
EigenSolver<MatrixXf> es1(eigen_inputcov);
MatrixXcf eigenvectors_input =es1.eigenvectors();
VectorXcf eigenvalues_input = es1.eigenvalues();
cout<<eigenvectors_std;
cout<<endl<<"========================================================================================================================================================="<<endl;
cout<<eigenvalues_std<<endl<<endl;
/*for (int i=0;i<rows;i++){
for (int j=0;j<columns;j++){
cout<<std_data[i][j];
}
cout<<endl;
}
*/
return 0;
}
|
4f59d953ea850def579b4045fd5148e02c39fc5f | 2e3d4537e4fc5fd25a20c54c8f51928b65708ec2 | /Curves v1.0/main.cpp | 568aba9bdd116fed36578adf4d82ff6e31cbe1e9 | [] | no_license | micura/Computer-Graphics-programs | 3b64eb74bda13a29c87f8e6a0a72349cb0ec8bfa | 4927e3f8523a98aa95448eaa9054e47c2e158bfd | refs/heads/master | 2021-01-14T04:29:33.638632 | 2020-02-24T00:15:56 | 2020-02-24T00:15:56 | 242,600,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,046 | cpp | main.cpp | #include "freeglut/include/GL/glut.h"
#include "bevgrafmath2017.h"
#include <math.h>
GLsizei winWidth = 900, winHeight = 750;
float t1 = -2.0;
float t2 = 0.5;
float t3 = 1.5;
float z = 0.5;
#define N 11 // Pontok száma
vec2 Points[N] = {
{ 100, 600 }, //P0
{ 400, 650 }, //P1
{ 600, 550 }, //P2
{ 150, 725 }, //P3 - e0
//P4 -- a program számolja
{ 0, 0 },
{ 750, 400 }, //P5
{ 500, 380 }, //P6
//P7 -- a program számolja
{ 0, 0 },
{ 150, 250 }, //P8
{ 400, 100 }, //P9
{ 750, 150 }, //P10
};
GLint dragged = -1;
class De_casteljau
{
public:
GLfloat x, y;
float vegpont_x = Points[6].x + 0.75*(Points[6].x - Points[5].x);
float vegpont_y = Points[6].y + 0.75*(Points[6].y - Points[5].y);
vec2 D[5] =
{
{ Points[6].x, Points[6].y },
{ vegpont_x, vegpont_y },
{ Points[8].x, Points[8].y },
{ Points[9].x, Points[9].y },
{ Points[10].x, Points[10].y },
};
vec2 iv(float t)
{
vec2 V[5];
for (int i = 0; i < 5; i++) {
V[i] = D[i];
}
vec2 tomb[1];
int n = 4;
for (int r = 0; r < 4; r++)
{
for (int i = 0; i < n; i++)
{
V[i].x = tomb[0].x = (1 - t) * V[i].x + t * V[i + 1].x;
V[i].y = tomb[0].y = (1 - t) * V[i].y + t * V[i + 1].y;
}
n--;
}
return tomb[0];
}
void vaz()
{
vec2 C[5];
for (int i = 0; i < 5; i++) {
C[i] = D[i];
}
int n = 4;
for (int r = 0; r < 4; r++)
{
glBegin(GL_LINE_STRIP);
for (int i = 0; i < n; i++)
{
C[i].x = x = (1 - z) * C[i].x + z * C[i + 1].x;
C[i].y = y = (1 - z) * C[i].y + z * C[i + 1].y;
glVertex2f(x, y);
}
glEnd();
n--;
}
}
void pontok()
{
int n = 4;
for (int r = 0; r < 4; r++)
{
glBegin(GL_POINTS);
for (int i = 0; i < n; i++)
{
if (n == 1)
{
glColor3f(0.5f, 0.0f, 0.3f);
}
D[i].x = x = (1 - z) * D[i].x + z * D[i + 1].x;
D[i].y = y = (1 - z) * D[i].y + z * D[i + 1].y;
glVertex2i(x, y);
}
glEnd();
n--;
}
}
};
void ControlPoints()
{
GLint i;
glColor3f(1.0f, 0.0f, 1.0f);
glBegin(GL_POINTS);
for (i = 0; i < N; i++)
{
glVertex2f(Points[i].x, Points[i].y);
}
glEnd();
glFlush();
}
void gorbek()
{
//===========================Hermite iv===========================//
glLineWidth(2.0);
glColor3f(0.0f, 0.0f, 0.0f);
GLfloat H[4];
GLfloat e2x;
GLfloat e2y;
glBegin(GL_LINE_STRIP);
for (float t = t1; t <= t3; t += 0.01) {
//Ez a G
mat24 G = {
Points[0].x, Points[1].x, Points[2].x, Points[3].x - Points[0].x,
Points[0].y, Points[1].y, Points[2].y, Points[3].y - Points[0].y,
};
//Ez az M
mat4 M = {
t1*t1*t1, t2*t2*t2, t3*t3*t3, 3 * t1*t1,
t1*t1, t2*t2, t3*t3, 2 * t1,
t1, t2, t3, 1.0,
1.0, 1.0, 1.0, 0.0
};
//Ez a T
GLfloat u1 = t;
GLfloat u2 = u1*u1;
GLfloat u3 = u2*u1;
//C = G * M //2x4
mat24 C = G*inverse(M);
GLfloat x = 0.0;
GLfloat y = 0.0;
e2x = C[0][0] * (3 * t * t) + C[0][1] * (2 * t) + C[0][2] * 1.0 + C[0][3] * 0.0;
e2y = C[1][0] * (3 * t * t) + C[1][1] * (2 * t) + C[1][2] * 1.0 + C[1][3] * 0.0;
x += C[0][0] * u3;
y += C[1][0] * u3;
x += C[0][1] * u2;
y += C[1][1] * u2;
x += C[0][2] * u1;
y += C[1][2] * u1;
x += C[0][3] * 1.0;
y += C[1][3] * 1.0;
glVertex2f(x, y);
}
glEnd();
//Hermite iv-hez tartozó érintők
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_POINTS);
glVertex2i(Points[2].x + e2x, Points[2].y + e2y);
glEnd();
glColor3f(1.0f, 0.0f, 0.0f);
glLineWidth(2.0);
glBegin(GL_LINES);
glVertex2i(Points[0].x, Points[0].y);
glVertex2i(Points[3].x, Points[3].y);
glVertex2i(Points[2].x, Points[2].y);
glVertex2i(Points[2].x + e2x, Points[2].y + e2y);
glEnd();
//===========================Bezier görbe===========================//
glLineWidth(2.0);
glColor3f(0.0, 0.0, 1.0);
GLfloat B[4];
mat24 GB;
glBegin(GL_LINE_STRIP);
for (float t = 0; t <= 1.0; t += 0.01) {
GLfloat u1 = t;
GLfloat u2 = u1*u1;
GLfloat u3 = u2*u1;
//Ez a GB
GB = {
Points[2].x, Points[2].x + (e2x / 3), Points[5].x, Points[6].x,
Points[2].y, Points[2].y + (e2y / 3), Points[5].y, Points[6].y,
};
//Ez az MB
mat4 MB = {
-1.0, 3.0, -3.0, 1.0,
3.0, -6.0, 3.0, 0.0,
-3.0, 3.0, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0
};
//MB*T
B[0] = MB[0][0] * u3 + MB[0][1] * u2 + MB[0][2] * u1 + MB[0][3] * 1.0;
B[1] = MB[1][0] * u3 + MB[1][1] * u2 + MB[1][2] * u1 + MB[1][3] * 1.0;
B[2] = MB[2][0] * u3 + MB[2][1] * u2 + MB[2][2] * u1 + MB[2][3] * 1.0;
B[3] = MB[3][0] * u3 + MB[3][1] * u2 + MB[3][2] * u1 + MB[3][3] * 1.0;
GLfloat x = 0.0;
GLfloat y = 0.0;
for (int i = 0; i<4; i++) {
x += B[i] * GB[0][i];
y += B[i] * GB[1][i];
}
glVertex2f(x, y);
}
glEnd();
glFlush();
//Bezier iv-hez tartozó érintők, és pontok
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_POINTS);
glVertex2f(GB[0][1], GB[1][1]);
glVertex2f(Points[2].x + e2x, Points[2].y + e2y);
//Végpontbeli
glVertex2f(Points[6].x + 0.75*(Points[6].x - Points[5].x),
Points[6].y + 0.75*(Points[6].y - Points[5].y)),
glEnd();
glColor3f(0.0f, 1.0f, 0.0f);
glLineWidth(2.0);
glBegin(GL_LINES);
glVertex2f(GB[0][1], GB[1][1]);
glVertex2i(Points[5].x, Points[5].y);
glVertex2f(Points[5].x, Points[5].y);
glVertex2f(Points[6].x, Points[6].y);
glColor3f(0.0f, 0.0f, 0.0f);
glVertex2f(Points[6].x, Points[6].y);
glVertex2f(Points[6].x + 0.75*(Points[6].x - Points[5].x),
Points[6].y + 0.75*(Points[6].y - Points[5].y)),
glEnd();
//===========================Öt kontrollpontos Bezier===========================//
De_casteljau casteljau; //Példányosítunk
GLfloat x, y = 0;
//Kössük össze a pontokat(konvex burok)
glColor3f(0.2f, 0.2f, 0.2f);
glBegin(GL_LINES);
for (int j = 0; j < 4; j++) {
glVertex2f(casteljau.D[j].x, casteljau.D[j].y);
glVertex2f(casteljau.D[j + 1].x, casteljau.D[j + 1].y);
}
glEnd();
//Rajzoljuk meg az ívet
glColor3f(0.6f, 0.0f, 0.5f);
glBegin(GL_LINE_STRIP);
for (float t = 0; t <= 1.0; t += 0.01) {
x = casteljau.iv(t).x;
y = casteljau.iv(t).y;
glVertex2f(x, y);
}
glEnd();
//Rajzoljuk meg a vázat
glColor3f(0.6f, 0.0f, 0.5f);
casteljau.vaz();
glColor3f(0.9f, 0.0f, 0.1f);
casteljau.pontok();
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 27:
exit(0);
break;
case '+':
if (z < 0.99) {
z += 0.01;
}
break;
case '-':
if (z > 0.01) {
z -= 0.01;
}
break;
glutPostRedisplay();
}
}
void init() {
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, winWidth, 0.0, winHeight);
glShadeModel(GL_FLAT);
glEnable(GL_POINT_SMOOTH);
glPointSize(8.0);
glLineWidth(5.0);
glLineStipple(1, 0xFF00);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
gorbek();
ControlPoints();
glutSwapBuffers();
}
GLint getActivePoint1(vec2 p[], GLint size, GLint sens, GLint x, GLint y) {
GLint i, s = sens * sens;
vec2 P = { (float)x, (float)y };
for (i = 0; i < size; i++)
if (dist2(p[i], P) < s)
return i;
return -1;
}
void processMouse(GLint button, GLint action, GLint xMouse, GLint yMouse) {
GLint i;
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN)
if ((i = getActivePoint1(Points, 11, 20, xMouse, winHeight - yMouse)) != -1)
dragged = i;
if (button == GLUT_LEFT_BUTTON && action == GLUT_UP)
dragged = -1;
}
void processMouseActiveMotion(GLint xMouse, GLint yMouse) {
GLint i;
if (dragged >= 0) {
Points[dragged].x = xMouse;
Points[dragged].y = winHeight - yMouse;
glutPostRedisplay();
}
}
void update(int n) {
glutPostRedisplay();
glutTimerFunc(10, update, 0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(winWidth, winHeight);
glutInitWindowPosition(300, 0);
glutCreateWindow("Curves");
init();
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
glutMouseFunc(processMouse);
glutMotionFunc(processMouseActiveMotion);
glutTimerFunc(10, update, 0);
glutMainLoop();
return 0;
} |
4bf3b68835b4d2daa04532fe530c10d1aaac593a | f3c134a598dd76a94b07aba0fcdafa4c12b23c65 | /src/dcoady/ctype/line.cpp | f97d52b2335f5e0ffe190672653d42891b5c6ec1 | [] | no_license | deniscoady/wikidata-filter | e2805fa62c3fc29b23e66efaf93e95bb398171a1 | 3fdf79ed3e7cb5bbae35f41e28f075dd2a020625 | refs/heads/master | 2023-04-07T21:26:00.027057 | 2015-10-05T02:59:59 | 2015-10-05T02:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 330 | cpp | line.cpp | #include <dcoady/ctype/line.h>
namespace dcoady {
namespace ctype {
line::line()
: std::ctype<char>(get_table())
{
}
std::ctype_base::mask const* line::get_table()
{
static std::vector<std::ctype_base::mask>
rc(table_size, std::ctype_base::mask());
rc['\n'] = std::ctype_base::space;
return &rc[0];
}
}} |
8cc80db9fcbc2bb25c618c5a09a4ebba81ed98d7 | 9c7f6d30ea51747f77132c7e969d7da1398cab3a | /pointers_2.cpp | 831fcded4ab1e89593ffda25ae4086ecea824e15 | [] | no_license | juanchuletas/U_CplusplusCourse | 37e2995150045ee3623bed4b6889d3e49b8903ce | 47bb13814302a5417a170fbd1cd8668f26441b3a | refs/heads/master | 2020-10-01T02:12:27.659472 | 2019-12-11T19:49:23 | 2019-12-11T19:49:23 | 227,430,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | pointers_2.cpp | #include<iostream>
#include<string>
#include <sstream>
int main()
{
int givenInt;
float givenFloat;
double givenDouble;
std::string givenString;
char givenChar;
std::cin>>givenInt;
std::cin>>givenFloat;
std::cin>>givenDouble;
//We need to use cin.ignore so cin will ignore
//the characters in the buffer leftover
//from the givenDouble
std::cin.ignore();
std::cin>>givenChar;
std::cin.ignore();
std::getline(std::cin,givenString);
std::cout<<"The value of intVal is = "<<givenInt<<"\n";
std::cout<<"The addressof intVal is = "<<&givenInt<<"\n";
std::cout<<"The value of stringVal is = "<<givenString<<"\n";
std::cout<<"The addressof stringVal is = "<<&givenString<<"\n";
return 0;
}
|
16f1499169f2ac332f43d92da51624e3c1eff2bc | 5499e8b91353ef910d2514c8a57a80565ba6f05b | /zircon/system/ulib/fs/include/fs/ticker.h | e560c2a5d2fb91cbb90512d1fd4170c26a47f485 | [
"BSD-3-Clause",
"MIT"
] | permissive | winksaville/fuchsia | 410f451b8dfc671f6372cb3de6ff0165a2ef30ec | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | refs/heads/master | 2022-11-01T11:57:38.343655 | 2019-11-01T17:06:19 | 2019-11-01T17:06:19 | 223,695,500 | 3 | 2 | BSD-3-Clause | 2022-10-13T13:47:02 | 2019-11-24T05:08:59 | C++ | UTF-8 | C++ | false | false | 1,442 | h | ticker.h | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains a helper for gathering metrics timing info.
#pragma once
#ifdef __Fuchsia__
#include <lib/zx/time.h>
#endif
// Compile-time option to enable metrics collection globally. On by default.
#define ENABLE_METRICS
#if defined(__Fuchsia__) && defined(ENABLE_METRICS)
#define FS_WITH_METRICS
#endif
namespace fs {
#ifdef FS_WITH_METRICS
// Helper class for getting the duration of events.
typedef zx::ticks Duration;
class Ticker {
public:
explicit Ticker(bool collecting_metrics)
: ticks_(collecting_metrics ? zx::ticks::now() : zx::ticks()) {}
void Reset() {
if (ticks_.get() == 0) {
return;
}
ticks_ = zx::ticks::now();
}
// Returns '0' for duration if collecting_metrics is false,
// preventing an unnecessary syscall.
//
// Otherwise, returns the time since either the constructor
// or the last call to reset (whichever was more recent).
Duration End() const {
if (ticks_.get() == 0) {
return zx::ticks();
}
return zx::ticks::now() - ticks_;
}
private:
zx::ticks ticks_;
};
#else
// Null implementation for host-side code.
class Duration {};
class Ticker {
public:
Ticker(bool) {}
void Reset();
Duration End() const { return Duration(); }
};
#endif
} // namespace fs
|
c8ba193056628d92b6602e8d496fc2a039b4317b | 2cb592c546ec8f6116339653fbf3b7c61a59717b | /Game3.0/Game/Game/GameConsole.h | f81da06989ba31fd3d7a065a2faac38716092adf | [] | no_license | TO-OTR/BRICK-UTSEUS-2018LO02 | 063790155fb079cadbb78a050d49b3e13b57dfdf | f05f401284bfaa4009c86068965b68a7304d1ee9 | refs/heads/master | 2020-04-04T16:33:32.430726 | 2018-12-18T08:02:51 | 2018-12-18T08:02:51 | 156,082,845 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | h | GameConsole.h | #pragma once
#include "console.h"
#include "Barre.h"
class GameConsole :
public Console
{
public:
GameConsole(void);
~GameConsole(void);
void onKeyPressed(WORD keyCode);
void setBarre(Barre &_barre);
private:
Barre *barre;
};
|
8dec0ad476bdae1b5ee7db5858e47e18dd236474 | 89709aec3b162770ffdb6b28efd461e678e5fd2f | /udp/src/models/base_datagram.pb.h | ed4ade9939d887b4da1df5c44002d4a13e812da4 | [
"MIT"
] | permissive | sunshinfight/socketme | dea37d88cf133f9c2313edc452a5c4de3f930371 | cd39d0da42fffe1293fde8a707f681d0c895458a | refs/heads/master | 2022-05-25T23:11:25.912676 | 2020-04-22T14:05:29 | 2020-04-22T14:05:29 | 257,916,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 45,826 | h | base_datagram.pb.h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: base_datagram.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_base_5fdatagram_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_base_5fdatagram_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3011000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3011004 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_base_5fdatagram_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_base_5fdatagram_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[5]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_base_5fdatagram_2eproto;
namespace jx {
class BaseDatagram;
class BaseDatagramDefaultTypeInternal;
extern BaseDatagramDefaultTypeInternal _BaseDatagram_default_instance_;
class ContactTran;
class ContactTranDefaultTypeInternal;
extern ContactTranDefaultTypeInternal _ContactTran_default_instance_;
class ContactsContent;
class ContactsContentDefaultTypeInternal;
extern ContactsContentDefaultTypeInternal _ContactsContent_default_instance_;
class MsgContent;
class MsgContentDefaultTypeInternal;
extern MsgContentDefaultTypeInternal _MsgContent_default_instance_;
class TextContent;
class TextContentDefaultTypeInternal;
extern TextContentDefaultTypeInternal _TextContent_default_instance_;
} // namespace jx
PROTOBUF_NAMESPACE_OPEN
template<> ::jx::BaseDatagram* Arena::CreateMaybeMessage<::jx::BaseDatagram>(Arena*);
template<> ::jx::ContactTran* Arena::CreateMaybeMessage<::jx::ContactTran>(Arena*);
template<> ::jx::ContactsContent* Arena::CreateMaybeMessage<::jx::ContactsContent>(Arena*);
template<> ::jx::MsgContent* Arena::CreateMaybeMessage<::jx::MsgContent>(Arena*);
template<> ::jx::TextContent* Arena::CreateMaybeMessage<::jx::TextContent>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace jx {
enum BaseDatagramHeader : int {
ContactHeader = 0,
HelloHeader = 1,
MsgHeader = 2,
TextHeader = 3,
BaseDatagramHeader_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(),
BaseDatagramHeader_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max()
};
bool BaseDatagramHeader_IsValid(int value);
constexpr BaseDatagramHeader BaseDatagramHeader_MIN = ContactHeader;
constexpr BaseDatagramHeader BaseDatagramHeader_MAX = TextHeader;
constexpr int BaseDatagramHeader_ARRAYSIZE = BaseDatagramHeader_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* BaseDatagramHeader_descriptor();
template<typename T>
inline const std::string& BaseDatagramHeader_Name(T enum_t_value) {
static_assert(::std::is_same<T, BaseDatagramHeader>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function BaseDatagramHeader_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
BaseDatagramHeader_descriptor(), enum_t_value);
}
inline bool BaseDatagramHeader_Parse(
const std::string& name, BaseDatagramHeader* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<BaseDatagramHeader>(
BaseDatagramHeader_descriptor(), name, value);
}
// ===================================================================
class ContactTran :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:jx.ContactTran) */ {
public:
ContactTran();
virtual ~ContactTran();
ContactTran(const ContactTran& from);
ContactTran(ContactTran&& from) noexcept
: ContactTran() {
*this = ::std::move(from);
}
inline ContactTran& operator=(const ContactTran& from) {
CopyFrom(from);
return *this;
}
inline ContactTran& operator=(ContactTran&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ContactTran& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ContactTran* internal_default_instance() {
return reinterpret_cast<const ContactTran*>(
&_ContactTran_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(ContactTran& a, ContactTran& b) {
a.Swap(&b);
}
inline void Swap(ContactTran* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ContactTran* New() const final {
return CreateMaybeMessage<ContactTran>(nullptr);
}
ContactTran* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ContactTran>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ContactTran& from);
void MergeFrom(const ContactTran& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ContactTran* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "jx.ContactTran";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_base_5fdatagram_2eproto);
return ::descriptor_table_base_5fdatagram_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kIpFieldNumber = 1,
kPortFieldNumber = 2,
kUserIdFieldNumber = 3,
};
// int32 ip = 1;
void clear_ip();
::PROTOBUF_NAMESPACE_ID::int32 ip() const;
void set_ip(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_ip() const;
void _internal_set_ip(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// int32 port = 2;
void clear_port();
::PROTOBUF_NAMESPACE_ID::int32 port() const;
void set_port(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_port() const;
void _internal_set_port(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// int32 userId = 3;
void clear_userid();
::PROTOBUF_NAMESPACE_ID::int32 userid() const;
void set_userid(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_userid() const;
void _internal_set_userid(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:jx.ContactTran)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::int32 ip_;
::PROTOBUF_NAMESPACE_ID::int32 port_;
::PROTOBUF_NAMESPACE_ID::int32 userid_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_base_5fdatagram_2eproto;
};
// -------------------------------------------------------------------
class MsgContent :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:jx.MsgContent) */ {
public:
MsgContent();
virtual ~MsgContent();
MsgContent(const MsgContent& from);
MsgContent(MsgContent&& from) noexcept
: MsgContent() {
*this = ::std::move(from);
}
inline MsgContent& operator=(const MsgContent& from) {
CopyFrom(from);
return *this;
}
inline MsgContent& operator=(MsgContent&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const MsgContent& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const MsgContent* internal_default_instance() {
return reinterpret_cast<const MsgContent*>(
&_MsgContent_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(MsgContent& a, MsgContent& b) {
a.Swap(&b);
}
inline void Swap(MsgContent* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline MsgContent* New() const final {
return CreateMaybeMessage<MsgContent>(nullptr);
}
MsgContent* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<MsgContent>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const MsgContent& from);
void MergeFrom(const MsgContent& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(MsgContent* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "jx.MsgContent";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_base_5fdatagram_2eproto);
return ::descriptor_table_base_5fdatagram_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kMsgBodyFieldNumber = 1,
};
// repeated bytes msgBody = 1;
int msgbody_size() const;
private:
int _internal_msgbody_size() const;
public:
void clear_msgbody();
const std::string& msgbody(int index) const;
std::string* mutable_msgbody(int index);
void set_msgbody(int index, const std::string& value);
void set_msgbody(int index, std::string&& value);
void set_msgbody(int index, const char* value);
void set_msgbody(int index, const void* value, size_t size);
std::string* add_msgbody();
void add_msgbody(const std::string& value);
void add_msgbody(std::string&& value);
void add_msgbody(const char* value);
void add_msgbody(const void* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& msgbody() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_msgbody();
private:
const std::string& _internal_msgbody(int index) const;
std::string* _internal_add_msgbody();
public:
// @@protoc_insertion_point(class_scope:jx.MsgContent)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> msgbody_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_base_5fdatagram_2eproto;
};
// -------------------------------------------------------------------
class TextContent :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:jx.TextContent) */ {
public:
TextContent();
virtual ~TextContent();
TextContent(const TextContent& from);
TextContent(TextContent&& from) noexcept
: TextContent() {
*this = ::std::move(from);
}
inline TextContent& operator=(const TextContent& from) {
CopyFrom(from);
return *this;
}
inline TextContent& operator=(TextContent&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TextContent& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const TextContent* internal_default_instance() {
return reinterpret_cast<const TextContent*>(
&_TextContent_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
friend void swap(TextContent& a, TextContent& b) {
a.Swap(&b);
}
inline void Swap(TextContent* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TextContent* New() const final {
return CreateMaybeMessage<TextContent>(nullptr);
}
TextContent* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TextContent>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TextContent& from);
void MergeFrom(const TextContent& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TextContent* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "jx.TextContent";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_base_5fdatagram_2eproto);
return ::descriptor_table_base_5fdatagram_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kTextBodyFieldNumber = 1,
};
// string textBody = 1;
void clear_textbody();
const std::string& textbody() const;
void set_textbody(const std::string& value);
void set_textbody(std::string&& value);
void set_textbody(const char* value);
void set_textbody(const char* value, size_t size);
std::string* mutable_textbody();
std::string* release_textbody();
void set_allocated_textbody(std::string* textbody);
private:
const std::string& _internal_textbody() const;
void _internal_set_textbody(const std::string& value);
std::string* _internal_mutable_textbody();
public:
// @@protoc_insertion_point(class_scope:jx.TextContent)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr textbody_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_base_5fdatagram_2eproto;
};
// -------------------------------------------------------------------
class ContactsContent :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:jx.ContactsContent) */ {
public:
ContactsContent();
virtual ~ContactsContent();
ContactsContent(const ContactsContent& from);
ContactsContent(ContactsContent&& from) noexcept
: ContactsContent() {
*this = ::std::move(from);
}
inline ContactsContent& operator=(const ContactsContent& from) {
CopyFrom(from);
return *this;
}
inline ContactsContent& operator=(ContactsContent&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const ContactsContent& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ContactsContent* internal_default_instance() {
return reinterpret_cast<const ContactsContent*>(
&_ContactsContent_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
friend void swap(ContactsContent& a, ContactsContent& b) {
a.Swap(&b);
}
inline void Swap(ContactsContent* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ContactsContent* New() const final {
return CreateMaybeMessage<ContactsContent>(nullptr);
}
ContactsContent* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ContactsContent>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const ContactsContent& from);
void MergeFrom(const ContactsContent& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ContactsContent* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "jx.ContactsContent";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_base_5fdatagram_2eproto);
return ::descriptor_table_base_5fdatagram_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kContactFieldNumber = 1,
};
// repeated .jx.ContactTran contact = 1;
int contact_size() const;
private:
int _internal_contact_size() const;
public:
void clear_contact();
::jx::ContactTran* mutable_contact(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::jx::ContactTran >*
mutable_contact();
private:
const ::jx::ContactTran& _internal_contact(int index) const;
::jx::ContactTran* _internal_add_contact();
public:
const ::jx::ContactTran& contact(int index) const;
::jx::ContactTran* add_contact();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::jx::ContactTran >&
contact() const;
// @@protoc_insertion_point(class_scope:jx.ContactsContent)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::jx::ContactTran > contact_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_base_5fdatagram_2eproto;
};
// -------------------------------------------------------------------
class BaseDatagram :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:jx.BaseDatagram) */ {
public:
BaseDatagram();
virtual ~BaseDatagram();
BaseDatagram(const BaseDatagram& from);
BaseDatagram(BaseDatagram&& from) noexcept
: BaseDatagram() {
*this = ::std::move(from);
}
inline BaseDatagram& operator=(const BaseDatagram& from) {
CopyFrom(from);
return *this;
}
inline BaseDatagram& operator=(BaseDatagram&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const BaseDatagram& default_instance();
enum ContentCase {
kMsg = 2,
kContacts = 3,
kText = 4,
CONTENT_NOT_SET = 0,
};
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const BaseDatagram* internal_default_instance() {
return reinterpret_cast<const BaseDatagram*>(
&_BaseDatagram_default_instance_);
}
static constexpr int kIndexInFileMessages =
4;
friend void swap(BaseDatagram& a, BaseDatagram& b) {
a.Swap(&b);
}
inline void Swap(BaseDatagram* other) {
if (other == this) return;
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline BaseDatagram* New() const final {
return CreateMaybeMessage<BaseDatagram>(nullptr);
}
BaseDatagram* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<BaseDatagram>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const BaseDatagram& from);
void MergeFrom(const BaseDatagram& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(BaseDatagram* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "jx.BaseDatagram";
}
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return nullptr;
}
inline void* MaybeArenaPtr() const {
return nullptr;
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_base_5fdatagram_2eproto);
return ::descriptor_table_base_5fdatagram_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kHeaderFieldNumber = 1,
kMsgFieldNumber = 2,
kContactsFieldNumber = 3,
kTextFieldNumber = 4,
};
// .jx.BaseDatagramHeader header = 1;
void clear_header();
::jx::BaseDatagramHeader header() const;
void set_header(::jx::BaseDatagramHeader value);
private:
::jx::BaseDatagramHeader _internal_header() const;
void _internal_set_header(::jx::BaseDatagramHeader value);
public:
// .jx.MsgContent msg = 2;
bool has_msg() const;
private:
bool _internal_has_msg() const;
public:
void clear_msg();
const ::jx::MsgContent& msg() const;
::jx::MsgContent* release_msg();
::jx::MsgContent* mutable_msg();
void set_allocated_msg(::jx::MsgContent* msg);
private:
const ::jx::MsgContent& _internal_msg() const;
::jx::MsgContent* _internal_mutable_msg();
public:
// .jx.ContactsContent contacts = 3;
bool has_contacts() const;
private:
bool _internal_has_contacts() const;
public:
void clear_contacts();
const ::jx::ContactsContent& contacts() const;
::jx::ContactsContent* release_contacts();
::jx::ContactsContent* mutable_contacts();
void set_allocated_contacts(::jx::ContactsContent* contacts);
private:
const ::jx::ContactsContent& _internal_contacts() const;
::jx::ContactsContent* _internal_mutable_contacts();
public:
// .jx.TextContent text = 4;
bool has_text() const;
private:
bool _internal_has_text() const;
public:
void clear_text();
const ::jx::TextContent& text() const;
::jx::TextContent* release_text();
::jx::TextContent* mutable_text();
void set_allocated_text(::jx::TextContent* text);
private:
const ::jx::TextContent& _internal_text() const;
::jx::TextContent* _internal_mutable_text();
public:
void clear_content();
ContentCase content_case() const;
// @@protoc_insertion_point(class_scope:jx.BaseDatagram)
private:
class _Internal;
void set_has_msg();
void set_has_contacts();
void set_has_text();
inline bool has_content() const;
inline void clear_has_content();
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
int header_;
union ContentUnion {
ContentUnion() {}
::jx::MsgContent* msg_;
::jx::ContactsContent* contacts_;
::jx::TextContent* text_;
} content_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::uint32 _oneof_case_[1];
friend struct ::TableStruct_base_5fdatagram_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// ContactTran
// int32 ip = 1;
inline void ContactTran::clear_ip() {
ip_ = 0;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::_internal_ip() const {
return ip_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::ip() const {
// @@protoc_insertion_point(field_get:jx.ContactTran.ip)
return _internal_ip();
}
inline void ContactTran::_internal_set_ip(::PROTOBUF_NAMESPACE_ID::int32 value) {
ip_ = value;
}
inline void ContactTran::set_ip(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_ip(value);
// @@protoc_insertion_point(field_set:jx.ContactTran.ip)
}
// int32 port = 2;
inline void ContactTran::clear_port() {
port_ = 0;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::_internal_port() const {
return port_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::port() const {
// @@protoc_insertion_point(field_get:jx.ContactTran.port)
return _internal_port();
}
inline void ContactTran::_internal_set_port(::PROTOBUF_NAMESPACE_ID::int32 value) {
port_ = value;
}
inline void ContactTran::set_port(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_port(value);
// @@protoc_insertion_point(field_set:jx.ContactTran.port)
}
// int32 userId = 3;
inline void ContactTran::clear_userid() {
userid_ = 0;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::_internal_userid() const {
return userid_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 ContactTran::userid() const {
// @@protoc_insertion_point(field_get:jx.ContactTran.userId)
return _internal_userid();
}
inline void ContactTran::_internal_set_userid(::PROTOBUF_NAMESPACE_ID::int32 value) {
userid_ = value;
}
inline void ContactTran::set_userid(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_userid(value);
// @@protoc_insertion_point(field_set:jx.ContactTran.userId)
}
// -------------------------------------------------------------------
// MsgContent
// repeated bytes msgBody = 1;
inline int MsgContent::_internal_msgbody_size() const {
return msgbody_.size();
}
inline int MsgContent::msgbody_size() const {
return _internal_msgbody_size();
}
inline void MsgContent::clear_msgbody() {
msgbody_.Clear();
}
inline std::string* MsgContent::add_msgbody() {
// @@protoc_insertion_point(field_add_mutable:jx.MsgContent.msgBody)
return _internal_add_msgbody();
}
inline const std::string& MsgContent::_internal_msgbody(int index) const {
return msgbody_.Get(index);
}
inline const std::string& MsgContent::msgbody(int index) const {
// @@protoc_insertion_point(field_get:jx.MsgContent.msgBody)
return _internal_msgbody(index);
}
inline std::string* MsgContent::mutable_msgbody(int index) {
// @@protoc_insertion_point(field_mutable:jx.MsgContent.msgBody)
return msgbody_.Mutable(index);
}
inline void MsgContent::set_msgbody(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:jx.MsgContent.msgBody)
msgbody_.Mutable(index)->assign(value);
}
inline void MsgContent::set_msgbody(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:jx.MsgContent.msgBody)
msgbody_.Mutable(index)->assign(std::move(value));
}
inline void MsgContent::set_msgbody(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
msgbody_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:jx.MsgContent.msgBody)
}
inline void MsgContent::set_msgbody(int index, const void* value, size_t size) {
msgbody_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:jx.MsgContent.msgBody)
}
inline std::string* MsgContent::_internal_add_msgbody() {
return msgbody_.Add();
}
inline void MsgContent::add_msgbody(const std::string& value) {
msgbody_.Add()->assign(value);
// @@protoc_insertion_point(field_add:jx.MsgContent.msgBody)
}
inline void MsgContent::add_msgbody(std::string&& value) {
msgbody_.Add(std::move(value));
// @@protoc_insertion_point(field_add:jx.MsgContent.msgBody)
}
inline void MsgContent::add_msgbody(const char* value) {
GOOGLE_DCHECK(value != nullptr);
msgbody_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:jx.MsgContent.msgBody)
}
inline void MsgContent::add_msgbody(const void* value, size_t size) {
msgbody_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:jx.MsgContent.msgBody)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
MsgContent::msgbody() const {
// @@protoc_insertion_point(field_list:jx.MsgContent.msgBody)
return msgbody_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
MsgContent::mutable_msgbody() {
// @@protoc_insertion_point(field_mutable_list:jx.MsgContent.msgBody)
return &msgbody_;
}
// -------------------------------------------------------------------
// TextContent
// string textBody = 1;
inline void TextContent::clear_textbody() {
textbody_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline const std::string& TextContent::textbody() const {
// @@protoc_insertion_point(field_get:jx.TextContent.textBody)
return _internal_textbody();
}
inline void TextContent::set_textbody(const std::string& value) {
_internal_set_textbody(value);
// @@protoc_insertion_point(field_set:jx.TextContent.textBody)
}
inline std::string* TextContent::mutable_textbody() {
// @@protoc_insertion_point(field_mutable:jx.TextContent.textBody)
return _internal_mutable_textbody();
}
inline const std::string& TextContent::_internal_textbody() const {
return textbody_.GetNoArena();
}
inline void TextContent::_internal_set_textbody(const std::string& value) {
textbody_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value);
}
inline void TextContent::set_textbody(std::string&& value) {
textbody_.SetNoArena(
&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:jx.TextContent.textBody)
}
inline void TextContent::set_textbody(const char* value) {
GOOGLE_DCHECK(value != nullptr);
textbody_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:jx.TextContent.textBody)
}
inline void TextContent::set_textbody(const char* value, size_t size) {
textbody_.SetNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:jx.TextContent.textBody)
}
inline std::string* TextContent::_internal_mutable_textbody() {
return textbody_.MutableNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline std::string* TextContent::release_textbody() {
// @@protoc_insertion_point(field_release:jx.TextContent.textBody)
return textbody_.ReleaseNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
inline void TextContent::set_allocated_textbody(std::string* textbody) {
if (textbody != nullptr) {
} else {
}
textbody_.SetAllocatedNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), textbody);
// @@protoc_insertion_point(field_set_allocated:jx.TextContent.textBody)
}
// -------------------------------------------------------------------
// ContactsContent
// repeated .jx.ContactTran contact = 1;
inline int ContactsContent::_internal_contact_size() const {
return contact_.size();
}
inline int ContactsContent::contact_size() const {
return _internal_contact_size();
}
inline void ContactsContent::clear_contact() {
contact_.Clear();
}
inline ::jx::ContactTran* ContactsContent::mutable_contact(int index) {
// @@protoc_insertion_point(field_mutable:jx.ContactsContent.contact)
return contact_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::jx::ContactTran >*
ContactsContent::mutable_contact() {
// @@protoc_insertion_point(field_mutable_list:jx.ContactsContent.contact)
return &contact_;
}
inline const ::jx::ContactTran& ContactsContent::_internal_contact(int index) const {
return contact_.Get(index);
}
inline const ::jx::ContactTran& ContactsContent::contact(int index) const {
// @@protoc_insertion_point(field_get:jx.ContactsContent.contact)
return _internal_contact(index);
}
inline ::jx::ContactTran* ContactsContent::_internal_add_contact() {
return contact_.Add();
}
inline ::jx::ContactTran* ContactsContent::add_contact() {
// @@protoc_insertion_point(field_add:jx.ContactsContent.contact)
return _internal_add_contact();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::jx::ContactTran >&
ContactsContent::contact() const {
// @@protoc_insertion_point(field_list:jx.ContactsContent.contact)
return contact_;
}
// -------------------------------------------------------------------
// BaseDatagram
// .jx.BaseDatagramHeader header = 1;
inline void BaseDatagram::clear_header() {
header_ = 0;
}
inline ::jx::BaseDatagramHeader BaseDatagram::_internal_header() const {
return static_cast< ::jx::BaseDatagramHeader >(header_);
}
inline ::jx::BaseDatagramHeader BaseDatagram::header() const {
// @@protoc_insertion_point(field_get:jx.BaseDatagram.header)
return _internal_header();
}
inline void BaseDatagram::_internal_set_header(::jx::BaseDatagramHeader value) {
header_ = value;
}
inline void BaseDatagram::set_header(::jx::BaseDatagramHeader value) {
_internal_set_header(value);
// @@protoc_insertion_point(field_set:jx.BaseDatagram.header)
}
// .jx.MsgContent msg = 2;
inline bool BaseDatagram::_internal_has_msg() const {
return content_case() == kMsg;
}
inline bool BaseDatagram::has_msg() const {
return _internal_has_msg();
}
inline void BaseDatagram::set_has_msg() {
_oneof_case_[0] = kMsg;
}
inline void BaseDatagram::clear_msg() {
if (_internal_has_msg()) {
delete content_.msg_;
clear_has_content();
}
}
inline ::jx::MsgContent* BaseDatagram::release_msg() {
// @@protoc_insertion_point(field_release:jx.BaseDatagram.msg)
if (_internal_has_msg()) {
clear_has_content();
::jx::MsgContent* temp = content_.msg_;
content_.msg_ = nullptr;
return temp;
} else {
return nullptr;
}
}
inline const ::jx::MsgContent& BaseDatagram::_internal_msg() const {
return _internal_has_msg()
? *content_.msg_
: *reinterpret_cast< ::jx::MsgContent*>(&::jx::_MsgContent_default_instance_);
}
inline const ::jx::MsgContent& BaseDatagram::msg() const {
// @@protoc_insertion_point(field_get:jx.BaseDatagram.msg)
return _internal_msg();
}
inline ::jx::MsgContent* BaseDatagram::_internal_mutable_msg() {
if (!_internal_has_msg()) {
clear_content();
set_has_msg();
content_.msg_ = CreateMaybeMessage< ::jx::MsgContent >(
GetArenaNoVirtual());
}
return content_.msg_;
}
inline ::jx::MsgContent* BaseDatagram::mutable_msg() {
// @@protoc_insertion_point(field_mutable:jx.BaseDatagram.msg)
return _internal_mutable_msg();
}
// .jx.ContactsContent contacts = 3;
inline bool BaseDatagram::_internal_has_contacts() const {
return content_case() == kContacts;
}
inline bool BaseDatagram::has_contacts() const {
return _internal_has_contacts();
}
inline void BaseDatagram::set_has_contacts() {
_oneof_case_[0] = kContacts;
}
inline void BaseDatagram::clear_contacts() {
if (_internal_has_contacts()) {
delete content_.contacts_;
clear_has_content();
}
}
inline ::jx::ContactsContent* BaseDatagram::release_contacts() {
// @@protoc_insertion_point(field_release:jx.BaseDatagram.contacts)
if (_internal_has_contacts()) {
clear_has_content();
::jx::ContactsContent* temp = content_.contacts_;
content_.contacts_ = nullptr;
return temp;
} else {
return nullptr;
}
}
inline const ::jx::ContactsContent& BaseDatagram::_internal_contacts() const {
return _internal_has_contacts()
? *content_.contacts_
: *reinterpret_cast< ::jx::ContactsContent*>(&::jx::_ContactsContent_default_instance_);
}
inline const ::jx::ContactsContent& BaseDatagram::contacts() const {
// @@protoc_insertion_point(field_get:jx.BaseDatagram.contacts)
return _internal_contacts();
}
inline ::jx::ContactsContent* BaseDatagram::_internal_mutable_contacts() {
if (!_internal_has_contacts()) {
clear_content();
set_has_contacts();
content_.contacts_ = CreateMaybeMessage< ::jx::ContactsContent >(
GetArenaNoVirtual());
}
return content_.contacts_;
}
inline ::jx::ContactsContent* BaseDatagram::mutable_contacts() {
// @@protoc_insertion_point(field_mutable:jx.BaseDatagram.contacts)
return _internal_mutable_contacts();
}
// .jx.TextContent text = 4;
inline bool BaseDatagram::_internal_has_text() const {
return content_case() == kText;
}
inline bool BaseDatagram::has_text() const {
return _internal_has_text();
}
inline void BaseDatagram::set_has_text() {
_oneof_case_[0] = kText;
}
inline void BaseDatagram::clear_text() {
if (_internal_has_text()) {
delete content_.text_;
clear_has_content();
}
}
inline ::jx::TextContent* BaseDatagram::release_text() {
// @@protoc_insertion_point(field_release:jx.BaseDatagram.text)
if (_internal_has_text()) {
clear_has_content();
::jx::TextContent* temp = content_.text_;
content_.text_ = nullptr;
return temp;
} else {
return nullptr;
}
}
inline const ::jx::TextContent& BaseDatagram::_internal_text() const {
return _internal_has_text()
? *content_.text_
: *reinterpret_cast< ::jx::TextContent*>(&::jx::_TextContent_default_instance_);
}
inline const ::jx::TextContent& BaseDatagram::text() const {
// @@protoc_insertion_point(field_get:jx.BaseDatagram.text)
return _internal_text();
}
inline ::jx::TextContent* BaseDatagram::_internal_mutable_text() {
if (!_internal_has_text()) {
clear_content();
set_has_text();
content_.text_ = CreateMaybeMessage< ::jx::TextContent >(
GetArenaNoVirtual());
}
return content_.text_;
}
inline ::jx::TextContent* BaseDatagram::mutable_text() {
// @@protoc_insertion_point(field_mutable:jx.BaseDatagram.text)
return _internal_mutable_text();
}
inline bool BaseDatagram::has_content() const {
return content_case() != CONTENT_NOT_SET;
}
inline void BaseDatagram::clear_has_content() {
_oneof_case_[0] = CONTENT_NOT_SET;
}
inline BaseDatagram::ContentCase BaseDatagram::content_case() const {
return BaseDatagram::ContentCase(_oneof_case_[0]);
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace jx
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::jx::BaseDatagramHeader> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::jx::BaseDatagramHeader>() {
return ::jx::BaseDatagramHeader_descriptor();
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_base_5fdatagram_2eproto
|
179aa3938b1b5ba9b6aacffc9188f8ded6f6c55b | 0f0b84bc92156e8ee93e58529b888a169a218eff | /LOJ1000.cpp | 34daff75d250cf664508759896f49309711a24de | [] | no_license | Mujahid2923/lightoj-solutions | 1924c2a9ad3b2a6f4b702b5539f1d94238aff25f | e16cf6cc55e558ff2a4c5e3102a908eb8aed8976 | refs/heads/master | 2021-06-30T08:10:13.521791 | 2020-09-25T05:28:28 | 2020-09-25T05:28:28 | 165,869,432 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | LOJ1000.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t,a,b;
cin>>t;
for(int i=1; i<=t; i++)
{
cin>>a>>b;
int sum=a+b;
printf("Case %d: %d\n",i,sum);
}
return 0;
}
|
9eb5f2f84f02d5e3d05148c249c21ca03d581886 | 5791d786c0f26fc287ac0fa7b293fe7339e041c2 | /Classes/circuit/worklayer/UI/device/microphone/CCMicrophone.h | c31399ddbade208a50967e6b97e889a16c6d9cac | [] | no_license | fengmm521/myspice | 2c2da3e9c250e0a4193d2d999b2eb119c18f0d38 | aacf57b4a11a34aa8ed38ee3557f6dc532aabffb | refs/heads/master | 2021-01-10T11:26:53.150769 | 2015-09-27T16:28:59 | 2015-09-27T16:28:59 | 43,237,336 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 432 | h | CCMicrophone.h | //
// CCMicrophone.h
// myspice
// 精灵类,主要用来创建一些定制的精灵动画。
// Created by woodcol on 15/9/27.
//
//
#ifndef __myspice__CCMicrophone__
#define __myspice__CCMicrophone__
#include "cocos2d.h"
#include "DeviceShowBase.h"
//麦克风
class CCMicrophone:public DeviceShowBase
{
public:
CREATE_FUNC(CCMicrophone);
virtual bool init();
};
#endif /* defined(__myspice__CCMicrophone__) */
|
eee6d7f10fc1b7e0be9d24b0fa3129e522dc1988 | 1832b62d456dccff292c7804658098707a119149 | /LaboratoryHomework/3PotRGB.ino | 17af8aa24b1839cee3a34cab53f9ffd8f291e94b | [] | no_license | Cosmin2108/Arduino | f8305eb5d6a0a1890f3fb1cd0845ed91f1cfe4f8 | e8913d3f5c28fb4fb32dfb52febdb3297add7bf6 | refs/heads/master | 2021-06-21T11:52:24.400540 | 2021-06-15T14:20:52 | 2021-06-15T14:20:52 | 217,827,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | ino | 3PotRGB.ino | // Pins of the RGB LED.
const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
// Analog input from the potentiometer
const int potPinRed = A0;
const int potPinGreen = A1;
const int potPinBlue = A2;
// Values for each pin of the RGB LED.
int currentColorValueRed;
int currentColorValueGreen;
int currentColorValueBlue;
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(potPinRed, INPUT);
pinMode(potPinGreen, INPUT);
pinMode(potPinBlue, INPUT);
}
void loop()
{
int potPinRedValue = map(analogRead(potPinRed), 0, 1024, 0, 255);
int potPinGreenValue = map(analogRead(potPinGreen), 0, 1024, 0, 255);
int potPinBlueValue = map(analogRead(potPinBlue), 0, 1024, 0, 255);
analogWrite(redPin, potPinRedValue);
analogWrite(greenPin, potPinGreenValue);
analogWrite(bluePin, potPinBlueValue);
}
|
12d04d5fb145db817b20f114a9923d7d7613aa5b | 8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a | /3rdParty/V8/v7.9.317/third_party/icu/source/i18n/number_formatimpl.h | fd8708c532e13196cd69c7507a99db4a8ffd5d8f | [
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"NAIST-2003",
"MIT",
"bzip2-1.0.6",
"Apache-2.0",
"SunPro",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"JSON",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later"
] | permissive | arangodb/arangodb | 0980625e76c56a2449d90dcb8d8f2c485e28a83b | 43c40535cee37fc7349a21793dc33b1833735af5 | refs/heads/devel | 2023-08-31T09:34:47.451950 | 2023-08-31T07:25:02 | 2023-08-31T07:25:02 | 2,649,214 | 13,385 | 982 | Apache-2.0 | 2023-09-14T17:02:16 | 2011-10-26T06:42:00 | C++ | UTF-8 | C++ | false | false | 6,090 | h | number_formatimpl.h | // © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#ifndef __NUMBER_FORMATIMPL_H__
#define __NUMBER_FORMATIMPL_H__
#include "number_types.h"
#include "number_stringbuilder.h"
#include "number_patternstring.h"
#include "number_utils.h"
#include "number_patternmodifier.h"
#include "number_longnames.h"
#include "number_compact.h"
#include "number_microprops.h"
U_NAMESPACE_BEGIN namespace number {
namespace impl {
/**
* This is the "brain" of the number formatting pipeline. It ties all the pieces together, taking in a MacroProps and a
* DecimalQuantity and outputting a properly formatted number string.
*/
class NumberFormatterImpl : public UMemory {
public:
/**
* Builds a "safe" MicroPropsGenerator, which is thread-safe and can be used repeatedly.
* The caller owns the returned NumberFormatterImpl.
*/
NumberFormatterImpl(const MacroProps ¯os, UErrorCode &status);
/**
* Builds and evaluates an "unsafe" MicroPropsGenerator, which is cheaper but can be used only once.
*/
static int32_t
formatStatic(const MacroProps ¯os, DecimalQuantity &inValue, NumberStringBuilder &outString,
UErrorCode &status);
/**
* Prints only the prefix and suffix; used for DecimalFormat getters.
*
* @return The index into the output at which the prefix ends and the suffix starts; in other words,
* the prefix length.
*/
static int32_t getPrefixSuffixStatic(const MacroProps& macros, int8_t signum,
StandardPlural::Form plural, NumberStringBuilder& outString,
UErrorCode& status);
/**
* Evaluates the "safe" MicroPropsGenerator created by "fromMacros".
*/
int32_t format(DecimalQuantity& inValue, NumberStringBuilder& outString, UErrorCode& status) const;
/**
* Like format(), but saves the result into an output MicroProps without additional processing.
*/
void preProcess(DecimalQuantity& inValue, MicroProps& microsOut, UErrorCode& status) const;
/**
* Like getPrefixSuffixStatic() but uses the safe compiled object.
*/
int32_t getPrefixSuffix(int8_t signum, StandardPlural::Form plural, NumberStringBuilder& outString,
UErrorCode& status) const;
const MicroProps& getRawMicroProps() const {
return fMicros;
}
/**
* Synthesizes the output string from a MicroProps and DecimalQuantity.
* This method formats only the main number, not affixes.
*/
static int32_t writeNumber(const MicroProps& micros, DecimalQuantity& quantity,
NumberStringBuilder& string, int32_t index, UErrorCode& status);
/**
* Adds the affixes. Intended to be called immediately after formatNumber.
*/
static int32_t writeAffixes(const MicroProps& micros, NumberStringBuilder& string, int32_t start,
int32_t end, UErrorCode& status);
private:
// Head of the MicroPropsGenerator linked list:
const MicroPropsGenerator *fMicroPropsGenerator = nullptr;
// Tail of the list:
MicroProps fMicros;
// Other fields possibly used by the number formatting pipeline:
// TODO: Convert more of these LocalPointers to value objects to reduce the number of news?
LocalPointer<const DecimalFormatSymbols> fSymbols;
LocalPointer<const PluralRules> fRules;
LocalPointer<const ParsedPatternInfo> fPatternInfo;
LocalPointer<const ScientificHandler> fScientificHandler;
LocalPointer<MutablePatternModifier> fPatternModifier;
LocalPointer<const ImmutablePatternModifier> fImmutablePatternModifier;
LocalPointer<const LongNameHandler> fLongNameHandler;
LocalPointer<const CompactHandler> fCompactHandler;
// Value objects possibly used by the number formatting pipeline:
struct Warehouse {
CurrencySymbols fCurrencySymbols;
} fWarehouse;
NumberFormatterImpl(const MacroProps ¯os, bool safe, UErrorCode &status);
MicroProps& preProcessUnsafe(DecimalQuantity &inValue, UErrorCode &status);
int32_t getPrefixSuffixUnsafe(int8_t signum, StandardPlural::Form plural,
NumberStringBuilder& outString, UErrorCode& status);
/**
* If rulesPtr is non-null, return it. Otherwise, return a PluralRules owned by this object for the
* specified locale, creating it if necessary.
*/
const PluralRules *
resolvePluralRules(const PluralRules *rulesPtr, const Locale &locale, UErrorCode &status);
/**
* Synthesizes the MacroProps into a MicroPropsGenerator. All information, including the locale, is encoded into the
* MicroPropsGenerator, except for the quantity itself, which is left abstract and must be provided to the returned
* MicroPropsGenerator instance.
*
* @see MicroPropsGenerator
* @param macros
* The {@link MacroProps} to consume. This method does not mutate the MacroProps instance.
* @param safe
* If true, the returned MicroPropsGenerator will be thread-safe. If false, the returned value will
* <em>not</em> be thread-safe, intended for a single "one-shot" use only. Building the thread-safe
* object is more expensive.
*/
const MicroPropsGenerator *
macrosToMicroGenerator(const MacroProps ¯os, bool safe, UErrorCode &status);
static int32_t
writeIntegerDigits(const MicroProps µs, DecimalQuantity &quantity, NumberStringBuilder &string,
int32_t index, UErrorCode &status);
static int32_t
writeFractionDigits(const MicroProps µs, DecimalQuantity &quantity, NumberStringBuilder &string,
int32_t index, UErrorCode &status);
};
} // namespace impl
} // namespace number
U_NAMESPACE_END
#endif //__NUMBER_FORMATIMPL_H__
#endif /* #if !UCONFIG_NO_FORMATTING */
|
b304f2858d92d0447cbb9908e99a4ad9f66f3dbf | 7d5593b9bbaf6bb8eaacca88449d90c9c305c36e | /problems/380-insert-delete-getrandom-o1/380.hh | e72034fd3843bd7b09f65a34ca3ddb34b672125c | [] | no_license | yottacto/leetcode | fc98052ed9d643be8a79116d28540596bcc7c26b | 9a41e41c0982c1a313803d1d8288d086fbdbd5b6 | refs/heads/master | 2021-04-25T12:05:55.671066 | 2019-12-15T03:07:31 | 2019-12-15T03:07:31 | 111,814,868 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | hh | 380.hh | #include <vector>
#include <algorithm>
#include <random>
#include <iterator>
#include <unordered_map>
struct RandomizedSet
{
std::vector<int> v;
std::unordered_map<int, int> h;
std::mt19937 gen;
// Initialize your data structure here.
RandomizedSet() : gen(std::random_device{}())
{
}
// Inserts a value to the set. Returns true if the set did not already
// contain the specified element.
bool insert(int val)
{
if (h.count(val)) {
return false;
} else {
v.emplace_back(val);
h[val] = v.size() - 1;
return true;
}
}
// Removes a value from the set. Returns true if the set contained the
// specified element.
bool remove(int val)
{
if (h.count(val)) {
auto pos = h[val];
h[v.back()] = pos;
std::swap(v[pos], v.back());
v.pop_back();
h.erase(val);
return true;
} else {
return false;
}
}
// Get a random element from the set.
int getRandom()
{
std::uniform_int_distribution<> dis(0, v.size() - 1);
return v[dis(gen)];
}
};
|
41137024f518595382b5cb8594d2b5ceaab588ca | a80bb4b52730c40ad09c123d60f42a46ca895ff1 | /Cellular.hpp | e92e9e16df8aec302bb7731a7ac16f51f5170516 | [] | no_license | theoden8/emu-automaton | dcabdd3e6706da536d49f94bac066bd95972cb11 | 5a8863129ea947300f801624aed2d359dfed2be8 | refs/heads/master | 2020-04-30T12:05:26.865337 | 2019-12-22T01:34:43 | 2019-12-22T01:34:43 | 176,818,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,127 | hpp | Cellular.hpp | #pragma once
#include <cstdlib>
#include <type_traits>
#include <utility>
namespace ca {
template <typename CA>
inline uint8_t random(int y, int x) {
return rand() % CA::no_states;
}
constexpr int DEAD = 0, LIVE = 1;
template <typename CA, typename B>
inline int count_neighbours(B &prev, int y, int x) {
int counter = 0;
for(int iy : {-1, 0, 1}) {
for(int ix : {-1, 0, 1}) {
if(!iy&&!ix)continue;
if(prev[y + iy][x + ix] == LIVE) {
++counter;
}
}
}
return counter;
}
template <class B, class S> struct BS;
template <int... Cs> struct one_of_cond;
template <int C, int... Cs> struct one_of_cond<C, Cs...> {
static inline bool eval(int val) { return C == val || one_of_cond<Cs...>::eval(val); }
};
template <> struct one_of_cond<> {
static inline bool eval(int){return false;}
};
template <int... Is>
using sequence = std::index_sequence<Is...>;
template <int... Bs, int... Ss>
struct BS<sequence<Bs...>, sequence<Ss...>> {
using this_t = BS<sequence<Bs...>, sequence<Ss...>>;
static constexpr int outside_state = 0;
static constexpr int no_states = 2;
static constexpr int dim = 4;
static inline uint8_t init_state(int y, int x) {
return random<this_t>(y, x);
}
template <typename B>
static inline uint8_t next_state(B &&prev, int y, int x) {
int count = count_neighbours<this_t>(prev, y, x);
int result = outside_state;
if(prev[y][x] == DEAD && one_of_cond<Bs...>::eval(count)/* || (rand() % 100 == 99 && count > 1)*/) {
return LIVE;
} else if(prev[y][x] == LIVE && one_of_cond<Ss...>::eval(count)) {
return LIVE;
}
return DEAD;
}
};
} // namespace ca
// http://www.conwaylife.com/wiki/List_of_Life-like_cellular_automata
namespace cellular {
using Replicator = ca::BS<ca::sequence<1,3,5,7>, ca::sequence<1,3,5,7>>;
using Fredkin = ca::BS<ca::sequence<1,3,5,7>, ca::sequence<0,2,4,6,8>>;
using Seeds = ca::BS<ca::sequence<2>, ca::sequence<>>;
using LiveOrDie = ca::BS<ca::sequence<2>, ca::sequence<0>>;
using Flock = ca::BS<ca::sequence<3>, ca::sequence<1,2>>;
using Mazectric = ca::BS<ca::sequence<3>, ca::sequence<1,2,3,4>>;
using Maze = ca::BS<ca::sequence<3>, ca::sequence<1,2,3,4,5>>;
using GameOfLife = ca::BS<ca::sequence<3>, ca::sequence<2,3>>;
using EightLife = ca::BS<ca::sequence<3>, ca::sequence<2,3,8>>;
using LongLife = ca::BS<ca::sequence<3,4,5>, ca::sequence<5>>;
using TxT = ca::BS<ca::sequence<3,6>, ca::sequence<1,2,5>>;
using HighLife = ca::BS<ca::sequence<3,6>, ca::sequence<2,3>>;
using Move = ca::BS<ca::sequence<3,6,8>, ca::sequence<2,4,5>>;
using Stains = ca::BS<ca::sequence<3,6,7,8>, ca::sequence<2,3,5,6,7,8>>;
using DayAndNight = ca::BS<ca::sequence<3,6,7,8>, ca::sequence<3,4,6,7,8>>;
using DryLife = ca::BS<ca::sequence<3,7>, ca::sequence<2,3>>;
using PedestrLife = ca::BS<ca::sequence<3,8>, ca::sequence<2,3>>;
} // namespace cellular
|
be097c50dfb3de9bacc3c31d0c24112ddbab76b3 | d82b193bb0ad64a3b952b62eec51f7c6babd0a15 | /RCD_CAR/src/RCDArduinoSketch/RCDArduinoSketch.ino | 27b9587118e785129238806941a60e2b2d999fa3 | [] | no_license | lorenzoMacca/RCD_demo | 5155bc8ecfa9db9a9944058ba04fb452e9515b9e | 34de72d69f74cc5a4da0871fc7fd7b8d04542545 | refs/heads/master | 2021-01-21T04:46:44.030655 | 2016-06-10T19:48:25 | 2016-06-10T19:48:25 | 55,777,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | ino | RCDArduinoSketch.ino | #include "lib/ESP8266/ESP8266Arduino.h"
#include <SoftwareSerial.h>
#define RX_PIN 10
#define TX_PIN 11
ESP8266Arduino *esp8266;
SoftwareSerial esp8266Serial(RX_PIN, TX_PIN); // RX, TX
String ssid = "KDG-C1CFE";
String pass = "F0Ey03x0YQU3";
String ip = "192.168.0.39";
String port = "9090";
void setup() {
pinMode(RX_PIN, INPUT);
pinMode(TX_PIN, OUTPUT);
esp8266Serial.begin(115200);
Serial.begin(9600);
esp8266 = new ESP8266Arduino(&esp8266Serial, &Serial);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
//test connection
bool isConnected = esp8266->testConnection();
//connect to wif
if(isConnected){
esp8266->connectToWifi(&ssid, &pass);
delay(300);
esp8266->cipmux(&ip, &port);
delay(300);
esp8266->quitConnection();
}
}
void loop() {
// put your main code here, to run repeatedly:
}
|
925190a0e4352017609f55997f32d36eb5dd122d | d8cd2ec9b3b4bdb7bf5133c687772a29936f660d | /Source/VMUV_Plugin/TCP/SocketWrapper.cpp | 127ed178786f4c390238c80b211b478b674cf6bd | [] | no_license | shastaclokey1/VMUV_UNREAL_PLUGIN | 7b33b938328371c447cef02c44da1d770d96c78c | 476aebface71f28f1de7d8229b13210090e89626 | refs/heads/master | 2021-01-19T18:20:28.021339 | 2017-08-23T02:17:45 | 2017-08-23T02:17:45 | 101,125,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,370 | cpp | SocketWrapper.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SocketWrapper.h"
#include "VMUV_Plugin.h"
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include "../Logging/traceLogger.h"
const FString socketWrapper::version = "1.0.0";
socketWrapper::socketWrapper() : config(Configuration::client)
{
rxDataPing.reserve(256);
rxDataPong.reserve(256);
}
FString socketWrapper::getVersion()
{
return version;
}
void socketWrapper::setRxData(vector<unsigned char> payload, PacketTypes type)
{
FString method = "setRxData()";
if (config == Configuration::server)
{
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "Socket wrapper config set to server"));
return;
}
if (usePing)
{
rxDataPing.clear();
for (int i = 0; i < (int)payload.size(); i++)
rxDataPing.push_back(payload[i]);
usePing = false;
}
else
{
rxDataPong.clear();
for (int i = 0; i < (int)payload.size(); i++)
rxDataPong.push_back(payload[i]);
usePing = true;
}
}
vector<unsigned char> socketWrapper::clientGetRxData() const
{
FString method = "clientGetRxData";
if (config == Configuration::server)
{
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "Socket wrapper config set to server"));
return vector<unsigned char>();
}
if (usePing)
return rxDataPong;
else
return rxDataPing;
}
void socketWrapper::clientStartRead()
{
FString method = "clientStartRead()";
if (clientIsBusy || config == Configuration::server)
{
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "Socket wrapper config set to server (or) client is busy"));
return;
}
WORD sockVersion;
WSADATA wsaData;
int nret;
char readBuff[256];
sockVersion = MAKEWORD(1, 0);
WSAStartup(sockVersion, &wsaData);
//initiallize the client socket
client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client == INVALID_SOCKET)
{
nret = WSAGetLastError();
UE_LOG(LogTemp, Error, TEXT("ERROR WITH socket() initiallization!"));
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, FString("Error With socket() initiallization") + FString::FromInt(nret)));
closesocket(client);
WSACleanup();
return;
}
//prepare for connection by filling sockaddr struct with info about the server
SOCKADDR_IN serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr.s_addr = loopBackIpAddr;//*((LPIN_ADDR)*hostEntry->h_addr_list);
serverInfo.sin_port = htons(port);
//connect to the server!
nret = connect(client, (LPSOCKADDR)&serverInfo, sizeof(serverInfo));
if (nret == SOCKET_ERROR)
{
nret = WSAGetLastError();
UE_LOG(LogTemp, Error, TEXT("ERROR WITH connect() function!"));
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, FString("Error With connect() initiallization: ") + FString::FromInt(nret)));
closesocket(client);
WSACleanup();
return;
}
//get a data packet from the tcp connection
nret = recv(client, readBuff, 7 + 19, 0);
if (nret == SOCKET_ERROR)
{
nret = WSAGetLastError();
UE_LOG(LogTemp, Error, TEXT("ERROR WITH recv() function!"));
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "Error With recv() initiallization"));
closesocket(client);
WSACleanup();
return;
}
//error check in case the server is sending wonky packets
if (nret != 26)
{
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "data packet from recv() was wrong size"));
closesocket(client);
WSACleanup();
return;
}
vector<unsigned char> packet, data;
for (int i = 0; i < 7 + 19; i++)
packet.push_back(readBuff[i]);
//check packet validity and set it to the rxData
bool rtn = packetMaker.isPacketValid(packet);
if (rtn)
{
UE_LOG(LogTemp, Warning, TEXT("Recieved valid packet from server ... unpacking."));
data = packetMaker.unpackData(packet);
setRxData(data, PacketTypes::raw_data);
numValidPacketsRead++;
closesocket(client);
WSACleanup();
return;
}
else
{
UE_LOG(LogTemp, Error, TEXT("Invalid data packet!"));
traceLogger::queueMessage(traceLogger::buildMessage(moduleName, method, "not a valid packet"));
closesocket(client);
WSACleanup();
return;
}
}
int socketWrapper::getNumValidPacketsRead() const
{
return numValidPacketsRead;
}
bool socketWrapper::getUsePing() const
{
return usePing;
}
|
f988fbaf303df6665173790102b0aa14b8292320 | dec084e532035a84c0ae36abb4ddadd15380e585 | /DetourLib/SharedDetour.cpp | 944527a40360cbff451c11da93e1c772ce6fe363 | [] | no_license | calvinhsia/DetourSample | 51c450e4a8bfa023e782579392d28d9e296ef666 | 9daedd2b40c01a0dd99f3a17c0c2b7be5cfde91e | refs/heads/master | 2021-10-24T13:14:21.531354 | 2021-10-21T06:31:48 | 2021-10-21T06:31:48 | 135,942,424 | 0 | 0 | null | 2020-08-09T23:21:37 | 2018-06-03T21:35:13 | C++ | UTF-8 | C++ | false | false | 14,123 | cpp | SharedDetour.cpp | #include <Windows.h>
#include "..\Detours\detours.h"
#include "..\DetourSharedBase\DetourShared.h"
#include "stdio.h"
DetourTableEntry g_arrDetourTableEntry[DTF_MAX];
// using declsepc(naked) means we don't have to push/pop the params multiple times
#ifndef _WIN64
/*
STUBMACRO defines ASM code that takes the parameter as a DTF enum and looks up the DetourTableEntry in the array
g_arrDetourTableEntry. Hotpath has minimal branching
It then gets the redirected entry, and if it's 0, gets the real entry and does a JMP to that entry
*/
#define STUBMACRO(DTF) \
{ \
_asm mov edx, (SIZE DetourTableEntry) * DTF /* calculate the index into the array*/\
_asm add edx, offset g_arrDetourTableEntry /*add the base table address.*/ \
_asm mov eax, [edx+4] /* look at the 2nd entry in the table (the redirected value)*/ \
_asm cmp eax, 0 /* cmp to 0*/ \
_asm je b1 /* if it's zero, jump to b1*/ \
_asm jmp eax /* now jump to the redirected*/ \
_asm b1: /* jmp label */ \
_asm jmp DWORD PTR [edx] /*jmp to the real */\
}
/*
DETOURFUNC macro defines a function with no prolog/epilog (naked)
*/
// the parameters and the return type of the declspace(naked) don't matter
#define DETOURFUNC(FuncName) _declspec(naked) void MyStub##FuncName() { STUBMACRO(DTF_##FuncName) }
// these macros create the detour stubs for x86, e.g. MyStubMessageBoxA
DETOURFUNC(MessageBoxA);
DETOURFUNC(GetModuleHandleA);
DETOURFUNC(GetModuleFileNameA);
DETOURFUNC(RtlAllocateHeap);
DETOURFUNC(HeapReAlloc);
DETOURFUNC(RtlFreeHeap);
DETOURFUNC(NdrClientCall2);
// the detoured functions for Registry
DETOURFUNC(RegCreateKeyExW);
DETOURFUNC(RegOpenKeyExW);
DETOURFUNC(RegOpenKeyExA);
// detoured functions for Themed Scrollbar
DETOURFUNC(EnableScrollbar);
// detoured functions for ResponsiveNess
DETOURFUNC(PeekMessageA);
#else _WIN64
char* g_szArch = "x64 64 bit";
// these are the stubs for x64. (naked and inline asm not supported)
int WINAPI MyStubMessageBoxA(
_In_opt_ HWND hWnd,
_In_opt_ LPCSTR lpText,
_In_opt_ LPCSTR lpCaption,
_In_ UINT uType)
{
auto redir = g_arrDetourTableEntry[DTF_MessageBoxA].GetMethod();
return (reinterpret_cast<decltype(&MessageBoxA)>(redir))(hWnd, lpText, lpCaption, uType);
}
HMODULE WINAPI MyStubGetModuleHandleA(
_In_opt_ LPCSTR lpModuleName)
{
auto redir = g_arrDetourTableEntry[DTF_GetModuleHandleA].GetMethod();
return (reinterpret_cast<decltype(&GetModuleHandleA)>(redir))(lpModuleName);
}
DWORD WINAPI MyStubGetModuleFileNameA(
_In_opt_ HMODULE hModule,
_Out_writes_to_(nSize, ((return < nSize) ? (return +1) : nSize)) LPSTR lpFilename,
_In_ DWORD nSize
)
{
auto redir = g_arrDetourTableEntry[DTF_GetModuleFileNameA].GetMethod();
return (reinterpret_cast<decltype(&GetModuleFileNameA)>(redir))(hModule, lpFilename, nSize);
}
PVOID WINAPI MyStubRtlAllocateHeap(
_In_opt_ HANDLE hHeapHandle,
_In_ ULONG dwFlags,
_In_ DWORD nSize
)
{
auto redir = g_arrDetourTableEntry[DTF_RtlAllocateHeap].GetMethod();
return (reinterpret_cast<pfnRtlAllocateHeap>(redir))(hHeapHandle, dwFlags, nSize);
}
PVOID WINAPI MyStubHeapReAlloc(
HANDLE hHeap,
DWORD dwFlags,
LPVOID lpMem,
SIZE_T dwBytes
)
{
auto redir = g_arrDetourTableEntry[DTF_HeapReAlloc].GetMethod();
return (reinterpret_cast<pfnHeapReAlloc>(redir))(hHeap, dwFlags, lpMem, dwBytes);
}
BOOL WINAPI MyStubRtlFreeHeap(
HANDLE hHeap,
DWORD dwFlags,
LPVOID lpMem
)
{
auto redir = g_arrDetourTableEntry[DTF_RtlFreeHeap].GetMethod();
return (reinterpret_cast<pfnRtlFreeHeap>(redir))(hHeap, dwFlags, lpMem);
}
LSTATUS APIENTRY MyStubRegCreateKeyExW(
__in HKEY hKey,
__in LPCWSTR lpSubKey,
__reserved DWORD Reserved,
__in_opt LPWSTR lpClass,
__in DWORD dwOptions,
__in REGSAM samDesired,
__in_opt CONST LPSECURITY_ATTRIBUTES lpSecurityAttributes,
__out PHKEY phkResult,
__out_opt LPDWORD lpdwDisposition
)
{
auto redir = g_arrDetourTableEntry[DTF_RegCreateKeyExW].GetMethod();
return (reinterpret_cast<decltype(&RegCreateKeyExW)>(redir))(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
}
LSTATUS APIENTRY MyStubRegOpenKeyExW(
__in HKEY hKey,
__in_opt LPCWSTR lpSubKey,
__in_opt DWORD dwOptions,
__in REGSAM samDesired,
__out PHKEY phkResult
)
{
auto redir = g_arrDetourTableEntry[DTF_RegOpenKeyExW].GetMethod();
return (reinterpret_cast<decltype(&RegOpenKeyExW)>(redir))(hKey, lpSubKey, dwOptions, samDesired, phkResult);
}
LSTATUS APIENTRY MyStubRegOpenKeyExA(
__in HKEY hKey,
__in_opt LPCSTR lpSubKey,
__in_opt DWORD dwOptions,
__in REGSAM samDesired,
__out PHKEY phkResult
)
{
auto redir = g_arrDetourTableEntry[DTF_RegOpenKeyExA].GetMethod();
return (reinterpret_cast<decltype(&RegOpenKeyExA)>(redir))(hKey, lpSubKey, dwOptions, samDesired, phkResult);
}
BOOL WINAPI MyStubEnableScrollbar(
_In_ HWND hWnd,
_In_ UINT wSBflags,
_In_ UINT wArrows)
{
auto redir = g_arrDetourTableEntry[DTF_EnableScrollbar].GetMethod();
return (reinterpret_cast<decltype(&EnableScrollBar)>(redir))(hWnd, wSBflags, wArrows);
}
BOOL
WINAPI
MyStubPeekMessageA(
_Out_ LPMSG lpMsg,
_In_opt_ HWND hWnd,
_In_ UINT wMsgFilterMin,
_In_ UINT wMsgFilterMax,
_In_ UINT wRemoveMsg)
{
auto redir = g_arrDetourTableEntry[DTF_PeekMessageA].GetMethod();
return (reinterpret_cast<decltype(&PeekMessageA)>(redir))(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg);
}
#endif _WIN64
// we want to use barebones critsect because we're very early in process
// because we're so early in the process, no other threads are busy, so unlikely necessary
CRITICAL_SECTION g_csRedirect;
//todo: perhaps export /lock/unlock, perhaps allow batch lock/unlock
// passing in pvNew == null will revert the redirection
// if HRESULT != S_OK, could be because we couldn't find the real function when initializing or the client passed in an invalid ID
CLINKAGE HRESULT EXPORT RedirectDetour(int DTF_Id, PVOID pvNew, PVOID * ppReal)
{
HRESULT hr = E_FAIL;
if (DTF_Id >= 0 && DTF_Id < DTF_MAX) // if the client passed in a legitimate value
{
if (g_arrDetourTableEntry[DTF_Id].RealFunction != nullptr) // if we successfully found the real function to detour
{
_ASSERT_EXPR(pvNew == nullptr || g_arrDetourTableEntry[DTF_Id].RedirectedFunction == nullptr, L"Redirecting a function already redirected");
// we want to make sure all 4 (or 8) bytes of the address are changed atomically
// because we're so early in the process, no other threads are busy, so unlikely necessary
#ifdef _WIN64
InterlockedExchange64((LONGLONG*)&g_arrDetourTableEntry[DTF_Id].RedirectedFunction, (LONGLONG)pvNew);
#else
InterlockedExchange((LONG*)&g_arrDetourTableEntry[DTF_Id].RedirectedFunction, (LONG)pvNew);
#endif
if (ppReal != nullptr)
{
*ppReal = g_arrDetourTableEntry[DTF_Id].RealFunction;
}
hr = S_OK;
}
}
_ASSERT_EXPR(hr == S_OK, L"redirect detour failed?");
return hr;
};
CLINKAGE HRESULT EXPORT LockDetourTable()
{
EnterCriticalSection(&g_csRedirect);
return S_OK;
}
CLINKAGE HRESULT EXPORT UnlockDetourTable()
{
LeaveCriticalSection(&g_csRedirect);
return S_OK;
}
class SharedDetours
{
public:
SharedDetours()
{
InitializeCriticalSection(&g_csRedirect);
InstallTheDetours();
}
~SharedDetours()
{
UninstallDetours();
DeleteCriticalSection(&g_csRedirect);
}
private:
bool DidInstallDetours;
void InstallTheDetours()
{
DidInstallDetours = true;
_ASSERT_EXPR(g_arrDetourTableEntry[DTF_MAX - 1].RealFunction == 0, L"table should have 0 detour real funcrtions");
_ASSERT_EXPR(g_arrDetourTableEntry[DTF_MAX - 1].RedirectedFunction == 0, L"table should have 0 detour redirected");
// This is required because on Win7 ole32 directly links to the Kernel32 implementations of these functions
// and doesn't use Advapi
HMODULE hmodNtDll = GetModuleHandleA("ntdll");
OSVERSIONINFO osvi = {};
osvi.dwOSVersionInfoSize = sizeof(osvi);
// Fix for warnings as errors when building against WinBlue build 9444.0.130614-1739
// warning C4996: 'GetVersionExW': was declared deprecated
// externalapis\windows\winblue\sdk\inc\sysinfoapi.h(442)
// Deprecated. Use VerifyVersionInfo* or IsWindows* macros from VersionHelpers.
#pragma warning( disable : 4996 )
GetVersionEx(&osvi);
#pragma warning( default : 4996 )
if ((osvi.dwMajorVersion == 6 && osvi.dwMinorVersion >= 1) || osvi.dwMajorVersion > 6)
{
HMODULE hModKernel = GetModuleHandleW(L"kernelbase");
// First check if the appropriate functions are in kernelbase or kernel32. We want the kernelbase ones
// if we can help it (win8)
if (GetProcAddress(hModKernel, "RegCreateKeyExA") == NULL)
{
hModKernel = GetModuleHandleW(L"kernel32");
//CHECKERR(hMod == NULL);
}
g_arrDetourTableEntry[DTF_RegCreateKeyExW].RealFunction = &RegCreateKeyExA;
g_arrDetourTableEntry[DTF_RegOpenKeyExW].RealFunction = &RegOpenKeyExW;
}
g_arrDetourTableEntry[DTF_MessageBoxA].RealFunction = &MessageBoxA;
g_arrDetourTableEntry[DTF_GetModuleHandleA].RealFunction = &GetModuleHandleA;
g_arrDetourTableEntry[DTF_GetModuleFileNameA].RealFunction = &GetModuleFileNameA;
g_arrDetourTableEntry[DTF_RtlAllocateHeap].RealFunction = (pfnRtlAllocateHeap)GetProcAddress(hmodNtDll, "RtlAllocateHeap");
g_arrDetourTableEntry[DTF_HeapReAlloc].RealFunction = HeapReAlloc;// (pfnRtlFreeHeap)GetProcAddress(hmodNtDll, "HeapReAlloc");
g_arrDetourTableEntry[DTF_RtlFreeHeap].RealFunction = (pfnRtlFreeHeap)GetProcAddress(hmodNtDll, "RtlFreeHeap");
HMODULE hComBase = GetModuleHandleW(L"rpcrt4.dll");
// NdrClientCall2 is not a WinAPI so must use _declspec(naked)
g_arrDetourTableEntry[DTF_NdrClientCall2].RealFunction = (PVOID)GetProcAddress(hComBase, "NdrClientCall2");
g_arrDetourTableEntry[DTF_EnableScrollbar].RealFunction = &EnableScrollBar;
g_arrDetourTableEntry[DTF_PeekMessageA].RealFunction = &PeekMessageA;
#ifndef _WIN64
// the system region of memory changes for various architectures
// Address Space Layout Randomization causes Dlls to be loaded at varying addresses
// we want to tell Detours that on this architecture what the range of system dlls is so
// the VirtualAlloc it uses doesn't coincide with e.g. MSCorLib, Rebase costs when collisions occur
// see bug https://devdiv.visualstudio.com/DevDiv/_workitems/edit/280248
DetourSetSystemRegionLowerBound((PVOID)0x50000000);
DetourSetSystemRegionUpperBound((PVOID)0x80000000);
#endif _WIN64
DetourTransactionBegin();
#define ATTACH(x,y) DetAttach(x, y,(PCHAR)#x)
#define DETACH(x,y) DetDetach(x, y,(PCHAR)#x)
ATTACH(&g_arrDetourTableEntry[DTF_MessageBoxA].RealFunction, MyStubMessageBoxA);
ATTACH(&g_arrDetourTableEntry[DTF_GetModuleHandleA].RealFunction, MyStubGetModuleHandleA);
ATTACH(&g_arrDetourTableEntry[DTF_GetModuleFileNameA].RealFunction, MyStubGetModuleFileNameA);
ATTACH(&g_arrDetourTableEntry[DTF_RtlAllocateHeap].RealFunction, MyStubRtlAllocateHeap);
ATTACH(&g_arrDetourTableEntry[DTF_RtlFreeHeap].RealFunction, MyStubRtlFreeHeap);
ATTACH(&g_arrDetourTableEntry[DTF_HeapReAlloc].RealFunction, MyStubHeapReAlloc);
#ifndef _WIN64
// ATTACH(&g_arrDetourTableEntry[DTF_NdrClientCall2].RealFunction, MyStubNdrClientCall2);
#endif _WIN64
ATTACH(&g_arrDetourTableEntry[DTF_RegCreateKeyExW].RealFunction, MyStubRegCreateKeyExW);
ATTACH(&g_arrDetourTableEntry[DTF_RegOpenKeyExW].RealFunction, MyStubRegOpenKeyExW);
ATTACH(&g_arrDetourTableEntry[DTF_EnableScrollbar].RealFunction, MyStubEnableScrollbar);
ATTACH(&g_arrDetourTableEntry[DTF_PeekMessageA].RealFunction, MyStubPeekMessageA);
auto res = DetourTransactionCommit();
_ASSERT_EXPR(res == S_OK, "Failed to TransactionCommit install");
}
void UninstallDetours()
{
if (DidInstallDetours)
{
DidInstallDetours = false;
DetourTransactionBegin();
DETACH(&g_arrDetourTableEntry[DTF_MessageBoxA].RealFunction, MyStubMessageBoxA);
DETACH(&g_arrDetourTableEntry[DTF_GetModuleHandleA].RealFunction, MyStubGetModuleHandleA);
DETACH(&g_arrDetourTableEntry[DTF_GetModuleFileNameA].RealFunction, MyStubGetModuleFileNameA);
DETACH(&g_arrDetourTableEntry[DTF_RtlAllocateHeap].RealFunction, MyStubRtlAllocateHeap);
DETACH(&g_arrDetourTableEntry[DTF_HeapReAlloc].RealFunction, MyStubHeapReAlloc);
DETACH(&g_arrDetourTableEntry[DTF_RtlFreeHeap].RealFunction, MyStubRtlFreeHeap);
#ifndef _WIN64
// DETACH(&g_arrDetourTableEntry[DTF_NdrClientCall2].RealFunction, MyStubNdrClientCall2);
#endif _WIN64
DETACH(&g_arrDetourTableEntry[DTF_RegCreateKeyExW].RealFunction, MyStubRegCreateKeyExW);
DETACH(&g_arrDetourTableEntry[DTF_RegOpenKeyExW].RealFunction, MyStubRegOpenKeyExW);
DETACH(&g_arrDetourTableEntry[DTF_EnableScrollbar].RealFunction, MyStubEnableScrollbar);
DETACH(&g_arrDetourTableEntry[DTF_PeekMessageA].RealFunction, MyStubPeekMessageA);
auto res = DetourTransactionCommit();
_ASSERT_EXPR(res == S_OK, "Failed to TransactionCommit uninstall");
for (int i = 0; i < DTF_MAX; i++)
{
g_arrDetourTableEntry[i].RealFunction = nullptr;
g_arrDetourTableEntry[i].RedirectedFunction = nullptr;
}
}
}
VOID DetAttach(PVOID* ppbReal, PVOID pbMine, PCHAR psz)
{
LONG res = DetourAttach(ppbReal, pbMine);
if (res != S_OK) {
WCHAR szBuf[1024] = {};
swprintf_s(szBuf, _countof(szBuf), L"Attach detour Failed %S Errcode=%d)", psz, res);
_ASSERT_EXPR(false, szBuf);
}
}
VOID DetDetach(PVOID* ppbReal, PVOID pbMine, PCHAR psz)
{
LONG res = DetourDetach(ppbReal, pbMine);
if (res != S_OK) {
WCHAR szBuf[1024] = {};
swprintf_s(szBuf, _countof(szBuf), L"Detach Failed %S Errcode=%d", psz, res);
_ASSERT_EXPR(false, szBuf);
}
}
};
CLINKAGE HRESULT EXPORT StartDetouring(PVOID* pDetours)
{
// SharedDetours xx;
auto xx = new SharedDetours();
*pDetours = xx;
return S_OK;
}
#pragma comment(linker, "/EXPORT:StartDetouring=_StartDetouring@4")
CLINKAGE HRESULT EXPORT StopDetouring(PVOID oDetours)
{
SharedDetours* xx = (SharedDetours*)oDetours;
delete xx;
return S_OK;
}
#pragma comment(linker, "/EXPORT:StopDetouring=_StopDetouring@4")
|
f111c5b435a683bf47c8609efa2f15176e4b7fd0 | 1aab741b833300ce780e2a5540a914781255f702 | /libkafka-asio/examples/offset_fetch_cxx03.cpp | 70435b04a016a905db6975236d9598114aa97f96 | [
"MIT",
"BSD-2-Clause"
] | permissive | GSLabDev/libasynckafkaclient | c169f0d25028258861b0a71d4f0718e1a5cdf334 | 98c6ecc227f965d5916929c3d70e95f12bdf7006 | refs/heads/master | 2021-01-18T22:34:47.209830 | 2016-05-26T12:18:08 | 2016-05-26T12:18:08 | 50,917,795 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,926 | cpp | offset_fetch_cxx03.cpp | //
// examples/offset_fetch_cxx03.cpp
// -------------------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
// ----------------------------------
//
// This example shows how to fetch offset data for a consumer group using the
// 'OffsetFetch' API of Kafka 0.8.2. On the other side it demonstrates how
// the library can be used in combination with promised/futures and is
// therefore running all IO related work inside of a separate thread.
// The example is mainly a port of the C++11-based example but is using the
// boost library instead of the C++11 standard library.
//
#include <boost/exception_ptr.hpp>
#include <boost/function.hpp>
#include <boost/thread.hpp>
#include <boost/system/system_error.hpp>
#include <libkafka_asio/libkafka_asio.h>
using libkafka_asio::Client;
using libkafka_asio::String;
using libkafka_asio::Int32;
using libkafka_asio::ConsumerMetadataRequest;
using libkafka_asio::ConsumerMetadataResponse;
using libkafka_asio::OffsetFetchRequest;
using libkafka_asio::OffsetFetchResponse;
// This will create handler functions which will set the value of the given
// promise on success or set the exception on error.
// The promise will be bound to the handler function.
template<typename T>
boost::function<
void(const Client::ErrorCodeType&, const typename T::OptionalType&)>
PromiseHandler(boost::shared_ptr<boost::promise<T> > pr)
{
struct local
{
static void Handle(const Client::ErrorCodeType& err,
const typename T::OptionalType& response,
boost::shared_ptr<boost::promise<T> > result)
{
if (err || !response)
{
result->set_exception(
boost::copy_exception(boost::system::system_error(err)));
return;
}
result->set_value(*response);
}
};
return boost::bind(local::Handle, ::_1, ::_2, pr);
}
// Overload of the above function for boolean promises.
// We will use this as handler for the re-connect operation.
boost::function<void(const Client::ErrorCodeType&)>
PromiseHandler(boost::shared_ptr<boost::promise<bool> > pr)
{
struct local
{
static void Handle(const Client::ErrorCodeType& err,
boost::shared_ptr<boost::promise<bool> > result)
{
if (err)
{
result->set_exception(
boost::copy_exception(boost::system::system_error(err)));
return;
}
result->set_value(true);
}
};
return boost::bind(local::Handle, ::_1, pr);
}
// Discover the coordinating broker for the given consumer group.
// The function schedules a ConsumerMetadata request. The returned future
// object is used to wait for the requested data to be available.
boost::BOOST_THREAD_FUTURE<ConsumerMetadataResponse>
DiscoverCoordinator(Client& client, const String& consumer_group)
{
boost::shared_ptr<boost::promise<ConsumerMetadataResponse> >
result(new boost::promise<ConsumerMetadataResponse>());
ConsumerMetadataRequest request;
request.set_consumer_group(consumer_group);
client.AsyncRequest(request, PromiseHandler(result));
return result->get_future();
}
// Re-connects the given client to the provided hostname and port.
// This also shows how the client can be connected without scheduling a request.
// Again, the returned future is used to wait until the operation completes
// successfully.
boost::BOOST_THREAD_FUTURE<bool>
ReConnect(Client& client, const String& hostname, Int32 port)
{
boost::shared_ptr<boost::promise<bool> > result(new boost::promise<bool>());
client.Close();
client.AsyncConnect(hostname, port, PromiseHandler(result));
return result->get_future();
}
// Fetch offset data for the given consumer group and topic-partition.
// Same as above: the function returns a future object.
boost::BOOST_THREAD_FUTURE<OffsetFetchResponse>
FetchOffset(Client& client,
const String& consumer_group,
const String& topic_name,
Int32 partition)
{
boost::shared_ptr<boost::promise<OffsetFetchResponse> >
result(new boost::promise<OffsetFetchResponse>());
OffsetFetchRequest request;
request.set_consumer_group(consumer_group);
request.FetchOffset(topic_name, partition);
client.AsyncRequest(request, PromiseHandler(result));
return result->get_future();
}
// The starting point of our program...
int main(int argc, char **argv)
{
// Run all IO work inside of another thread.
// All request handlers are invoked from inside that thread as well.
boost::asio::io_service ios;
boost::asio::io_service::work work(ios);
boost::thread worker(boost::bind(&boost::asio::io_service::run, &ios));
// Construct a `libkafka_asio` client object
Client::Configuration configuration;
configuration.auto_connect = true;
configuration.client_id = "libkafka_asio_example";
configuration.socket_timeout = 2000;
configuration.AddBrokerFromString("192.168.59.104:49158");
String consumer_group = "ExampleGroup";
String topic_name = "example";
Int32 partition = 0;
Client client(ios, configuration);
try
{
// First get the broker that is currently coordinating the offset management
ConsumerMetadataResponse coordinator =
DiscoverCoordinator(client, consumer_group).get();
// Then re-connect the client to the coordinator
bool is_connected =
ReConnect(client,
coordinator.coordinator_host(),
coordinator.coordinator_port()).get();
// Finally, fetch offset data from the coordinator and print it
if (is_connected)
{
OffsetFetchResponse offset =
FetchOffset(client, consumer_group, topic_name, partition).get();
std::cout
<< "Offset: " << offset.topics()[0].partitions[0].offset
<< std::endl;
}
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
ios.stop();
worker.join();
return 0;
}
|
9681a611ac8358faf324ee96ab4bd9b7075de3cc | cae0243512e1614fc9ef945713c9499d1a56d389 | /src/testers/tester_daniel_restart.cpp | 99b36d5424193287bce183939c5d17050afcf18b | [] | no_license | alejandro-reyesamaro/POSL | 15b5b58a9649234fa9bedbca4393550d38a69e7d | 0b3b7cf01a0392fc76394bbc04c52070637b3009 | refs/heads/master | 2021-04-15T11:10:24.998562 | 2016-09-06T15:10:54 | 2016-09-06T15:10:54 | 33,991,084 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | tester_daniel_restart.cpp | #include "tester_daniel_restart.h"
#include "../data/solution.h"
#include "../modules/operation_module.h"
#include "../modules/om_fixed_first_configuration.h"
#include "../modules/om_daniel_as_restart_processing.h"
#include "../modules/grouped_sequential_computation.h"
#include "../operators/sequential_exec_operator.h"
Tester_DanielRestart::Tester_DanielRestart(int argc, char *argv[])
: Tester(argc, argv)
{}
string Tester_DanielRestart::test()
{
shared_ptr<Benchmark> bench(make_shared<CostasArray>(15));
shared_ptr<PSP> psp(make_shared<PSP>(bench));
//[ 12, 9, 0, 13, 1, 7, 8, 6, 11, 3, 2, 5, 14, 10, 4 ] - [ 13, 10, 1, 14, 2, 8, 9, 7, 12, 4, 3, 6, 15, 11, 5 ]
vector<int> conf ({12, 9, 0, 13, 1, 7, 8, 6, 11, 3, 2, 5, 14, 10, 4 });
bench->SetDefaultConfiguration(conf);
shared_ptr<OperationModule> om_s(make_shared<OM_FixedFirstConfiguration>(bench));
shared_ptr<OperationModule> om_r(make_shared<OM_DanielASRestartProcessing>());
shared_ptr<Operator> op(make_shared<SequentialExecOperator>(om_s, om_r));
shared_ptr<GroupedComputation> G(make_shared<GroupedSequentialComputation>(op));
shared_ptr<Solution> solution = static_pointer_cast<Solution>(G->execute(psp, t_seed));
cout << solution->configurationToString() << endl;
return "OM_Daniel_Reset: OK !"; // : "OM_Daniel_Reset: fail :/";
}
|
9cc759ed32dee3a047986f9abce501df64092557 | b4efea02cb77bb02f14cd79a7b6243ca3fae3b14 | /utils/test_harness/tools/sysman/src/test_harness_sysman_psu.cpp | 80482a495006fe1ceadc0f47c7a222c3cb4deae2 | [
"MIT"
] | permissive | wrrobin/level-zero-tests | 47730040b0a9e1220c76b5955134cd1451898db5 | 723749cb22e6f8648ee9c781dd632d7288fab74b | refs/heads/master | 2022-11-13T19:35:48.223393 | 2020-06-29T18:41:36 | 2020-06-30T01:31:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | test_harness_sysman_psu.cpp | /*
*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "test_harness/test_harness.hpp"
#include <level_zero/ze_api.h>
#include "utils/utils.hpp"
namespace lzt = level_zero_tests;
namespace level_zero_tests {
uint32_t get_psu_handles_count(ze_device_handle_t device) {
uint32_t count = 0;
zet_sysman_handle_t hSysman = lzt::get_sysman_handle(device);
EXPECT_EQ(ZE_RESULT_SUCCESS, zetSysmanPsuGet(hSysman, &count, nullptr));
EXPECT_GT(count, 0);
return count;
}
std::vector<zet_sysman_psu_handle_t> get_psu_handles(ze_device_handle_t device,
uint32_t &count) {
zet_sysman_handle_t hSysman = lzt::get_sysman_handle(device);
if (count == 0) {
count = get_psu_handles_count(device);
}
std::vector<zet_sysman_psu_handle_t> psuHandles(count);
EXPECT_EQ(ZE_RESULT_SUCCESS,
zetSysmanPsuGet(hSysman, &count, psuHandles.data()));
return psuHandles;
}
zet_psu_properties_t get_psu_properties(zet_sysman_psu_handle_t psuHandle) {
zet_psu_properties_t properties;
EXPECT_EQ(ZE_RESULT_SUCCESS,
zetSysmanPsuGetProperties(psuHandle, &properties));
return properties;
}
zet_psu_state_t get_psu_state(zet_sysman_psu_handle_t psuHandle) {
zet_psu_state_t state;
EXPECT_EQ(ZE_RESULT_SUCCESS, zetSysmanPsuGetState(psuHandle, &state));
return state;
}
} // namespace level_zero_tests
|
7d8375df34b1c77d4422d9a6efcb12bea0ff0c96 | c8fe9838c4776012da2281f40fbfa6fa85b37489 | /include/mico/expressions/character.h | 815e08fdd77fe58a155e9461d7528a0dae1d3d0b | [
"MIT"
] | permissive | newenclave/mico | 7a27cfcb600d581886efce6c4cd63975ce3c7555 | 7d3616e01cc2881688cdc803b990ccf791e1120a | refs/heads/master | 2023-04-07T15:47:55.032628 | 2023-03-21T12:27:36 | 2023-03-21T12:27:36 | 94,879,752 | 45 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | h | character.h | #ifndef MICO_EXPRESSIONS_CHAR_H
#define MICO_EXPRESSIONS_CHAR_H
#include <sstream>
#include "mico/ast.h"
#include "mico/tokens.h"
#include "mico/expressions/impl.h"
#include "mico/types.h"
namespace mico { namespace ast { namespace expressions {
template <>
class impl<type::CHARACTER>: public typed_expr<type::CHARACTER> {
using this_type = impl<type::CHARACTER>;
public:
using value_type = mico::string::value_type;
using uptr = std::unique_ptr<this_type>;
impl( value_type val )
:value_(val)
{ }
std::string str( ) const override
{
mico::string v( 1, value_ );
return std::string("'") + charset::encoding::to_file(v) + "'";
}
value_type value( ) const
{
return value_;
}
static
uptr make( value_type val )
{
return uptr( new this_type(val ) );
}
void mutate( mutator_type /*call*/ ) override
{
}
bool is_const( ) const override
{
return true;
}
ast::node::uptr clone( ) const override
{
return uptr( new this_type(value_ ) );
}
private:
value_type value_;
};
using character = impl<type::CHARACTER>;
}}}
#endif // STRING_H
|
2355351bd5304761573d308f64823fd23abcaf4c | 6c572769cd9b9f1f2dfdac0112ca3ed42b4f8c09 | /Arduino/bpm180_toptechboy_sparkfun_SD_shield_simpleLogger/bpm180_toptechboy_sparkfun_SD_shield_simpleLogger.ino | a0f2a06e26fb8ea38b828e753750984af5481ca6 | [] | no_license | nyirock/el | 4ec12a5ded702dd041764883ca79afcab048c109 | 699c54f0f058086faf2e9ad0b25ff04a24ce5667 | refs/heads/master | 2021-01-19T04:15:57.984096 | 2016-07-06T07:30:41 | 2016-07-06T07:30:41 | 55,384,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,352 | ino | bpm180_toptechboy_sparkfun_SD_shield_simpleLogger.ino | #include <SPI.h>
#include <SD.h>
#include "Wire.h"
#include "Adafruit_BMP085.h"
Adafruit_BMP085 mySensor; // Create a pressure sensor called mySensor
float tempC;// variable to hold the temperature reading
float tempF;
float pressurePa; //variable to hold the barometric pressure in Pa
File myFile;
// On the Ethernet Shield, CS is pin 4. Note that even if it's not
// used as the CS pin, the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD library
// functions will not work.
const int chipSelect = 8;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
mySensor.begin();//initialize mySensor
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(10, OUTPUT);
// The chipSelect pin you use should also be set to output
pinMode(chipSelect, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
void loop()
{
tempC = mySensor.readTemperature();//read temperature in C
tempF = tempC*1.8 + 32.; //convert temp to F
pressurePa = mySensor.readPressure();// read pressure
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
/*for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}*/
dataString=String(tempC)+","+String(pressurePa)+","+String(millis());
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.csv", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(1000);
}
|
ba3fe48eeba6d6cf0d5bf10035768663927031cc | dd7569e4abb94aef8810257a704bf06064952b2c | /64. 合并排序数组 .cpp | f0a40f4fbeaac97f64d0f05acdc3c11492d412f5 | [] | no_license | oeljeklaus-you/LintCode | f8d5b609d4d6d68b4ae41b4dc4f34c1a1c329b3e | 2596580b01c81d29e39194cb3bf716d178b36d9c | refs/heads/master | 2020-03-17T08:48:01.393304 | 2018-06-06T01:50:38 | 2018-06-06T01:50:38 | 133,450,241 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | 64. 合并排序数组 .cpp | class Solution {
public:
/*
* @param A: sorted integer array A which has m elements, but size of A is m+n
* @param m: An integer
* @param B: sorted integer array B which has n elements
* @param n: An integer
* @return: nothing
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
// write your code here
int index=m+n;
while(n)
{
if(A[m-1]>B[n-1])
{
A[m-1+n]=A[m-1];
index=m-1+n;
m--;
}
else
{
A[index-1]=B[n-1];
index=index-1;
n--;
}
}
}
}; |
0068eb1122a811253f22fca90ddb25824167595e | 3bd35024ffd5426359a2e77007c465378996c976 | /cli/traversal/unit.hxx | 656ec728642b2983be2f9f48cccb2f318433f5f2 | [
"MIT"
] | permissive | yssource/cli | e3fae1a248ee1e13b37ed3d6ac8354590a96c1e0 | bc5ca36a3971c1572c4c27ee9372127a3962115f | refs/heads/master | 2020-04-18T03:51:54.604791 | 2014-09-18T04:24:00 | 2014-09-18T04:24:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | hxx | unit.hxx | // file : cli/traversal/unit.hxx
// author : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009-2011 Code Synthesis Tools CC
// license : MIT; see accompanying LICENSE file
#ifndef CLI_TRAVERSAL_UNIT_HXX
#define CLI_TRAVERSAL_UNIT_HXX
#include <traversal/elements.hxx>
#include <semantics/unit.hxx>
namespace traversal
{
struct cxx_includes: edge<semantics::cxx_includes>
{
cxx_includes ()
{
}
cxx_includes (node_dispatcher& n)
{
node_traverser (n);
}
virtual void
traverse (type&);
};
struct cli_includes: edge<semantics::cli_includes>
{
cli_includes ()
{
}
cli_includes (node_dispatcher& n)
{
node_traverser (n);
}
virtual void
traverse (type&);
};
struct cxx_unit: node<semantics::cxx_unit> {};
struct cli_unit: scope_template<semantics::cli_unit>
{
virtual void
traverse (type&);
virtual void
pre (type&);
virtual void
post (type&);
};
}
#endif // CLI_TRAVERSAL_UNIT_HXX
|
42037d6a59b51909bc1aed7d6dcfda0479b0eb1b | 94821aafe743907eee47d61b47b00bfff1512dfc | /Swarm_Rover_V1_0/COM_MANAGER.h | b77a6d24cf8e65382cf8309ffe7983f78178100f | [] | no_license | nlantz/Swarm_Rover | 2c827db8153189e96a9071fc1c2cd890cb83ac92 | 24da1f96b6b648b0429209d7c73aa2b8cde742e3 | refs/heads/master | 2021-01-10T19:43:33.668004 | 2014-12-23T19:15:53 | 2014-12-23T19:15:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | h | COM_MANAGER.h | #ifndef COM_MANAGER_H
#define COM_MANAGER_H
#include "Arduino.h"
class COM_MANAGER{
public:
COM_MANAGER(); //Constructor
~COM_MANAGER(); //Destructor
void transmit(unsigned long data, int nbits);
boolean transmitObjectDetect(unsigned long data, int nbits, int RxPin);
void markObjectDetect(int uSec, int RxPin);
void mark(int usec);
void space(int usec);
};
#endif
|
77820cdec9c7e42b4630894b1fbd9dd9766bf155 | 79cdd121bd78a52bbe94d0b6ab5fa11b62cbcd4b | /src/main.cc | 46158ba96d93d7eb05b5b09f12178b8a321c1756 | [] | no_license | gerarddelcastillo/ex03-threeintegersort | 34e67c526b9b48aaaf2760ec341f41b72b6a66e1 | ecaed94e694d98c17c28f7caff9b34b58bb52229 | refs/heads/master | 2020-03-30T13:48:33.915157 | 2018-12-14T18:45:33 | 2018-12-14T18:45:33 | 151,288,721 | 0 | 0 | null | 2018-10-02T16:41:27 | 2018-10-02T16:41:27 | null | UTF-8 | C++ | false | false | 137 | cc | main.cc | //
// Created by Gerard Del Castillo on 11/28/2018.
//
#include <algorithm>
#include <threeintegersort.h>
int main() {
return 0;
} |
a636f990ae378f88a15e484c5376d216fc4e7f31 | 7246f7795ba754d05b0868b9c887f8d650f37a46 | /ProjetPriseDeNote/latexexport.h | f74422df7df3dd0962bfde034dc617c985ca5602 | [] | no_license | Simobain/MotDit | 736ebc16262e2ae4184e8029a6bdb3b55b7c05a5 | 4bfa7ac8882b3f61b69e0615cc624fbde8d0a49c | refs/heads/master | 2021-01-19T19:37:49.636026 | 2013-06-16T22:04:03 | 2013-06-16T22:04:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,608 | h | latexexport.h | #ifndef TEXEXPORT_H
#define TEXEXPORT_H
#include "exportstrategy.h"
/*!
* \file latexexport.h
* \brief Classe LaTexExport : permet d'exporter les notes en LaTex
* \author Pauline Cuche/Simon Robain
*/
/*!
* \class LaTexExport
* \brief Cette classe permet d'exporter les différents types de notes en LaTex.
*Elle hérite de ExportStrategy
*/
class LaTexExport : public ExportStrategy
{
public:
/*!
* \brief Constructeur Par Defaut
*
* Constructeur par défaut de la classe LaTexExport
*/
LaTexExport();
/*!
* \brief Cette methode permet de rentrer les balises ouvrantes d'un fichier .Tex
*/
QString header(Note*);
/*!
* \brief Cette methode permet de rentrer les balises fermantes d'un fichier .Tex
*/
QString footer(Note*);
/*!
* \brief Cette methode permet d'exporter un Document en LaTex
*/
QString exportNote(Document* d , unsigned int titreLvl);
/*!
* \brief Cette methode permet d'exporter un Article en LaTex
*/
QString exportNote(Article* a , unsigned int titreLvl);
/*!
* \brief Cette methode permet d'exporter une Video en LaTex
*/
QString exportNote(Video* v , unsigned int titreLvl);
/*!
* \brief Cette methode permet d'exporter un Audio en LaTex
*/
QString exportNote(Audio* a , unsigned int titreLvl);
/*!
* \brief Cette methode permet d'exporter une Image en LaTex
*/
QString exportNote(Image* i , unsigned int titreLvl);
};
#endif // TEXEXPORT_H
|
0818279955933315077bae704761321320a36cf2 | 82989fa5beaa922e41e664c3a861207b6f54223a | /1/1.22/1.22.cpp | 990ecf6061fb3b3105e2ffd88b26f1f86d8045c0 | [] | no_license | didizlatkova/cpp-primer | 40d54f8f0fba70d344d3851a937db5af0d136176 | 61aa1a0e896be4401f972af6826d507c90c3934a | refs/heads/master | 2021-01-21T22:19:46.992176 | 2017-03-12T11:23:26 | 2017-03-12T11:23:26 | 102,150,498 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | 1.22.cpp | /*
Write a program that reads several transactions for the same
ISBN . Write the sum of all the transactions that were read.
*/
#include <iostream>
#include "../Book Resources/1/Sales_item.h"
using namespace std;
int main()
{
Sales_item item, sum;
cin >> item;
sum = item;
while(cin>>item)
{
sum += item;
}
cout << "Sum is: " << sum << endl;
return 0;
} |
0f1d16239d9c58f2defae922526fc5d4c2740b12 | e316c998ec4a529761ab7716d3925662850dcdf4 | /main.cpp | 1dae9d7672bc95b3ea568d78c2dd13b28ee6c65f | [] | no_license | ncheneld/alphabet-soup | 097dd70a6c5f2894d6170855456d824284fc52f9 | d80584c179cb140791786d904bb2ac4e0d86e16e | refs/heads/master | 2021-03-31T16:32:44.090851 | 2020-03-20T16:28:45 | 2020-03-20T16:28:45 | 248,119,784 | 0 | 0 | null | 2020-03-18T02:26:50 | 2020-03-18T02:26:49 | null | UTF-8 | C++ | false | false | 2,040 | cpp | main.cpp | /*
main.cpp is the driver for WordSearch.
------------------------------------------
- It takes in a file from the command line
i.e. ./{program} inFile.txt
- Input Example
3x3
A B C
D E F
G H I
ABC
AEI
Other Notes:
compiled using g++ -o -g program main.cpp WordSearch.cpp
ran using ./program test.txt
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include "WordSearch.h"
using namespace std;
void ReadFile(WordSearch &WordSearch, string filename);
int main(int argc, char *argv[])
{
string filename = argv[1];
WordSearch WordSearch;
ReadFile(WordSearch, filename);
WordSearch.Search();
WordSearch.Print();
return 0;
}
void ReadFile(WordSearch &WordSearch, string filename)
{
vector<int> rows;
int sizeA;
int sizeB;
char letter;
char temp;
string getWord = "";
try
{
ifstream myFile;
myFile.open(filename);
// reading the dimensions of the grid
myFile >> sizeA;
myFile >> temp;
myFile >> sizeB;
WordSearch.set(sizeA, sizeB);
// storing the grid
for (int i = 0; i < sizeA; ++i)
{
for (int j = 0; j < sizeB; ++j)
{
myFile >> letter;
rows.push_back(letter);
}
WordSearch.Grid.push_back(rows);
rows.clear();
}
// to get to the next line to start reading the words
getline(myFile, getWord);
// reading in the list of words
while (getline(myFile, getWord))
{
Words insertWord;
insertWord.Word = getWord;
insertWord.Word.erase(remove_if(insertWord.Word.begin(), insertWord.Word.end(), ::isspace), insertWord.Word.end());
WordSearch.WordList.push_back(insertWord);
}
myFile.close();
}
catch(const std::exception& e)
{
cerr << e.what() << '\n';
}
}
|
f5ad065659d7faa1ddacfa8c1194f12a6e126ee3 | 4c75d7861be66659a1cfc499e764fc305fab30df | /CCKVDemo/CCKVDemo/OpenSSL/crypto/aes/openSSL_aes_ecb.cpp | 4b83df3ae0f414b9b7947a1e5bf136cad6ee06a5 | [] | no_license | huary/CCKV | 85df73201914bb16a2be5ce375de71f64501478d | ae6028922ac0160e4283e111e40f4136081ddfbb | refs/heads/master | 2021-06-24T23:38:02.703930 | 2019-09-29T09:34:01 | 2019-09-29T09:34:01 | 210,117,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | openSSL_aes_ecb.cpp | /*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <assert.h>
#include "openSSL_aes.h"
#include "openSSL_aes_locl.h"
namespace openSSL {
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc)
{
assert(in && out && key);
assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
if (AES_ENCRYPT == enc)
AES_encrypt(in, out, key);
else
AES_decrypt(in, out, key);
}
}
|
4dc24583bca5a2f639019ba69d9816c60619e619 | 4b6343d8750b61eedcabb61b0f9459c22d6ed8d0 | /task/server.cpp | 18204b992683a45ad735b937712faf5fb70c608c | [] | no_license | zahoussem/grub_freq_aware | 571f0475c3ed4a3fb52c2bd354aa34a0364f6930 | b999f651d05f685ba974adcf91e1986374c48fde | refs/heads/master | 2021-01-14T03:09:09.961730 | 2020-06-29T13:58:05 | 2020-06-29T13:58:05 | 242,581,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,890 | cpp | server.cpp | #include "server.hpp"
namespace task
{
/**
* The Constructor of the Class server
* @param budget The budget that is allocated to the current server
* @param T The period of the server
*/
Server::Server(double budget, double T)
{
this->budget = budget;
this->T = T;
this->v = 0;
this->remaining = 0;
this->d = 0;
this->state = INACTIVE;
this->bw = budget / T;
}
/**
* The destructor of the class server
*/
Server::~Server()
{
}
/**
* Getter of state
*/
int Server::_state()
{
return this->state;
}
/**
* setter of state
* @param state The state to set
*/
void Server::_state(int state)
{
this->state = state;
}
/**
* Getter of Ts
*/
double Server::_T()
{
return this->T;
}
/**
* setter of Ts
* @param Ts The Ts to set
*/
void Server::_T(double T)
{
this->T = T;
}
/**
* Getter of d
*/
double Server::_d()
{
return this->d;
}
/**
* setter of d
* @param d The d to set
*/
void Server::_d(double d)
{
this->d = d;
}
/**
* Postpones the current server absolute deadline
*/
void Server::postpone_d()
{
this->d += this->T;
}
/**
* Getter of budget
*/
double Server::_budget(double speed)
{
return this->budget/speed;
}
/**
* setter of budget
* @param budget The budget to set
*/
void Server::_budget(double budget, double speed)
{
this->budget = budget/speed;
}
/**
* Getter of v
*/
double Server::_v()
{
return this->v;
}
/**
* setter of v
* @param v The v to set
*/
void Server::_v(double v)
{
this->v = v;
}
/**
* Computing the remaining time to finish the server budget
*/
void Server::compute_remaining()
{
// Houssam : Computes ramaining execution time
}
/**
* Updating the virtual time
*/
void Server::update_v()
{
// Houssam : Computes the virtual time!!
// Need to compute the elapsed time from the latest current
}
/**
* Getter of remaining
*/
double Server::_remaining()
{
return this->remaining;
}
/**
* setter of remaining
* @param remaining The remaining to set
*/
void Server::_remaining(double remaining)
{
this->remaining = remaining;
}
/**
* Getter of bw
*/
double Server::_bw(double speed)
{
return this->bw/speed;
}
/**
* setter of bw
* @param bw The bw to set
*/
void Server::_bw(double bw, double speed)
{
this->bw = bw/speed;
}
/**
* Arms the active contending times
* @param time The time to wait before signaling
* return false if the operation fails
*/
bool Server::arm_act_cont_timer(double time)
{
// Houssam : This function adds an event of active_contending to the event list
return 0;
}
} // namespace task
|
40d10931011a8884870a5a8ea904fde4ccbfc9d2 | 86d197c0e128dbc715771bdbab45f2000f0dc08f | /src/main.cpp | 8f5762895ef54ebb0505b99094f492fa3ceb5973 | [] | no_license | HarbingTarbl/Nemu | 5fc9af4c1fb8580ca5f3e44d1ad378f84a5b2e6f | fd73c04e7455d300dc3deca57af30fbc024e7a8f | refs/heads/master | 2021-01-02T22:57:08.772966 | 2014-04-22T02:02:01 | 2014-04-22T02:02:01 | 16,090,089 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | cpp | main.cpp | #include "VMemory.hpp"
#include "CPU.hpp"
#include "NES.hpp"
#include "Renderer.hpp"
#include "OpCodes.hpp"
#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
int main(int argc, const char* args[])
{
using namespace std;
bool Ok = true;
try
{
Render::Initalize(800, 600);
}
catch (exception& e)
{
Ok = false;
cout << "Could not initalize window : " << e.what() << endl;
}
NES Nemu;
if (!Ok)
{
cin.get();
return 1;
}
try
{
if (argc != 2)
{
cout << "Usage: Nemu rom_file_path" << endl;
return 1;
}
Nemu.mCart.LoadROM(args[1]);
Nemu.mCPU.HardReset();
Nemu.mPPU.Reset();
}
catch (exception& e)
{
Ok = false;
cout << "Could not load NES : " << e.what() << endl;
}
if (!Ok)
{
cin.get();
return 2;
}
while (Render::WindowOpen())
{
while (Render::WindowOpen())
{
Nemu.mPPU.Cycle(Nemu.mCPU.Cycle());
}
if (Render::FrameComplete)
Render::BeginFrame();
else
Render::EndFrame();
}
//vector<uint16_t> image;
//fstream imageFile("image.clr", fstream::in | fstream::binary);
//imageFile.seekg(0, imageFile.end);
//image.resize(imageFile.tellp() / 2);
//imageFile.seekg(0, imageFile.beg);
//imageFile.read((char*)image.data(), image.size() * 2);
//imageFile.close();
//while (Render::WindowOpen())
//{
// Render::BeginFrame();
// for (int i = 0; i < 240; i++) //Render 240 scanlines
// {
// Render::BeginScanline(0);
// memcpy(Render::PixelOut, image.data() + i * 256, 256 * sizeof(Render::Pixel));
// Render::EndScanline();
// }
// Render::EndFrame();
//}
//Render::Terminate();
return 0;
} |
64ab7fb35c08115926705225c58ee270f56ecc94 | 25118489134e3607131dc21ee3fc541ec419a66e | /Generation.h | f29e9eba8992cfd9fc286bea2b259e04d6504251 | [] | no_license | RuzickaJiri/Software_deployment | b84a31e919ba55f0d681d9d9cb11c333c3e3303b | 2a4fdccc0455bbdefafad15b8b923dadb2003559 | refs/heads/master | 2020-05-18T00:59:49.611405 | 2019-05-30T14:56:56 | 2019-05-30T14:56:56 | 184,077,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | h | Generation.h | #include "Tree.h"
#include "Operator.h"
#include <iostream>
#ifndef GEN_
#define GEN_
class Generation{
public :
Generation(size_t size,std::vector<std::string> xlabels);
~Generation();
Tree GetBestIndividual( bool **x, int y[], int x_size) const;
std::string GetBestFormula(bool **x, int y[], int x_size) const;
void set_fitness(bool **x,int y[], int x_size);
//Generation Evolve(int n,int x,int y,int record) const;//std::vector<std::string> xlabels
Generation* Evolve(int n, bool **x,int y[],int x_size, int record,std::string* bestIndividual_ );
void PrintTree();
void AppendTree(Tree t);
void set_nbr_trees(size_t a);
size_t size();
float * fit();
protected :
Tree * Trees_;
size_t nbr_trees_;
size_t size_;
std::vector<std::string> xlabels_;
float* fit_;
};
#endif
|
3b9cc49ea3922ea6e9bec965b5e5d78b8b77364d | 3d44ba3949e4e227337b22f55a1abfd51bfcac41 | /cachelab-handout/algoquedijoelprof.cpp | aecb0521c6a371f88eed5e912767af477de82990 | [] | no_license | tatianacv/ComputerArchitecture | 7d49cbdc58b9a036b2f3cacc6fbb0ad010efef6f | ac4ceafcaac7bc99464adff24e442c048fc3e087 | refs/heads/master | 2021-01-01T23:42:53.943850 | 2020-02-10T00:24:05 | 2020-02-10T00:24:05 | 239,395,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74 | cpp | algoquedijoelprof.cpp | fid=fopen(nombre del file, 'r');
fscanf(fid, " %c %llx, $d", &c, &a, &n);
|
edb5ec4b881069701f34b2051873d96d0f1935ac | eec6fc365c7415835b4a69eaceb23a224f2abc47 | /BaekJoon/2020/게임 (1072번).cpp | 509746cbf88e6926ae7f64a2a1bec9a2837f709e | [] | no_license | chosh95/STUDY | 3e2381c632cebecc9a91e791a4a27a89ea6491ea | 0c88a1dd55d1826e72ebebd5626d6d83665c8431 | refs/heads/master | 2022-04-30T23:58:56.228240 | 2022-04-18T13:08:01 | 2022-04-18T13:08:01 | 166,837,216 | 3 | 1 | null | 2019-06-20T10:51:49 | 2019-01-21T15:32:03 | C++ | UTF-8 | C++ | false | false | 474 | cpp | 게임 (1072번).cpp | #include <iostream>
#include <algorithm>
using namespace std;
long long X, Y, Z;
long long res = 987654321;
void bisearch() {
long long lo = 0, hi = 1000000000;
while (lo <= hi) {
long long mid = (lo + hi) / 2;
long long z = ((Y + mid) * 100) / (X + mid);
if (z > Z) {
hi = mid - 1;
}
else {
res = mid + 1;
lo = mid + 1;
}
}
}
int main()
{
cin >> X >> Y;
Z = (Y*100) / X;
if (Z >= 99) {
cout << -1;
return 0;
}
bisearch();
cout << res;
} |
3139dca03e4e45f9d5fbbbb967ee4dfb68431207 | c45b28dc411206a3846c4e05a048b328e83a3b80 | /Graph/adjMatrix.cpp | 3b876e1bd0e3c6c23410b244d1d09b3e26828b3e | [] | no_license | Anurag313y/Ds-algo | 4023b0086e7c127b169f70deeecf6ca0a80c69c9 | 2f026156f634055bc5207552e7860a19183ba591 | refs/heads/main | 2023-08-19T15:58:24.065963 | 2021-09-29T06:47:59 | 2021-09-29T06:47:59 | 411,556,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | cpp | adjMatrix.cpp | /////Adjancy Matrix of Undirected Graph
#include<bits/stdc++.h>
using namespace std;
int main()
{
///size of matrix (n x m)
int n,m;
cin>>n>>m;
vector<vector<int>> adjm(n+1, vector<int>(n+1,0));
for(int i=0; i<m;i++){
int x,y;
cin>>x>>y;
adjm[x][y] = 1;
adjm[y][x] = 1;
}
cout<<"our adjancy matrix is:"<<endl;
for(int i=1; i<n+1;i++){
for(int j=1; j<n+1;j++){
cout<<adjm[i][j]<<" ";
}cout<<endl;
}
return 0;
}
///input:
// 7 7
// 1 2
// 1 3
// 2 4
// 2 5
// 2 6
// 2 7
// 7 3
// output:
// our adjancy matrix is:
// 0 1 1 0 0 0 0
// 1 0 0 1 1 1 1
// 1 0 0 0 0 0 1
// 0 1 0 0 0 0 0
// 0 1 0 0 0 0 0
// 0 1 0 0 0 0 0
// 0 1 1 0 0 0 0 |
36903d6f1a999ee9dc84c68346ac0c6a3983fb6c | 045cc95f97998eaa1cb6f3abff69d8589b26fefa | /Chapter5/Chapter5_Exercise14.cpp | 10faa7c25d43dced3cfe027c615dd4f40f9f268a | [] | no_license | Simkod/learncpp | 481934d4b4a1f2097bb90f3e034e017f9540bc00 | d563e36b6b9e9fdbef8ca8800d653c08b4ff2e2b | refs/heads/master | 2020-05-17T23:21:41.377435 | 2019-11-08T09:10:30 | 2019-11-08T09:10:30 | 184,030,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,389 | cpp | Chapter5_Exercise14.cpp |
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <numeric>
#include <algorithm>
using namespace std;
enum DayName
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
class Day
{
public:
Day();
Day(DayName name);
~Day();
vector<int> getValues() const
{
return m_values;
}
void addValue(int number)
{
m_values.push_back(number);
}
DayName getName()
{
return m_name;
}
private:
DayName m_name;
vector<int> m_values;
};
Day::Day()
{
}
Day::Day(DayName name)
: m_name(name)
{
}
Day::~Day()
{
}
void initializeAcceptedDayExpressions(multimap<DayName, string>* acceptedDayExpressions)
{
acceptedDayExpressions->insert(pair<DayName, string>(Monday, "mon"));
acceptedDayExpressions->insert(pair<DayName, string>(Monday, "monday"));
acceptedDayExpressions->insert(pair<DayName, string>(Tuesday, "tue"));
acceptedDayExpressions->insert(pair<DayName, string>(Tuesday, "tuesday"));
acceptedDayExpressions->insert(pair<DayName, string>(Wednesday, "wed"));
acceptedDayExpressions->insert(pair<DayName, string>(Wednesday, "wednesday"));
acceptedDayExpressions->insert(pair<DayName, string>(Thursday, "thu"));
acceptedDayExpressions->insert(pair<DayName, string>(Thursday, "thursday"));
acceptedDayExpressions->insert(pair<DayName, string>(Friday, "fri"));
acceptedDayExpressions->insert(pair<DayName, string>(Friday, "friday"));
acceptedDayExpressions->insert(pair<DayName, string>(Saturday, "sat"));
acceptedDayExpressions->insert(pair<DayName, string>(Saturday, "saturday"));
acceptedDayExpressions->insert(pair<DayName, string>(Sunday, "sun"));
acceptedDayExpressions->insert(pair<DayName, string>(Sunday, "sunday"));
}
bool dayAlreadyAdded(vector<Day>* checkVector, DayName dayName)
{
if (checkVector->empty())
{
return false;
}
for (vector<Day>::const_iterator vectIt = checkVector->begin(); vectIt != checkVector->end(); ++vectIt)
{
Day day = *vectIt;
if (day.getName() == dayName)
{
return true;
}
}
return false;
}
Day* findDayfromName(DayName name, vector<Day>* searchVector)
{
for (vector<Day>::iterator vectIt = searchVector->begin(); vectIt != searchVector->end(); ++vectIt)
{
Day day = *vectIt;
if (day.getName() == name)
{
return &(*vectIt);
}
}
return NULL;
}
bool isDayInputAccepted(string inputDay, multimap<DayName, string>* acceptedExpressions)
{
for (multimap<DayName, string>::const_iterator it = acceptedExpressions->begin(); it != acceptedExpressions->end(); it++)
{
if (it->second == inputDay)
{
return true;
}
}
return false;
}
DayName getDayNameForInput(string inputDay, multimap<DayName, string>* acceptedExpressions)
{
DayName outputName;
for (multimap<DayName, string>::const_iterator it = acceptedExpressions->begin(); it != acceptedExpressions->end(); it++)
{
if (it->second == inputDay)
{
outputName = it->first;
return outputName;
}
}
}
string dayNameToString(DayName dayName)
{
string nameAsString;
switch (dayName)
{
case Monday: nameAsString = "Monday"; break;
case Tuesday: nameAsString = "Tuesday"; break;
case Wednesday: nameAsString = "Wednesday"; break;
case Thursday: nameAsString = "Thursday"; break;
case Friday: nameAsString = "Friday"; break;
case Saturday: nameAsString = "Saturday"; break;
case Sunday: nameAsString = "Sunday"; break;
default: nameAsString = dayName; break;
}
return nameAsString;
}
void printSumOfDayValues(vector<Day>* daysVector)
{
cout << endl;
for (vector<Day>::const_iterator vectIt = daysVector->begin(); vectIt != daysVector->end(); ++vectIt)
{
Day day = *vectIt;
vector<int> values = day.getValues();
int valuesSum = accumulate(values.begin(), values.end(), 0);
string dayName = dayNameToString(day.getName());
cout << dayName << ":\t\t" << valuesSum;
cout << endl;
}
cout << endl;
}
void printInvalidDayInputs(int invalidInputsNumber)
{
cout << "Number of invalid day inputs: " << invalidInputsNumber << endl;
cout << endl;
}
int main()
{
multimap<DayName, string>* acceptedDayExpressions = new multimap<DayName, string>;
initializeAcceptedDayExpressions(acceptedDayExpressions);
vector<Day>* days = new vector<Day>;
int invalidDayInputcounter(0);
//get inputs from user
while (true)
{
bool quitExecution(false);
DayName dayName;
bool dayInputValid(false);
while (!dayInputValid)
{
cout << "Add a day. If you don't want to add more, type 'DONE': ";
cin.clear();
string day;
cin >> day;
cout << endl;
if (day == "DONE")
{
quitExecution = true;
break;
}
transform(day.begin(), day.end(), day.begin(), ::tolower);
if (cin.fail() || !isDayInputAccepted(day, acceptedDayExpressions))
{
cout << "Problem with day input. Try again." << endl;
dayInputValid = false;
++invalidDayInputcounter;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
else if (isDayInputAccepted(day, acceptedDayExpressions))
{
dayName = getDayNameForInput(day, acceptedDayExpressions);
dayInputValid = true;
break;
}
}
if (quitExecution) break;
//Value input
int value;
bool valueInputValid(false);
while (!valueInputValid)
{
cout << "Add a value to the day: ";
cin.clear();
cin >> value;
cout << endl;
if (cin.fail())
{
cout << "Problem with value input. Try again." << endl;
valueInputValid = false;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
else
{
valueInputValid = true;
break;
}
}
if (dayInputValid && valueInputValid)
{
//check if day is already in days vector
if (!dayAlreadyAdded(days, dayName))
{
Day newDay(dayName);
days->push_back(newDay);
}
findDayfromName(dayName, days)->addValue(value);
}
else
{
cout << "Input Problem.";
}
}
//Output
printSumOfDayValues(days);
printInvalidDayInputs(invalidDayInputcounter);
system("pause");
} |
2fd43988e59c419a5c80ee18bf4ac5d828862c4b | 3b5c5ec5b76df1b6a6b9af292e25e41c984212e2 | /test/uvcpp/req.cc | 8df896cfffe6656651f6f2d688443a905edfa0a0 | [] | no_license | neevek/uvcpp | 75d200e27a4c533e9df36dc77e5ba6aeda37c7a7 | a1cc04b25e360e9ae390751d5e6153706a69293f | refs/heads/master | 2021-07-17T14:01:37.321060 | 2020-05-05T06:11:23 | 2020-05-05T06:13:34 | 141,360,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cc | req.cc | #include <gtest/gtest.h>
#include "uvcpp.h"
using namespace uvcpp;
TEST(Req, DNSRequestResolveLocalHost) {
auto loop = std::make_shared<Loop>();
ASSERT_TRUE(loop->init());
auto req = DNSRequest::create(loop);
req->selfRefUntil<EvDNSRequestFinish>();
req->once<EvError>([](const auto &e, auto &r) {
FAIL() << "failed with status: " << e.status;
});
req->once<EvDNSResult>([](const auto &e, auto &tcp) {
ASSERT_GT(e.dnsResults.size(), 0);
for (auto &ip : e.dnsResults) {
auto result = "::1" == ip || "127.0.0.1" == ip;
ASSERT_TRUE(result);
}
});
req->resolve("localhost");
loop->run();
}
TEST(Req, DNSRequest0000) {
auto loop = std::make_shared<Loop>();
ASSERT_TRUE(loop->init());
auto req = DNSRequest::create(loop);
req->selfRefUntil<EvDNSRequestFinish>();
req->once<EvError>([](const auto &e, auto &r) {
FAIL() << "failed with status: " << e.status;
});
req->once<EvDNSResult>([](const auto &e, auto &tcp) {
ASSERT_EQ(e.dnsResults.size(), 1);
ASSERT_STREQ("0.0.0.0", e.dnsResults[0].c_str());
});
req->resolve("0.0.0.0");
loop->run();
}
|
98bfc625ec792df362abaf05c7f8ceb27de453a6 | 6bb5139002378822b2fcc085ffb7a30d8e661cd6 | /YIN/motor_line2/motor_line2.ino | 6145db73e47bf781c9e6409d77299f7e08d00a80 | [] | no_license | maroro0220/arduino_basic | 8e1d419e6e60838952ffa238eddce456f82c6c7f | b0e878afeb2b46ea5e056a4ca3f0e4c8ff2a5daf | refs/heads/master | 2021-01-15T22:19:00.038439 | 2017-11-08T03:32:51 | 2017-11-08T03:32:51 | 99,896,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,730 | ino | motor_line2.ino | // IN1, IN2, ENA (D2, D4, D5), IN3, IN4, ENB (D7, D8, D9)
//http://www.hardcopyworld.com/ngine/aduino/index.php/archives/159
#define IN1 2
#define IN2 4
#define ENA 5
#define IN3 9
#define IN4 7
#define ENB 6
#define SPEED 150
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
attachInterrupt(1, motor, LOW);
delay(2000);
Serial.begin(9600);
}
int line;
void lineBackward(){
Backward(150);
delay(5000);
}
void Forward(int speed){
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, speed);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
analogWrite(ENB, speed);
}
void Backward(int speed){
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
analogWrite(ENB, speed);
}
void Left(int speed){
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
analogWrite(ENB, speed);
}
void Right(int speed){
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, speed);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
analogWrite(ENB, speed);
}
void Stop(int speed){
analogWrite(ENA, 0);
analogWrite(ENB, 0);
}
void motor(){
int rm=random(5);
int tim=random(3,10);
Serial.println(analogRead(0)/700);
Serial.print("random: ");
Serial.print(rm);
Serial.print("\n tim: ");
Serial.print(tim);
switch(rm){
case 0:
Serial.print("\nForward");
Forward(SPEED);
delay(1000*tim);
break;
case 1:
Serial.print("\Backward");
Backward(SPEED);
delay(1000*tim);
break;
case 2:
Serial.print("\nLeft");
Left(SPEED);
delay(500*tim);
break;
case 3:
Serial.print("\nRight");
Right(SPEED);
delay(500*tim);
break;
case 4:
Serial.print("\nStop");
Stop(SPEED);
delay(100*tim);
break;
}
}
void loop() {
Stop(SPEED);
delay(1000);
lineBackward();
int ir ;
// int line;
// ir= analogRead(0)/700;
// Serial.println(ir);
//line=ir;
//if(!line){
//while(analogRead(0)>=800){
// }
// }
// while(analogRead(0)<800){
// Serial.println(analogRead(0));
// Backward(150);
// delay(5000);
// }
// else if(line){
// Backward(150);
// delay(5000);
// line=!line;
// }
}
|
24444534c2d93413c2dbabb7ccd6cfdac5893058 | d501850612acfcc3434d886a1393e279f1fb8445 | /1089.cpp | d26eba8b7ef5d035b913f1747065f7b1cf3a49ed | [] | no_license | crrflying/C | c9c3e53e03475a7f603c3b6740811d428eb189a6 | 3160a14b98f6c7809ec89bebc462e1a764c4c633 | refs/heads/master | 2020-05-22T06:06:33.151036 | 2019-05-12T11:41:21 | 2019-05-12T11:41:21 | 186,247,161 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 992 | cpp | 1089.cpp | #include<stdio.h>
int main()
{
int n;
scanf("%d", &n);
int wj[n];
int w1,w2;
for(int i=1;i<=n;i++)
{
scanf("%d", &wj[i]); //输入玩家说的话
}
//假设有两个狼人i,j
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
int pl=0, wl=0;
//遍历每个人说的话,判断其是否说谎
for(int k=1;k<=n;k++)
{
//如果玩家k说的话小于0,则wj[k]为狼人,如果这个狼人不是i也不是j,则说明是谎话;
//如果大于0,说明这个人是好人,如果wj[k]是 i或者j中的一个,说明是谎话
if((wj[k] < 0 && -wj[k] != i && -wj[k] !=j) || (wj[k] > 0 && (wj[k] == i || wj[k] == j)))
{
//k说谎了,如果k不是狼人,则好人说谎加1,否则狼人说谎+1
if(k != i && k != j) pl++;
else wl++;
}
}
if(pl == 1 && wl == 1)
{
w1 = i;
w2 = j;
break;
}
}
if(w1) break;
}
if(w1) printf("%d %d", w1, w2);
else printf("No Solution");
}
|
4090bd3e8919ebc373f28a7251b1f854ee13939c | 8817aaa66bcba8563a302830a312e1e5108c90df | /from_bill/ZEUS5_IP/tdev/tdevmount20091217.cpp | 270dde56b6f1d9627d47111bb0829f4070ae6e5c | [] | no_license | dennis-tmeinc/dvr | 908428496c16343afcc969bea2f808e9389febe8 | 7064cfc66445df45d0e747e7304e301a25c214f8 | refs/heads/master | 2021-01-12T17:19:44.988144 | 2018-03-27T22:19:53 | 2018-03-27T22:19:53 | 69,481,073 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,241 | cpp | tdevmount20091217.cpp | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <dirent.h>
class dir_find {
protected:
DIR * m_pdir ;
struct dirent * m_pent ;
struct dirent m_entry ;
char m_dirname[PATH_MAX] ;
char m_pathname[PATH_MAX] ;
struct stat m_statbuf ;
public:
dir_find() {
m_pdir=NULL ;
}
// close dir handle
void close() {
if( m_pdir ) {
closedir( m_pdir );
m_pdir=NULL ;
}
}
// open an dir for reading
void open( const char * path ) {
int l ;
close();
m_pent=NULL ;
strncpy( m_dirname, path, sizeof(m_dirname) );
l=strlen( m_dirname ) ;
if( l>0 ) {
if( m_dirname[l-1]!='/' ) {
m_dirname[l]='/' ;
m_dirname[l+1]='\0';
}
}
m_pdir = opendir(m_dirname);
}
dir_find( const char * path ) {
m_pdir=NULL;
open( path );
}
~dir_find() {
close();
}
int isopen(){
return m_pdir!=NULL ;
}
// find directory.
// return 1: success
// 0: end of file. (or error)
int find()
{
struct stat findstat ;
if( m_pdir ) {
while( readdir_r( m_pdir, &m_entry, &m_pent)==0 ) {
if( m_pent==NULL ) {
break;
}
if( (m_pent->d_name[0]=='.' && m_pent->d_name[1]=='\0') ||
(m_pent->d_name[0]=='.' && m_pent->d_name[1]=='.' && m_pent->d_name[2]=='\0') ) {
continue ;
}
if( m_pent->d_type == DT_UNKNOWN ) { // d_type not available
strcpy( m_pathname, m_dirname );
strcat( m_pathname, m_pent->d_name );
if( stat( m_pathname, &findstat )==0 ) {
if( S_ISDIR(findstat.st_mode) ) {
m_pent->d_type = DT_DIR ;
}
else if( S_ISREG(findstat.st_mode) ) {
m_pent->d_type = DT_REG ;
}
}
}
return 1 ;
}
}
m_pent=NULL ;
return 0 ;
}
char * pathname()
{
if(m_pent) {
strcpy( m_pathname, m_dirname );
strcat( m_pathname, m_pent->d_name );
return (m_pathname) ;
}
return NULL ;
}
char * filename()
{
if(m_pent) {
return (m_pent->d_name) ;
}
return NULL ;
}
// check if found a dir
int isdir()
{
if( m_pent ) {
return (m_pent->d_type == DT_DIR) ;
}
else {
return 0;
}
}
// check if found a regular file
int isfile()
{
if( m_pent ) {
return (m_pent->d_type == DT_REG) ;
}
else {
return 0;
}
}
// return file stat
struct stat * filestat()
{
char * path = pathname();
if( path ) {
if( stat( path, &m_statbuf )==0 ) {
return &m_statbuf ;
}
}
return NULL ;
}
};
char * mountcmd ;
void tdev_mount(char * path)
{
char * pathname ;
dir_find dfind(path);
pid_t childid ;
int devfound=0 ;
while( dfind.find() ) {
pathname = dfind.pathname();
if( dfind.isdir() ) {
tdev_mount( pathname ) ;
}
else if( dfind.isfile() ) {
if( strstr(path,"/sd")!=NULL && strcmp( dfind.filename(), "dev" )==0 ) {
devfound=1 ;
break;
}
}
}
if( devfound ) {
if( (childid=fork())==0 ) {
execl(mountcmd, mountcmd, "add", path+4, NULL ); // will not return
exit(1);
}
else {
waitpid(childid, NULL, 0);
}
}
}
int main(int argc, char *argv[])
{
if( argc>1 ) {
mountcmd = argv[1] ;
}
else {
mountcmd = "tdevmount" ;
}
tdev_mount("/sys/block");
return 0 ;
}
|
14535953ec2c343989e3b9d05ca710aa60172a60 | 0ea123f8f49346d2e43ce1e6e642e79781067792 | /ODE/include/inverseCtx.h | 45d8fb940f4bc537d12e520704315e88b7d3380f | [
"MIT"
] | permissive | paralab/Dendro-5.01 | 38615a9f900e478caf6e2e1db7c5f5442813dfe6 | 5dbcfa64a81364c47ef720e7c3793c6742cacdcf | refs/heads/master | 2023-08-05T10:49:43.693159 | 2023-07-11T16:07:45 | 2023-07-11T16:07:45 | 102,657,919 | 29 | 8 | MIT | 2023-06-19T19:44:48 | 2017-09-06T21:01:16 | C++ | UTF-8 | C++ | false | false | 2,399 | h | inverseCtx.h | /**
* @file sensitivityCtx.h
* @author Milinda Fernando
* @brief Ctx class to perform sensitivity analysis for time dependent problems.
* @version 0.1
* @date 2021-10-12
* @copyright Copyright (c) 2021
*/
#pragma once
#include "dendro.h"
#include "mesh.h"
#include "launcher.h"
namespace invp
{
template<typename DerivedInverseCtx, typename Ctx>
class InverseCtx
{
protected:
/**@brief forward ctx*/
Ctx* m_uiForCtx = NULL;
/**@brief adjoint ctx*/
Ctx* m_uiAdjCtx = NULL;
/**@brief Global communicator*/
MPI_Comm m_uiCommGlobal;
/**@brief Local communicator*/
MPI_Comm m_uiCommLocal;
launcher::Launcher* m_uiJobLauncher=NULL;
public:
InverseCtx(){};
~InverseCtx(){};
/**@brief: derived class static cast*/
DerivedInverseCtx &asLeaf() { return static_cast<DerivedInverseCtx &>(*this); }
/**@brief get global communicator*/
MPI_Comm get_global_comm() const { return m_uiCommGlobal;}
/**@brief get local communicator*/
MPI_Comm get_local_comm() const { return m_uiCommLocal;}
/**@brief set the job launcher*/
int set_launcher(launcher::Launcher* launcher) {
m_uiJobLauncher = launcher;
m_uiCommGlobal = m_uiJobLauncher->get_global_communicator();
m_uiCommLocal = *(m_uiJobLauncher->get_sub_communicator());
return 0;
}
/**@brief create forward problem ctx*/
int initialize_forward_ctx() { return asLeaf().initialize_forward_ctx(); }
/**@brief create adjoint problem ctx*/
int initialize_adjoint_ctx() { return asLeaf().initialize_adjoint_ctx(); }
/**@brief launch the forward problem */
int launch_forward_solve() { return asLeaf().launch_forward_solve();}
/**@brief launch the adjoint problem */
int launch_adjoint_solve() {return asLeaf().launch_adjoint_solve();}
/**@brief launch gradient approximation */
int gradient_approximation() {return asLeaf().gradient_approximation();}
};
}// end of namespece sa. |
a2b9ae88f6833a3dd3ad640e260773aa4a426b6b | 0c268ff10b68c4a24023ca646bb46c5a125eb84c | /Codeforces_ProblemSet/939b.cpp | 85962411acdc3119c97541d631f81b2585ba4ef8 | [] | no_license | TzeHimSung/AcmDailyTraining | 497b9fb77c282f2f240634050e38f395cf1bedbc | 2a69fa38118e43cbeca44cb99369e6e094663ec8 | refs/heads/master | 2023-03-21T21:39:02.752317 | 2021-03-14T03:41:00 | 2021-03-14T03:41:00 | 159,670,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | 939b.cpp | //basic
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <climits>
#include <cmath>
#include <cstdint>
//STL
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <array>
#include <iterator>
//define
#define int int32_t
#define ll int64_t
#define dou double
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define init(a,b) fill(begin(a),end(a),b)
#define sot(a,b) sort(a+1,a+1+b)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define rep0(i,a,b) for(int i=a;i<b;i++)
#define repa(i,a) for(auto &i:a)
#define eps 1e-8
#define inf 0x3f3f3f3f
//namespace
using namespace std;
//header end
ll n,k,x,remain=1e18+10,buy=0;
int num=1;
const int maxn=1e5+10;
int main()
{
scanf("%lld%lld",&n,&k);
rep1(i,1,k)
{
scanf("%lld",&x);
if (x>n) continue;
ll tmp=n%x;
if (tmp<remain)
{
num=i;
remain=tmp;
buy=n/x;
}
}
printf("%d %lld\n",num,buy);
return 0;
} |
d43afeb7f985204dd030ce95ae27635241c63904 | 3b141c379debc63588586dbceb44442ccfba97eb | /12-model_loading/SceneLoaderFactory.cpp | 010e60891249622cc5462bfa22085f17b43371a6 | [] | no_license | FabrizioPerria/OpenGL | 27fbca335e5b4efe660a93306450f0af2e13896a | a5686f096189290051d80ace9fdaf0394f9785ba | refs/heads/master | 2020-12-24T18:32:04.622301 | 2016-05-24T14:35:36 | 2016-05-24T14:35:36 | 55,981,134 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | SceneLoaderFactory.cpp | #include "SceneLoaderFactory.h"
#include "RawSceneLoader.h"
#include "AssimpSceneLoader.h"
std::unique_ptr<ISceneLoader> SceneLoaderFactory::makeLoader(std::string type)
{
if(type == "raw")
return std::unique_ptr<RawSceneLoader>(new RawSceneLoader);
else if(type == "assimp")
return std::unique_ptr<AssimpSceneLoader>(new AssimpSceneLoader);
return std::unique_ptr<RawSceneLoader>(new RawSceneLoader);
} |
c46b18cc08735e6b991b5670f7fd1ab015e5dc18 | 7e157199610f52120735ead7caa397a7b068a711 | /OniDev/source/collision/rect.cpp | 337de51706bada26eaf9fab6be0210e7bd62fe61 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | onidev/onidev | 2f63445feae6b8f7985f3a2d47a4a249a420cab3 | c9ade0c27bf6fe179eb85cbffc34b3981009d5f6 | refs/heads/master | 2021-01-21T13:34:12.365850 | 2016-05-18T11:43:26 | 2016-05-18T11:43:26 | 55,431,294 | 2 | 1 | null | 2016-04-04T19:42:46 | 2016-04-04T17:33:18 | C++ | UTF-8 | C++ | false | false | 4,875 | cpp | rect.cpp | // OniDev - Copyright (c) 2013-2016 Boris Marmontel
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
/*=============================================================================
rect.cpp
=============================================================================*/
#include <onidev/collision/rect.h>
#include <cstdio>
#include <cmath>
#include <onidev/collision/convex_polygon.h>
#include <onidev/collision/polygon.h>
#include <onidev/collision/mask.h>
#include <onidev/collision/line.h>
#include <onidev/collision/disk.h>
//extern int number;
namespace od
{
Rect::Rect(): x1(0), y1(0), x2(0), y2(0) {}
Rect::Rect(const Rect & rect): x1(rect.x1), y1(rect.y1), x2(rect.x2), y2(rect.y2) {}
Rect::Rect(float x1, float y1, float x2, float y2): x1(x1), y1(y1), x2(x2), y2(y2) {}
// Duplication code Collision pour optimisation
bool Rect::intersect(float x, float y) const
{
return x > x1 && y > y1 && x <= x2 && y <= y2;
}
bool Rect::intersect(const Line & line, float dx, float dy) const
{
float line_x1 = line.x1 + dx, line_x2 = line.x2 + dx;
float line_y1 = line.y1 + dy, line_y2 = line.y2 + dy;
// Find min and max X for the segment
float minX = line_x1;
float maxX = line_x2;
if(line_x1 > line_x2)
{
minX = line_x2;
maxX = line_x1;
}
// Find the intersection of the segment's and rectangle's x-projections
if(maxX > x2)
{
maxX = x2;
}
if(minX < x1)
{
minX = x1;
}
// If their projections do not intersect return false
if(minX > maxX)
{
return false;
}
// Find corresponding min and max Y for min and max X we found before
float minY = line_y1;
float maxY = line_y2;
float Dx = line_x2 - line_x1;
if(std::abs(Dx) > 0.0000001)
{
float a = (line_y2 - line_y1) / Dx;
float b = line_y1 - a * line_x1;
minY = a * minX + b;
maxY = a * maxX + b;
}
if(minY > maxY)
{
float tmp = maxY;
maxY = minY;
minY = tmp;
}
// Find the intersection of the segment's and rectangle's y-projections
if(maxY > y2)
{
maxY = y2;
}
if(minY < y1)
{
minY = y1;
}
// If Y-projections do not intersect return false
if(minY > maxY)
{
return false;
}
return true;
}
// Duplication code Collision pour optimisation
bool Rect::intersect(const Rect & b, float dx, float dy) const
{
return (x2 > b.x1 + dx) && (x1 < b.x2 + dx)
&& (y2 > b.y1 + dy) && (y1 < b.y2 + dy);
}
bool Rect::intersect(const Disk & disk, float dx, float dy) const
{
return disk.intersect(*this, dx, dy);
}
bool Rect::intersect(const Mask & mask, float dx, float dy) const
{
return mask.intersect(*this, dx, dy);
}
bool Rect::intersect(const ConvexPolygon & poly, float dx, float dy) const
{
return poly.intersect(*this, -dx, -dy);
}
bool Rect::intersect(const Polygon & poly, float dx, float dy) const
{
return poly.intersect(*this, -dx, -dy);
}
bool Rect::collide(const Shape & s, float dx, float dy) const
{
//number++;
return s.intersect(*this, -dx, -dy);
}
const Rect Rect::boundingBox() const
{
return *this;
}
float Rect::width() const
{
return x2 - x1;
}
float Rect::height() const
{
return y2 - y1;
}
Pos Rect::center() const
{
return Pos((x1+x2)/2.f, (y1+y2)/2.f);
}
const Rect Rect::translate(float x, float y) const
{
return Rect(x1-x, y1-y, x2-x, y2-y);
}
void Rect::translate(float x, float y)
{
x1 -= x; x2 -= x;
y1 -= y; y2 -= y;
}
void Rect::scale(float x, float y)
{
x1 *= x; x2 *= x;
y1 *= y; y2 *= y;
}
Rect & Rect::operator=(const Rect & rect)
{
x1 = rect.x1;
y1 = rect.y1;
x2 = rect.x2;
y2 = rect.y2;
return *this;
}
} // namespace od
|
e7955564426ee9fab19592c1783251956f422443 | 62066f9781e0ac72ad0a12fa03d0ed2ac4bc1e58 | /CircularList.h | de8f018c3cf9674b713805ad64189e6049e323fe | [] | no_license | cs2100-utec-aed-2019ii/cs2100-listas-tekken_force | 76a40968c7c0c8ef441eb8b6f8a98cb006d18d0c | 9ffc900bddf3433beca0905ea4e88cd6473baffe | refs/heads/master | 2020-07-13T07:20:47.127661 | 2019-10-28T22:16:38 | 2019-10-28T22:16:38 | 205,030,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,504 | h | CircularList.h | #ifndef JERARQUIA_LISTAS_CIRCULARLIST_H
#define JERARQUIA_LISTAS_CIRCULARLIST_H
#include "List.h"
#include <time.h>
#include "ForwardNode.h"
#include <ctime>
template <class T>
class CircularList : public List<T>{
protected:
ForwardNode<T> *head;
public:
CircularList(List<T>&);
CircularList(T*, int);
CircularList(ForwardNode<T> *);
CircularList(int);
CircularList();
~CircularList();
T& Front() override;
T& Back() override;
void push_back(const T& a) override;
void push_front(const T& a) override;
Node<T>* pop_back() override;
Node<T>* pop_front() override;
bool empty() override;
unsigned int size() override;
void clear() override;
void erase(Node<T>*) override;
void insert(Node<T>*,T) override;
void drop(T) override;//elimina los nodos que en la lista tengan los valores iguales al del parametro
List<T>& sort() override;
List<T>& reverse() override;
T& operator[](int) override;
template<typename __T>
friend std::ostream& operator<< (std::ostream& os , const CircularList<__T>& C){
ForwardNode<T> **pp = &C.head;
while ( (*pp)->Next = C.head ){
os << (**p)->get_value() << "-> " ;
pp = &(*pp)->Next;
}
os <<(*pp)->get_value() << "->";
return os;
}
template<typename __T>
friend List& operator<< (List<__T>&, const T& ) ;
template<typename __T>
friend List& operator>> (List<__T>&, const T& );
};
template<class T>
CircularList<T>::CircularList() : List<T>(){
CircularList<T>::head = nullptr;
}
template<class T>
CircularList<T>::CircularList(List<T>& copy) : List<T>(copy){
CircularList<T>::head = copy.head;
}
template<class T>
CircularList<T>::CircularList(int n) : List<T>(n){
srand(time(NULL));
for (int i=0;i<n;i++){
CircularList::push_back( rand() % 10 +1 );
}
}
template<class T>
CircularList<T>::CircularList(T* arr, int size) : List<T>(arr,size){
}
template<class T>
CircularList<T>::CircularList(ForwardNode<T>* node) : List<T>(node){
CircularList<T>::head = node;
node.next = head;
}
template<class T>
T& CircularList<T>::Front() {
return head->Value;
}
template<class T>
T& CircularList<T>::Back() {
ForwardNode<T> **pp = &(head);
while((*pp)->next != head) {
pp = &(*pp)->next;
}
return (*pp)->Value ;
}
template<class T>
void CircularList<T>::push_back(const T& a){
ForwardNode<T> **pp = &head;
ForwardNode<T> *node = new ForwardNode<T>(a);
if ( !*pp ) {
*pp = node;
node->next = *pp ;
return ;
}
while((*pp)->next != head ) {
pp=&(*pp)->next;
}
node->next = head;
(*pp)->next = node;
/*
//Aqui falla en (*tracer) , si la lista esta vacia
ForwardNode<T>**tracer = &head;
ForwardNode<T> *node = new ForwardNode<T>(a);
std::cout<<"1"<<std::endl ;
while ( (*tracer) && (*tracer)->next != head){
tracer = &(*tracer)->next;
}
node->next = head;
(*tracer)->next= node;
*/
}
template<class T>
void CircularList<T>::push_front(const T& a){
ForwardNode<T> **pp = &head;
ForwardNode<T> *node = new ForwardNode<T>(a);
if ( !*pp ) {
*pp = node;
node->next = *pp ;
return ;
}
while((*pp)->next != head ) {
pp=&(*pp)->next;
}
(*pp)->next =node;
node->next = head;
head = node;
}
template<class T>
Node<T>* CircularList<T>::pop_back(){
ForwardNode<T> **pp = &head;
while((*pp)->next != head ) {
pp=&(*pp)->next;
}
ForwardNode<T> * node = (*pp);
(*pp) = head;
return node;
}
template<class T>
Node<T>* CircularList<T>::pop_front(){
ForwardNode<T> **pp = &head;
while((*pp)->next != head ) {
pp=&(*pp)->next;
ForwardNode<T> * node = head;
head = head->next;
(*pp)->next = head;
return node;
}
}
template<class T>
bool CircularList<T>::empty(){
return (head == nullptr) ;
}
template<class T>
unsigned int CircularList<T>::size(){
if (head ==nullptr) return 0;
ForwardNode<T> ** pp = &head;
int cant = 1;
while ((*pp)->next !=head){
pp = &(*pp)->next;
cant++;
}
return cant;
}
template<class T>
void CircularList<T>::clear() {}
template<class T>
void CircularList<T>::erase(Node<T>*){}
template<class T>
void CircularList<T>::insert(Node<T>*,T){}
template<class T>
void CircularList<T>::drop(T) {}
template<class T>
List<T>& CircularList<T>::sort(){}
template<class T>
List<T>& CircularList<T>::reverse(){}
template<class T>
T& CircularList<T>::operator[](int index){
ForwardNode<T> **pp = &head;
while(index ) {
pp=&(*pp)->next;
index--;
}
return (*pp)->Value;
}
#endif
|
91d4c063c60fce701db603b8ddb7f8c340e2f591 | 0e0a39875ad5089ca1d49d1e1c68d6ef337941ff | /inc/Graphics/GeometryBuffer.h | 95a8b585f1d73ed7093ccf25e195ccfa0542d526 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | FloodProject/flood | aeb30ba9eb969ec2470bd34be8260423cd83ab9f | 466ad3f4d8758989b883f089f67fbc24dcb29abd | refs/heads/master | 2020-05-18T01:56:45.619407 | 2016-02-14T17:00:53 | 2016-02-14T17:18:40 | 4,555,061 | 6 | 2 | null | 2014-06-21T18:08:53 | 2012-06-05T02:49:39 | C# | WINDOWS-1252 | C++ | false | false | 3,327 | h | GeometryBuffer.h | /************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
#include "Core/References.h"
#include "Core/Math/Vector.h"
#include "Graphics/Buffer.h"
#include "Graphics/VertexBuffer.h"
NAMESPACE_GRAPHICS_BEGIN
//-----------------------------------//
/**
* Represents a buffer with geometry data. You have to associate the vertex
* data layout to the buffer so it can be used by the engine.
*/
class API_GRAPHICS GeometryBuffer : public ReferenceCounted
{
public:
GeometryBuffer();
GeometryBuffer(BufferUsage, BufferAccess);
~GeometryBuffer();
// Gets/sets the buffer usage type.
ACCESSOR(BufferUsage, BufferUsage, usage)
// Gets/sets the buffer access type.
ACCESSOR(BufferAccess, BufferAccess, access)
// Forces rebuild of geometry data.
void forceRebuild();
// Clears the buffer.
void clear();
// Sets the attribute data in the buffer.
void set(VertexAttribute, uint8* data, uint32 size);
// Sets the data in the buffer.
void set(uint8* data, uint32 size);
// Adds data to the buffer.
void add(uint8* data, uint32 size);
// Sets the index data in the index buffer.
void setIndex(uint8* data, uint32 size);
// Adds index data to the index buffer.
void addIndex(uint8* data, uint32 size);
// Adds an index to the index buffer.
void addIndex(uint16 index);
// Returns if the buffer has indexed data.
bool isIndexed() const;
// Gets a pointer to the attribute data.
float* getAttribute(VertexAttribute, uint32 i) const;
// Gets the stride of the vertex attribute.
int8 getAttributeStride(VertexAttribute) const;
// Gets the number of vertices in the buffer.
uint32 getNumVertices() const;
// Gets the number of indices in the buffer.
uint32 getNumIndices() const;
// Clears index data buffer.
void clearIndexes();
template<typename T>
FLD_IGNORE void set(VertexAttribute attr, const Vector<T>& data)
{
if( data.Empty() ) return;
uint32 sizeInBytes = data.Size() * sizeof(T);
if( !declarations.find(attr) )
{
VertexElement decl(attr, VertexDataType::Float, sizeof(T) / sizeof(float));
decl.stride = 0;
decl.offset = this->data.Size();
decl.size = sizeInBytes;
declarations.add(decl);
add((uint8*)data.Buffer(), sizeInBytes);
}
else
{
set(attr, (uint8*)data.Buffer(), sizeInBytes);
}
}
// Buffer usage.
BufferUsage usage;
// Buffer access.
BufferAccess access;
// Holds the vertex data.
Vector<uint8> data;
// Holds the index data.
Vector<uint8> indexData;
// Holds the index size in bits.
uint8 indexSize;
// Holds if the buffer needs to be rebuilt.
bool needsRebuild;
// Hash of the contents of the buffer.
uint32 hash;
// Holds the vertex declarations.
VertexDeclaration declarations;
};
TYPEDEF_INTRUSIVE_POINTER_FROM_TYPE( GeometryBuffer );
//-----------------------------------//
NAMESPACE_GRAPHICS_END |
e47228777a71754c1dd64b15f01bdbae3d624390 | 9718c436ab7664cfa1fa810fc798572a12177158 | /4draymarcher/FunTimes/utils.cpp | 4cf40abe96bee252a8d9ae381e033d801c26b6bc | [] | no_license | veesusmikelheir/Experiments | 319b219e8a47480f6b92807b6de3105634897852 | 83900443501eab23d106fc775534624fed5fd1aa | refs/heads/master | 2020-08-27T06:37:14.744503 | 2019-10-24T10:35:40 | 2019-10-24T10:35:40 | 217,272,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | utils.cpp | #include "GLFW/glfw3.h"
#include <stdlib.h>
// Necessary clean up to avoid leakage
void properExit(int code) {
glfwTerminate();
exit(code);
}
void conditionalExit(int code) {
if (code) {
properExit(code);
}
} |
0bb7731a02b822fcf7af20ac341b6a09a2ce9779 | b2756d5bc65ac143fe2d8a0c7e9bcae02827854b | /Source/SmartCity/GeoMap.h | 153987a4e2bb549f7a8a69e7bc7fe8282e56aa6b | [] | no_license | denfrost/UE4-SmartCity | f4be3d6dd6e5c23638cfc1e1c4a64b89245a1a1d | 1b65be2289669e9549c132224e1042e25cb2b0f9 | refs/heads/master | 2022-10-04T22:54:10.808821 | 2020-06-08T11:43:41 | 2020-06-08T11:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | GeoMap.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
/**
*
*/
class SMARTCITY_API GeoMap
{
public:
GeoMap();
~GeoMap();
};
|
09e70efc206e48d0042bab4073c63315c581935c | 7850cecd7a1476ca48f082faa5acd30c08eef1b1 | /mcu/src/bfcp/messages/BFCPMsgFloorRequest.cpp | b5f82be7af2d21cfc125753ebdbe7491acf1feaa | [] | no_license | InteractiviteVideoEtSystemes/mediaserver | abc68705cf0a4e228deff2107fd8ebc6990cd5f6 | b6c965d9a8d62957d8636b3f5fc65391460cd55e | refs/heads/master | 2023-07-06T01:53:45.862522 | 2023-03-28T06:41:05 | 2023-03-28T06:41:05 | 48,166,471 | 5 | 3 | null | 2022-06-10T13:00:55 | 2015-12-17T09:56:12 | C++ | UTF-8 | C++ | false | false | 5,639 | cpp | BFCPMsgFloorRequest.cpp | #include "bfcp/messages/BFCPMsgFloorRequest.h"
#include "log.h"
/* Instance members. */
BFCPMsgFloorRequest::BFCPMsgFloorRequest(int transactionId, int conferenceId, int userId) :
BFCPMessage(BFCPMessage::FloorRequest, transactionId, conferenceId, userId),
beneficiaryId(NULL),
participantProvidedInfo(NULL)
{
}
BFCPMsgFloorRequest::~BFCPMsgFloorRequest()
{
::Debug("BFCPMsgFloorRequest::~BFCPMsgFloorRequest() | free memory\n");
int num_floors = this->floorIds.size();
for (int i=0; i < num_floors; i++)
delete this->floorIds[i];
if (this->beneficiaryId)
delete this->beneficiaryId;
if (this->participantProvidedInfo)
delete this->participantProvidedInfo;
}
bool BFCPMsgFloorRequest::ParseAttributes(JSONParser &parser)
{
do {
// Get key name.
if (! parser.ParseJSONString()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse JSON key\n");
goto error;
}
enum BFCPAttribute::Name attribute = BFCPAttribute::mapJsonStr2Name[parser.GetValue()];
//::Log("BFCPMsgFloorRequest::ParseAttributes() | BFCPAttribute::Name attribute: %d\n", attribute);
if (! parser.ParseDoubleDot()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse ':'\n");
goto error;
}
switch(attribute) {
case BFCPAttribute::FloorId:
if (! parser.ParseJSONArrayStart()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'floorId' array start\n");
goto error;
}
if (parser.ParseJSONArrayEnd())
break;
do {
if (! parser.ParseJSONNumber()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'floorId' value in the array\n");
goto error;
}
int floorId = (int)parser.GetNumberValue();
::Debug("BFCPMsgFloorRequest::ParseAttributes() | attribute 'floorId' found\n");
AddFloorId(floorId);
} while (parser.ParseComma());
if (! parser.ParseJSONArrayEnd()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'floorId' array end\n");
goto error;
}
break;
case BFCPAttribute::BeneficiaryId:
if (! parser.ParseJSONNumber()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'beneficiaryId'\n");
goto error;
}
::Debug("BFCPMsgFloorRequest::ParseAttributes() | attribute 'beneficiaryId' found\n");
SetBeneficiaryId((int)parser.GetNumberValue());
break;
case BFCPAttribute::ParticipantProvidedInfo:
if (! parser.ParseJSONString()) {
::Error("BFCPMsgFloorRequest::ParseAttributes() | failed to parse 'participantProvidedInfo'\n");
goto error;
}
::Debug("BFCPMsgFloorRequest::ParseAttributes() | attribute 'participantProvidedInfo' found\n");
SetParticipantProvidedInfo(parser.GetValue());
break;
default:
::Debug("BFCPMsgFloorRequest::ParseAttributes() | skiping unknown key\n");
parser.SkipJSONValue();
break;
}
} while (parser.ParseComma());
::Debug("BFCPMsgFloorRequest::ParseAttributes() | exiting attributes object\n");
return true;
error:
return false;
}
bool BFCPMsgFloorRequest::IsValid()
{
// Must have at least one FloorId attribute.
if (this->CountFloorIds() < 1) {
::Error("BFCPMsgFloorRequest::IsValid() | MUST have at least one FloorId attribute\n");
return false;
}
return true;
}
void BFCPMsgFloorRequest::Dump()
{
::Debug("[BFCPMsgFloorRequest]\n");
::Debug("- [primitive: FloorRequest, conferenceId: %d, userId: %d, transactionId: %d]\n", this->conferenceId, this->userId, this->transactionId);
int num_floors = this->floorIds.size();
for (int i=0; i < num_floors; i++) {
::Debug("- floodId: %d\n", GetFloorId(i));
}
if (this->HasBeneficiaryId()) {
::Debug("- beneficiaryId: %d\n", GetBeneficiaryId());
}
::Debug("[/BFCPMsgFloorRequest]\n");
}
void BFCPMsgFloorRequest::AddFloorId(int floorId)
{
this->floorIds.push_back(new BFCPAttrFloorId(floorId));
}
void BFCPMsgFloorRequest::SetBeneficiaryId(int beneficiaryId)
{
// If already set, replace it.
if (this->beneficiaryId) {
::Debug("BFCPMsgFloorRequest::SetBeneficiaryId() | attribute 'beneficiaryId' was already set, replacing it\n");
delete this->beneficiaryId;
}
this->beneficiaryId = new BFCPAttrBeneficiaryId(beneficiaryId);
}
void BFCPMsgFloorRequest::SetParticipantProvidedInfo(std::wstring participantProvidedInfo)
{
// If already set, replace it.
if (this->participantProvidedInfo) {
::Debug("BFCPMsgFloorRequest::SetParticipantProvidedInfo() | attribute 'participantProvidedInfo' was already set, replacing it\n");
delete this->participantProvidedInfo;
}
this->participantProvidedInfo = new BFCPAttrParticipantProvidedInfo(participantProvidedInfo);
}
bool BFCPMsgFloorRequest::HasBeneficiaryId()
{
return (this->beneficiaryId ? true : false);
}
bool BFCPMsgFloorRequest::HasParticipantProvidedInfo()
{
return (this->participantProvidedInfo ? true : false);
}
int BFCPMsgFloorRequest::GetFloorId(unsigned int index)
{
if (index >= this->floorIds.size())
throw BFCPMessage::AttributeNotFound("'floorId' attribute not in range");
return this->floorIds[index]->GetValue();
}
int BFCPMsgFloorRequest::CountFloorIds()
{
return this->floorIds.size();
}
int BFCPMsgFloorRequest::GetBeneficiaryId()
{
if (! this->beneficiaryId)
throw BFCPMessage::AttributeNotFound("'beneficiaryId' attribute not found");
return this->beneficiaryId->GetValue();
}
std::wstring BFCPMsgFloorRequest::GetParticipantProvidedInfo()
{
if (! this->participantProvidedInfo)
throw BFCPMessage::AttributeNotFound("'participantProvidedInfo' attribute not found");
return this->participantProvidedInfo->GetValue();
}
|
e46b2fb071a97ee61860980ff0e01679dcf70332 | 7a78522a78f7082f9517e0aa6af75db3f9de2357 | /Engine/source/EtPipeline/Content/ContentBuildConfiguration.h | 6a02d1b5f69453583a6007ea731ebb8013cbe057 | [
"MIT"
] | permissive | avpdiver/ETEngine | 86a511d5d1ca8f03d47579d0ce0b367180e9b55e | 8a51e77a59cdeef216d4b6c41e4b882677db9596 | refs/heads/master | 2023-03-21T21:57:22.190835 | 2022-07-14T01:09:49 | 2022-07-14T01:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | h | ContentBuildConfiguration.h | #pragma once
namespace et {
namespace pl {
//------------------------------
// BuilConfiguration
//
// Provides info for how to build assets for runtime
//
struct BuildConfiguration
{
// definitions
//-------------
enum class E_Configuration : uint8
{
Invalid,
Debug,
Develop,
Shipping
};
enum class E_Architecture : uint8
{
Invalid,
x32,
x64
};
enum class E_Platform : uint8
{
Invalid,
Windows,
Linux
};
enum class E_GraphicsBackend : uint8
{
OpenGL
};
// construct destruct
//--------------------
BuildConfiguration();
BuildConfiguration(E_Configuration const config, E_Architecture const arch, E_Platform const platform);
// Data
///////
E_Configuration m_Configuration = E_Configuration::Invalid;
E_Architecture m_Architecture = E_Architecture::Invalid;
E_Platform m_Platform = E_Platform::Invalid;
E_GraphicsBackend m_GraphicsBackend = E_GraphicsBackend::OpenGL;
};
} // namespace pl
} // namespace et
|
930c340b09e1483175559a8fbbd5ebf1ed91fe23 | 6a96925bc81615eb528ccd5322be99757a223a53 | /log.hpp | 9dd1288d98ecf363ec2e33c7dc4ea8cd777fd7d5 | [] | no_license | markdellostritto/qatom | 4d849f0b82bf190d59a4f6260d21b84cac456e96 | 64c9ed30d25d2184cd43ce44128ba37f63b61d1d | refs/heads/master | 2022-01-26T17:31:16.410209 | 2019-07-30T14:42:52 | 2019-07-30T14:42:52 | 156,614,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,641 | hpp | log.hpp | #ifndef LOG_H
#define LOG_H
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <fstream>
#include <memory>
namespace logging{
inline void nullDeleter(void* p){}
//**********************************************************************************
//Sink class
//**********************************************************************************
class Sink{
private:
typedef std::shared_ptr<std::ostream> streamP;
streamP stream_;
public:
//constructors/destructors
Sink(){stream_=streamP(&std::cout,nullDeleter);}
Sink(std::ostream* stream){stream_=(stream==&std::cout)?streamP(stream,nullDeleter):streamP(stream);}
Sink(const Sink& sink):stream_(sink.stream()){};
virtual ~Sink(){};
//get/set functions
const streamP& stream() const{return stream_;};
//operators
const Sink& operator=(const Sink& sink){stream_=sink.stream();}
};
//**********************************************************************************
//Log class
//**********************************************************************************
class Log{
public:
static Log& get(){
static Log log;
return log;
}
//member functions
void addSink(const Sink& sink){sinks.push_back(sink);};
int numSinks() const{return sinks.size();};
const Sink& sink(int i) const{return sinks.at(i);};
template <class T> const Log& operator<<(const T& object) const;
private:
//constructors/destructors
Log(){};
~Log(){};
//make sure we disable the copy constructor and assignment operator
Log(const Log& log);
void operator=(const Log& log);
//member variables
std::vector<Sink> sinks;
};
template <class T>
const Log& Log::operator<<(const T& object) const{
for(int i=0; i<sinks.size(); i++){
*(sinks[i].stream())<<object;
}
return *this;
}
//**********************************************************************************
//LoggerBase class
//**********************************************************************************
class LoggerBase{
protected:
Log& log_;
public:
//constructors/destructors
LoggerBase():log_(Log::get()){};
LoggerBase(const LoggerBase& l):log_(Log::get()){};
virtual ~LoggerBase(){};
//operators
friend std::ostream& operator<<(std::ostream& stream, const LoggerBase& logger){return logger.print(stream);}
template <class T> const Log& operator<<(const T& object) const;
const LoggerBase& operator=(const LoggerBase& t){};
//member functions
Log& log(){return log_;};
const Log& log()const{return log_;};
void flush();
virtual std::ostream& print(std::ostream& stream) const=0;
};
template <class T>
const Log& LoggerBase::operator<<(const T& object) const{
for(int i=0; i<log_.numSinks(); i++){
*(log_.sink(i).stream())<<*this<<object;
}
return log_;
}
class DebugLogger: public LoggerBase{
protected:
std::string name_;
public:
//constructors/destructors
DebugLogger():name_("DEBUG"){};
DebugLogger(std::string name):name_(name){};
DebugLogger(const char* name):name_(std::string(name)){};
DebugLogger(const DebugLogger& l):name_(l.name()){};
//get/set functions
const std::string& name() const{return name_;};
//operators
const DebugLogger& operator=(const DebugLogger& l){name_=l.name();};
//member functions
std::ostream& print(std::ostream& stream) const{return stream<<name_<<": ";};
};
}
/*namespace record{
//**********************************************************************************
//Stream class
//**********************************************************************************
class Stream{
private:
typedef std::shared_ptr<std::ostream> StreamP;
StreamP stream_;
std::string name_;
public:
//constructors/destructors
Stream();
Stream(std::ostream* stream);
Stream(const Stream& stream);
~Stream(){};
//access
StreamP& stream(){return stream_;};
const StreamP& stream()const{return stream_;};
std::string& name(){return name_;};
const std::string& name()const{return name_;};
//operators
Stream& operator=(const Stream& stream);
};
//**********************************************************************************
//Log class
//**********************************************************************************
class Log{
private:
//constructors/destructors
Log(){};
~Log(){};
//make sure we disable the copy constructor and assignment operator
Log(const Log& log);
void operator=(const Log& log);
//member variables
std::vector<Stream> streams_;
public:
//static functions
static Log& get(){static Log log; return log;}
//operators
template <class T> const Log& operator<<(const T& object) const;
//access
unsigned int nStreams()const{return streams_.size();};
const Stream& stream(unsigned int i)const{return streams_.at(i);};
//member functions
void add(const Stream& stream){streams_.push_back(stream);};
void flush();
template <class T> const Log& append(const T& object);
};
template <class T>
const Log& Log::operator<<(const T& object) const{
for(unsigned int i=0; i<streams_.size(); i++)
*streams_[i].stream()<<"["<<streams_[i].name()<<"] "<<object;
return *this;
}
template <class T>
const Log& Log::append(const T& object){
for(unsigned int i=0; i<streams_.size(); i++)
*streams_[i].stream()<<object;
return *this;
}
}*/
#endif
|
344d09a8f0abbee6c00f77e6f4260131cb0074e4 | 33812fd99580266e0dc63ac8ac6518c9f27ef21c | /Day001/EXAM_13/exam_13.cpp | 1f6d0e82509d5538f8c37f14e5833c2018a042bb | [] | no_license | JMK92/C_pp_Programming | eb23f0de1d4849260454ae9bd376249482038a6c | ad9b8753fc3d57412be1d2aa2c4124d824d6de55 | refs/heads/master | 2023-05-30T15:17:27.444925 | 2021-06-20T14:12:55 | 2021-06-20T14:12:55 | 372,444,137 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 644 | cpp | exam_13.cpp | /*
레퍼런스(Reference) & NickName(별칭)
- 이름을 지닌 대상에 별명을 붙여주는 행위
- 변수 : 메모리 공간에 붙여진 이름, 기억공간(장소)
- 메모리 공간에 이름을 하나 더 추가하는 행위
- 형식
int& ref = val; -> int이름을 ref로
*/
#include<iostream>
using namespace std;
int main() {
int val = 10;
int* pVal = &val; // 포인터변수
int& rVal = val; // 레퍼런스 선언 , val의 또다른 이름
cout << "Val = " << val << endl;
cout << "rVal = " << rVal << endl;
cout << "Val 주소 = " << &val << endl;
cout << "Val 주소 = " << pVal << endl;
return 0;
} |
3ac0642e70757fe8776cea5d1225b1b76eb609a5 | 8e00949820b168b0ad1d6640b67ad810ed4daa67 | /calWheelSpeed/calWheelSpeed.ino | b0fd5683aa181a7166bc9d41fd8ce11064bbca28 | [] | no_license | EC544-F2015-Group5/Challenge_4 | 111656f75ff04a256e8f6555e3dd07b531182de7 | b03d8f368f86edfb812f1e5f161739d6a48ddf29 | refs/heads/master | 2021-01-10T17:09:46.568432 | 2015-10-29T15:57:43 | 2015-10-29T15:57:43 | 44,640,341 | 0 | 0 | null | 2015-10-28T16:19:52 | 2015-10-20T23:16:57 | Arduino | UTF-8 | C++ | false | false | 822 | ino | calWheelSpeed.ino | int pinReceptor = A1;
int sensorVal;
int BorW=0;
int counter = 0;
int caltime = 0;
double rotation = 0;
double Wheelspeed = 0;
void increase(){
counter++;
}
double getWheelspeed(double rota){
double Wspeed = 0.1*rota;
return Wspeed;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
sensorVal = analogRead(pinReceptor);
if(sensorVal>20)
{
BorW = 1;
}
else
{
BorW = 0;
//if(the engine is working){increase();}
}
//Serial.println(sensorVal);
Serial.println(BorW);
Serial.println(counter);
if(caltime = 10)
{
rotation = counter/12;
Wheelspeed = getWheelspeed(rotation);
caltime = 0;
counter = 0;
}
delay(100);
}
|
78db7eb711d7980b942f0d9df6ad2fa5a991912e | 5153b4b3826705491d90302b1212b7b277537ff5 | /DriveTrain.cpp | 9f6b408d03163941b8985ad7a35aa7f62b727541 | [] | no_license | SuchForbiddenColors/Code2014ForReal | e47efd7f15e1de9661f030de820f5e84f25f2f1a | 319f2eb78836075b64bd64a79f40dca2033ec5a6 | refs/heads/master | 2020-04-17T08:01:10.791929 | 2015-11-11T01:45:27 | 2015-11-11T01:45:27 | 28,749,185 | 0 | 0 | null | 2015-01-03T17:48:25 | 2015-01-03T16:55:27 | C++ | UTF-8 | C++ | false | false | 5,159 | cpp | DriveTrain.cpp | #include "DriveTrain.h"
#include "Defines.h"
#include "Math.h"
DriveTrain::DriveTrain(int leftMotor, int rightMotor)
{
drive = new RobotDrive(leftMotor, rightMotor);
leftHandicapSubtraction = 0;
rightHandicapSubtraction = 0;
messageUse = 0;
handicapHasBeenPressed = false;
}
void DriveTrain::TankDrive(GenericHID * leftJoystick, GenericHID * rightJoystick)
{
float leftSpeed = leftJoystick->GetY() * LEFT_MOTOR_INVERT;
float rightSpeed = rightJoystick->GetY() * RIGHT_MOTOR_INVERT;
float leftHandicap;
float rightHandicap;
if(leftJoystick->GetRawButton(LR_BUTTON_TURBO) || rightJoystick->GetRawButton(LR_BUTTON_TURBO))
{
rightSpeed *= TURBO_SPEED;
leftSpeed *= TURBO_SPEED;
}
else
{
rightSpeed *= NORMAL_SPEED;
leftSpeed *= NORMAL_SPEED;
}
if(leftJoystick->GetRawButton(L_RIGHT_SUBTRACT))
{
if(handicapHasBeenPressed==false)
{
rightHandicapSubtraction += .05;
}
handicapHasBeenPressed = true;
}
else if(leftJoystick->GetRawButton(L_LEFT_SUBTRACT))
{
if(handicapHasBeenPressed==false)
{
leftHandicapSubtraction += .05;
}
handicapHasBeenPressed = true;
}
else
{
handicapHasBeenPressed = false;
}
if(leftJoystick->GetRawButton(L_SUBTRACT_RESET))
{
leftHandicapSubtraction = 0;
rightHandicapSubtraction = 0;
}
leftHandicap = 1 - leftHandicapSubtraction;
rightHandicap = 1 - rightHandicapSubtraction;
if(rightSpeed > .9) // Only works when going forward
{
rightSpeed *= rightHandicap;
}
if(leftSpeed > .9)
{
leftSpeed *= leftHandicap;
}
drive -> TankDrive(leftSpeed, rightSpeed);
}
void DriveTrain::XBoxDrive(GenericHID * XStick)
{
float forward = XStick->GetRawAxis(2); //2 is a controller's LeftY
float turn = XStick->GetRawAxis(4); //4 is a controller's RightX
float turbo = XStick->GetRawAxis(3); //3 seems to be either Trigger, but will only work if use Left Trigger, which
float leftHandicap; //controls the axis from 0-1
float rightHandicap;
if(turbo <= 0)
{
turbo = 0;
}
else
{
turbo = turbo / 2; //So output will range from 0 to .5, to add to minimum speed
}
if(fabs(forward) < .0125) //To buffer; XStick is sensitive
{
forward = 0;
}
if(fabs(turn) < .0125)
{
turn = 0;
}
if(turbo < .0125)
{
turbo = 0;
}
if(XStick->GetRawButton(X_RIGHT_BUMPER))
{
turn *= .5;
}
if(forward < 0)
{
turn *= -1; // Turns the same direction if going forward or backward
}
forward *= (.5 + turbo); //Modify speed with turbo, minimum of .5
if(XStick->GetRawButton(X_LEFT_CLICK) && XStick->GetRawButton(X_RIGHT_CLICK) && XStick->GetRawButton(X_RIGHT_BUMPER))
{
if(handicapHasBeenPressed==false)
{
rightHandicapSubtraction += .05;
}
handicapHasBeenPressed = true;
}
else if(XStick->GetRawButton(X_LEFT_CLICK) && XStick->GetRawButton(X_RIGHT_CLICK) && XStick->GetRawButton(X_LEFT_BUMPER))
{
if(handicapHasBeenPressed==false)
{
leftHandicapSubtraction += .05;
}
handicapHasBeenPressed = true;
}
else
{
handicapHasBeenPressed = false;
}
if(XStick->GetRawButton(X_BACK) && XStick->GetRawButton(X_START))
{
leftHandicapSubtraction = 0;
rightHandicapSubtraction = 0;
}
leftHandicap = 1 - leftHandicapSubtraction;
rightHandicap = 1 - rightHandicapSubtraction;
forward *= DRIVE_INVERT_FORWARD;
turn *= DRIVE_INVERT_TURN;
DissectedDrive(forward, turn, leftHandicap, rightHandicap);
}
void DriveTrain::Drive(float forward, float turn)
{
forward *= DRIVE_INVERT_FORWARD;
turn *= DRIVE_INVERT_TURN;
drive->Drive(forward, turn);
}
void DriveTrain::DissectedDrive(float speed, float curve, float leftHandicap, float rightHandicap)
{ //Speed and curve are the same as forward and turn, respectively
float leftSpeed, rightSpeed;
float m_sensitivity = .5;
if (curve < 0)
{
float value = log(-curve);
float ratio = (value - m_sensitivity)/(value + m_sensitivity);
if (ratio == 0) ratio =.0000000001;
leftSpeed = speed / ratio;
rightSpeed = speed;
}
else if (curve > 0)
{
float value = log(curve);
float ratio = (value - m_sensitivity)/(value + m_sensitivity);
if (ratio == 0) ratio =.0000000001;
leftSpeed = speed;
rightSpeed = speed / ratio;
}
else
{
leftSpeed = speed;
rightSpeed = speed;
}
if (speed > .9) // Only works when going forward
{
leftSpeed *= leftHandicap;
rightSpeed *= rightHandicap;
}
drive->SetLeftRightMotorOutputs(leftSpeed, rightSpeed);
}
float DriveTrain::Handicaps(bool right)
{
float value;
if(right == true)
{
value = rightHandicapSubtraction;
}
else if(right == false)
{
value = leftHandicapSubtraction;
}
return value;
}
void DriveTrain::Message(DriverStationLCD * dslcd)
{
if(messageUse != (2 - rightHandicapSubtraction - leftHandicapSubtraction) / 2 ) // Just so that if either variable
{ // changes we'll rerun the thing
float rightHandicap = 1 - rightHandicapSubtraction;
float leftHandicap = 1 - leftHandicapSubtraction;
dslcd->PrintfLine(dslcd->kUser_Line5,"R Turbo: %f",rightHandicap);
dslcd->PrintfLine(dslcd->kUser_Line6,"L Turbo: %f",leftHandicap);
messageUse = (2 - rightHandicapSubtraction - leftHandicapSubtraction) / 2;
dslcd->UpdateLCD();
}
}
|
8ff95a305d59bd84f0607900585036233d2873df | b687b9adc8e886a92b407b506041ded030dd0e97 | /tabulator/PageNumCtrl.cxx | c958008b209c0badbb761c4da65e6626e0b865d0 | [] | no_license | vir/pdf | 6dc2cd1c4f62aef208e54edc58e3ea30fa14c507 | 6b36a3d41e4c5962d7af0407f926423d07076412 | refs/heads/master | 2021-01-17T09:25:51.145910 | 2017-07-18T14:50:18 | 2017-07-18T14:50:18 | 37,723,254 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,378 | cxx | PageNumCtrl.cxx | #include "PageNumCtrl.hpp"
BEGIN_EVENT_TABLE(PageNumCtrl, wxTextCtrl)
EVT_CHAR (PageNumCtrl::OnChar)
EVT_SET_FOCUS (PageNumCtrl::OnSetFocus)
END_EVENT_TABLE()
PageNumCtrl::PageNumCtrl(wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, const wxString& name)
: wxTextCtrl(parent, id, value, pos, size, style, wxDefaultValidator, name), num(0), min(0), max(10000)
{
}
void PageNumCtrl::OnChar(wxKeyEvent & event)
{
wxString backup = wxTextCtrl::GetValue();
long tmp;
if(event.GetKeyCode() < 32 || event.GetKeyCode() == 127 || event.GetKeyCode() > 256)
event.Skip();
if(event.GetKeyCode() > 255 || !isdigit(event.GetKeyCode()))
return;
// EmulateKeyPress(event); // causes infinite recursion on win32
event.Skip();
wxString newval = wxTextCtrl::GetValue();
if(!newval.ToLong(&tmp) || tmp<min || tmp>max) {
wxTextCtrl::SetValue(backup);
wxBell();
}
else
num = tmp;
}
void PageNumCtrl::OnSetFocus(wxFocusEvent & event)
{
SelectAll();
event.Skip();
}
void PageNumCtrl::SetRange(int r1, int r2)
{
min = r1;
max = r2;
}
void PageNumCtrl::SetValue(int i)
{
num = i;
wxTextCtrl::SetValue(wxString::Format(_T("%d"), i));
}
int PageNumCtrl::GetValue()
{
long tmp;
wxString newval = wxTextCtrl::GetValue();
if(newval.ToLong(&tmp) || tmp<min || tmp>max) {
num = tmp;
}
return num;
}
|
394f47398966fdc9a3f4c8a000655abde35c863f | e59177d7d26f249bb3974e5877ea3bbc4354cf4a | /700+/720_Longest_Word_in_Dictionary.cpp | 191b448cbd6f4349523db8ab8f31ac00f86b9469 | [] | no_license | milanow/LeetCodePractice | 8ae2957f70f94dcfd22558d0b736cda587c5b308 | c99545d6b5a191bce6fd66c9941b06573a0af0c1 | refs/heads/master | 2021-09-12T12:42:21.958668 | 2018-04-16T18:42:39 | 2018-04-16T18:42:39 | 104,815,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | 720_Longest_Word_in_Dictionary.cpp | /* 720. Longest Word in Dictionary
* The key is to find out (1)if the substring(0, sz-1) of a word (in words)
* is also in words
*
* Sorting the words first and save previous qualified words (meets (1) in a set
* checking if current word's substring(0, sz-1) also inside the set
*/
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(), words.end());
unordered_set<string> built;
string res;
for (string w : words) {
if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) {
res = w.size() > res.size() ? w : res;
built.insert(w);
}
}
return res;
}
}; |
37f73239dd0c58307888ea406c19b3b93e7fc571 | 81d229a16cccac2cb9684b6a685e9be973a5e6e3 | /queue-rate/ConcurrencyFreaks/CPP/papers/poormansurcu/PerformanceBenchmarkURCU.h | e27e2a5a922af124c089d31f8afcf31026bfc688 | [] | no_license | charlesarcher/queue-rate | 83e2f183f4679eb3a1de7b088c3900efc31f8106 | 18dab4c3a0d45e99eb1e842568753c0c51f4e5a8 | refs/heads/master | 2021-01-12T00:19:47.931172 | 2017-01-12T05:08:39 | 2017-01-12T05:08:39 | 78,710,000 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,187 | h | PerformanceBenchmarkURCU.h | /*
* PerformanceTest.h
*
* Created on: Jul 24, 2013
* Author: pramalhe
*/
#ifndef _PERFORMANCE_BENCHMARK_URCU_H_
#define _PERFORMANCE_BENCHMARK_URCU_H_
#include <thread>
#include <iostream>
#include <atomic>
#include <forward_list>
#include <algorithm>
#include <vector>
#include <utility>
#include "TestCasesURCU.h"
#include "RCUBase.h"
#include "RCUBulletProof.h"
#include "RCUPoorMans.h"
#define MAX_RUNS 10
class UserData {
public:
int a;
int b;
//inline bool operator==(const UserData& l, const UserData& r){ return ((l.a == r.a) && (l.b == r.b)); }
};
struct RunEntry {
test_case_enum_t testCase;
int writePerMil;
int numThreads;
long opsPerSec;
};
std::vector<RunEntry> _runs;
// TODO: Change these to static members of the PerformanceBenchmark class
const int numElements = 100;
std::atomic<UserData*> udarray[numElements];
class PerformanceBenchmarkURCU {
public:
// These must be public so that the WorkerThread class instances can access them
RCU::RCUBulletProof _rcuBP;
RCU::RCUPoorMans _rcuPoorMans;
// TODO: MB
// Forward declaration
class WorkerThread;
WorkerThread **_workerThread = nullptr;
class WorkerThread {
public:
std::atomic<bool> quit {false};
std::atomic<long> aNumOps {0};
std::atomic<long> aNumReadOps {0};
std::atomic<long> aNumWriteOps {0};
long numOps;
long numReadOps;
long numWriteOps;
std::thread * const th = new std::thread(&WorkerThread::run, this);
PerformanceBenchmarkURCU * const pbl;
const test_case_enum_t testCase = TC_RCU_MAX;
const int tidx;
const unsigned int writePerMil = 0;
RCU::RCUBase *rcuBase = nullptr;
WorkerThread(PerformanceBenchmarkURCU * const pbl, const test_case_enum_t testCase, const int tidx, const int writePerMil)
: pbl(pbl),
testCase(testCase),
tidx(tidx),
writePerMil(writePerMil) {
quit.store(false);
switch(testCase) {
case TC_RCU_BULLET_PROOF:
rcuBase = &pbl->_rcuBP;
break;
case TC_RCU_POOR_MANS:
rcuBase = &pbl->_rcuPoorMans;
break;
case TC_RCU_MEMORY_BARRIER:
std::cout << "ERROR: Not implemented yet\n";
break;
default:
std::cout << "ERROR: Not implemented yet\n";
}
}
~WorkerThread() {
delete th;
}
void run() {
unsigned int x = 0;
uint64_t xrand = 12345678901234567LL;
aNumOps.store(0);
aNumReadOps.store(0);
aNumWriteOps.store(0);
numOps = 0;
numReadOps = 0;
numWriteOps = 0;
while (!quit.load()) {
xrand = randomLong(xrand);
x = (xrand < 0) ? (-xrand)%1000 : xrand%1000;
xrand = randomLong(xrand);
const int i1 = xrand % numElements;
//UserData& ud1 = udarray[i1];
if (writePerMil != 1000 && (writePerMil == 0 || x >= writePerMil)) {
// Read operation
const int cookie = rcuBase->read_lock();
UserData *ud = udarray[i1].load(std::memory_order_relaxed);
for (int i = 0; i < numElements; i++) {
UserData *udi = udarray[i1].load(std::memory_order_relaxed);
// Just some dereferences to cause crashes if there is a bug in
// one of the RCU implementations
if (ud->a == udi->a && ud->b == udi->b) break;
}
rcuBase->read_unlock(cookie);
numReadOps++;
numOps++;
} else {
// Write operations
UserData *ud_old = nullptr;
UserData *ud_new = new UserData;
ud_new->a = ud_new->b = i1;
while (true) {
// Make a new UserData instance and try to swap one of the current ones with it
ud_old = udarray[i1].load();
UserData *tmp = ud_old;
if (udarray[i1].compare_exchange_strong(tmp, ud_new)) break;
}
rcuBase->synchronize();
// Now it's ok to delete the memory of the older one
delete ud_old;
numWriteOps++;
numOps++;
}
}
aNumOps.store(numOps);
aNumReadOps.store(numReadOps);
aNumWriteOps.store(numWriteOps);
//std::cout << " numWriteOps=" << numWriteOps << "\n";
}
private:
/**
* An imprecise but fast random number generator
*/
uint64_t randomLong(uint64_t x) {
x ^= x >> 12; // a
x ^= x << 25; // b
x ^= x >> 27; // c
return x * 2685821657736338717LL;
}
};
public:
PerformanceBenchmarkURCU(int numThreads, int numMilis, int numRuns);
virtual ~PerformanceBenchmarkURCU();
void singleTest(test_case_enum_t testCase, int writePerMil);
void addRun(test_case_enum_t testCase, int writePerMil, int numThreads, long opsPerSec);
void saveDB(int writePerMil);
private:
const int _numThreads;
const int _numMilis;
const int _numRuns;
};
#endif /* _PERFORMANCE_BENCHMARK_TREES_H_ */
|
7ca6a593c24a4d059d07e881f9e6e7c0f8f13f9f | 328ef5181c5a2ffaa75ef4cfa8424b80f42395fb | /main.cpp | a3cb5a9fbcb43ea647798ddb2abae19a2c7d144e | [] | no_license | EzGDNull/CryptoppDemo-rsa-sign | 269e0d77e971d8cea629a731a9303d9324a4c0e8 | 1a27cac1cbb3601869bc2561a720c1831e40eefd | refs/heads/main | 2023-06-06T06:40:16.600414 | 2021-07-05T00:48:38 | 2021-07-05T00:48:38 | 381,750,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,489 | cpp | main.cpp | #include "mainwindow.h"
/*#include "cryptopp/include/md5.h"
#include "cryptopp/include/filters.h"
#include "cryptopp/include/hex.h"*/
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QByteArray privateKeydecBase64 = QByteArray::fromBase64(
QString("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvYMbiPk2DHUTu \
vN7qDpXbjtBjnuxMHK6le8J3vYSmqv1q4a++V1Qdeh9WkJ58IqIIkDM28b2eBXBz \
aSzbDSh8xmGjok+6+YVgyR5SK5arP3b8K5zclXczC2+C/UgoEzM4m24g1HN1wNXE \
NaYC9jrAO0ui2NICijLzN7jQszWcQ2yx97Ynudu4wa7pvV0W2JBNqo3GwO06oUM8 \
YZV/Q8iipwCxN3bqX9htbcDOzkQ3zz2MZgIlVTLWHaEU1Ts859PIwwji013RytD2 \
CQan56roVUs9YN9Q+6wlRJD+4rL9LVa8Xq4ssNwYQr9QrCknfZ/jExFbRn5Nmpas \
9i0DRxhHAgMBAAECggEAZ4N9oCgZ5BuwhiEgiZHWTeM7iLFS05HSW4Zyv+4yj5U5 \
Qo63BmfRFBzyxktR3/8pGFjUgcepnc2kE9quSRS5IvyMwOKaoMeKPBg5N1LW+Xja \
J/kt+tyVoKFNTklk/5JllzHWjLYY+BW7lrX7qJ/hCXl2KUZEno8nh3sKMNS1/ear \
YTPH7cbq1tCRu7JMqsDf3kjpdHaq4enpyIZMrSrwuR7hjWBfbxxnZx35asiRjv4F \
HnOn9R7KszQjQ2SINNWiT2zAUBguiyDFl+60ZNCeeX6Iei4ax9HNg/iF5jHPht9j \
bpbm2/Z0RHkXr1zmn4eBv9Z6dO9B/pwveuo5rl6s0QKBgQDiaSXN2uo9V1ddjwGm \
f6r2tRUh1kzjDOEVscZgHHHXSyZIozzrNM5j2/qOTSsnLvCBPXln6vW2olN10mUJ \
xmO5joQBEdG0FD7LAgdz7JeMnzPimo46WLfvGs1gxE3WaRct55bpomA/qb3Ovd9P \
G1RagOx2WKwki6yatzKzHU7aCwKBgQDGTERTh2N2UQhrdE4kY/h3TokdH0uOBRxK \
RjAsWWlnjaQlyy0rJ7RUQw53gFcR0DV/Z96EOXRppTD78Yby4wAaq6ja6fQNVWjd \
AlbCPUWWSJ7wvQotRqUlxELJk/DGcXEJaKOSELFQDZhotvvhO1xC6Z7/2M4caLDA \
1xWMqchcNQKBgAfj+jlOY9N3c8gC79/Jmz+11+KyAUP4cu+6nltDIoSKTe9CISFh \
WcAJLpY/Aj3/WMpoRg7lFWMkDRySFIteqqMQ4HDZGiHYgse4bmIP4Mg51CkVkdde \
uCpRGM9CiCPsza3/4DaMPiZ51++Ylmu/XBU7YQJO3ND5PS63K8EqSFE5AoGAKRoF \
z4pwg0WoiR1CVSijh5cvtGmYL4e/pWWG9qpRvrUNIQhMBHXmWtDLXtmrMnYFoLLW \
3HFMP9mNnasiXZXPn7eU+Esl2t2pLqYddYVdtxi2WQ/V3CyYbouPjFitv3QkCd82 \
iEANgJpQzOOgsb6sEPJ7kmxNzHWmrVHnlZBbh0ECgYBgcQydlp/HqJYp09BlvcQZ \
GjL6yv1/tx9J2p0QFYrpb5zSWas0Bx4cpHIve0M64QYXFjSzoH/88pc7mkzOfSK3 \
Slau227c+TQBkIsWgcbvydYbcTBy8i2pOoUkM+EJV8i/ja4t2aBNOV+l81I3/ZrY \
3t0osnDRfJ0INvlDx9dPfQ==").toLatin1());
QByteArray publicKeydecBase64 = QByteArray::fromBase64(
QString("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr2DG4j5Ngx1E7rze6g6V \
247QY57sTByupXvCd72Epqr9auGvvldUHXofVpCefCKiCJAzNvG9ngVwc2ks2w0o \
fMZho6JPuvmFYMkeUiuWqz92/Cuc3JV3Mwtvgv1IKBMzOJtuINRzdcDVxDWmAvY6 \
wDtLotjSAooy8ze40LM1nENssfe2J7nbuMGu6b1dFtiQTaqNxsDtOqFDPGGVf0PI \
oqcAsTd26l/YbW3Azs5EN889jGYCJVUy1h2hFNU7POfTyMMI4tNd0crQ9gkGp+eq \
6FVLPWDfUPusJUSQ/uKy/S1WvF6uLLDcGEK/UKwpJ32f4xMRW0Z+TZqWrPYtA0cY \
RwIDAQAB").toLatin1());
CryptoPP::AutoSeededRandomPool rng;
// Message
std::string message = "clever";
CryptoPP::ByteQueue Privatequeue;
CryptoPP::HexDecoder encoder(new CryptoPP::Redirector(Privatequeue));
// Signer object
CryptoPP::Weak::RSASSA_PKCS1v15_MD5_Signer signer;
std::string dek = QString(privateKeydecBase64.toHex()).toStdString();
//std::cout<<dek.size()<<" dek "<<dek<<std::endl;
encoder.Put((const unsigned char*)dek.data(), dek.size());
encoder.MessageEnd();
signer.AccessKey().Load(Privatequeue);
// Sign message
std::string signedMessage = "";
CryptoPP::StringSource s1(message, true, new CryptoPP::SignerFilter(rng, signer, new CryptoPP::HexEncoder(new CryptoPP::StringSink(signedMessage))));
// Verifier object
CryptoPP::ByteQueue Publicqueue;
CryptoPP::Weak::RSASSA_PKCS1v15_MD5_Verifier verifier;
CryptoPP::HexDecoder decoder(new CryptoPP::Redirector(Publicqueue));
std::string dec = QString(publicKeydecBase64.toHex()).toStdString();
//std::cout<<"dec"<<dec<<std::endl;
decoder.Put((const unsigned char*)dec.data(), dec.size());
decoder.MessageEnd();
verifier.AccessKey().Load(Publicqueue);
CryptoPP::StringSource signatureFile( signedMessage, true, new CryptoPP::HexDecoder);
if (signatureFile.MaxRetrievable() != verifier.SignatureLength())
{ throw std::string( "Signature Size Problem" ); }
CryptoPP::SecByteBlock signature1(verifier.SignatureLength());
signatureFile.Get(signature1, signature1.size());
// Verify
CryptoPP::SignatureVerificationFilter *verifierFilter = new CryptoPP::SignatureVerificationFilter(verifier);
verifierFilter->Put(signature1, verifier.SignatureLength());
CryptoPP::StringSource s(message, true, verifierFilter);
// Result
qDebug()<<"verifierFilter->GetLastResult()"<<verifierFilter->GetLastResult()<<endl;
// Result
if(true == verifierFilter->GetLastResult()) {
qDebug() << "Signature on message verified" << endl;
} else {
qDebug() << "Message verification failed" << endl;
}
MainWindow w;
w.show();
return a.exec();
}
|
76511a424db47f0671a9ece691062018a742ff8c | 49abb58c40577ce4470cca16034cf03ff0f94f7c | /C++/cisco/CPA/lab/cpa_lab_7_3_8/main.cpp | 1c5ca9d296d34221800e1193ebb85a8e81827f0b | [
"MIT"
] | permissive | stablestud/trainee | 196c3e64920adc8278bd2f06430b6e357091c2a7 | 72e18117e98ab4854e9271c2534e91cf39c42042 | refs/heads/master | 2022-08-11T11:52:26.099642 | 2022-07-30T22:45:56 | 2022-07-30T22:45:56 | 130,486,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,079 | cpp | main.cpp | #include <iostream>
#include <exception>
#include "ipAddress.h"
int main(void)
{
char ip[14];
int range;
try {
std::cin >> ip >> range;
ipAddressRange i0(ip, range);
i0.print();
} catch (std::exception& err) {
std::cout << err.what() << std::endl;
}
try {
std::cin >> ip >> range;
ipAddressRange i1(ip, range);
i1.print();
} catch (std::exception& err) {
std::cout << err.what() << std::endl;
}
try {
std::cin >> ip >> range;
ipAddressRange i2(ip, range);
i2.print();
} catch (std::exception& err) {
std::cout << err.what() << std::endl;
}
try {
std::cin >> ip >> range;
ipAddressRange i3(ip, range);
i3.print();
} catch (std::exception& err) {
std::cout << err.what() << std::endl;
}
return 0;
}
|
fa1df0da2cf2db5d178b1c00baee3d3b8e3f9819 | a12bd9ee16dd864756829f2ff98f9e7ca59e322a | /06. arduino/ch04/buzzer/ex04/app.ino | a2fb74b9321a2c12da4089b8f17e7e45d4eb4dbc | [] | no_license | hongjy127/TIL | 0bda9250f850a21dc27597a8b6288cf7ecb9e470 | a1760aba50bb3b77ab6576f5b5dcb16f0d9f5c5a | refs/heads/master | 2023-06-17T17:04:21.873930 | 2021-07-18T07:54:26 | 2021-07-18T07:54:26 | 325,415,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | ino | app.ino | #include <Melody.h>
#include "pitches.h"
#include "pirates.h"
int length = sizeof(notes) / sizeof(int);
Melody melody(2, notes, durations, length);
void setup() {
melody.play();
}
void loop() {
melody.run();
} |
0dd1bd3a2d8b89cca0e6225084456d552c3049af | 25f207ef23e55300ef8b9b2e94ae9de4ba2bd924 | /plugins/inp/sidplay/sidplay/fixpoint.h | 98fba21515ac114224ec2b80d5de471afd9140f4 | [
"LicenseRef-scancode-philippe-de-muyter"
] | permissive | zig/dcplaya | 7a6af0ea20a9426d915f1c08d864f18288fb4a9d | 3ecdfe75ffe5ca2beb73c85c2f7cb05dd79364f2 | refs/heads/master | 2021-01-13T02:26:18.205607 | 2009-08-05T01:11:05 | 2009-08-05T01:11:05 | 271,023 | 4 | 2 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 5,965 | h | fixpoint.h | /*******************************************************************************
*
* File header: PseudoFloat.h
*
* Description: Fixed point class
*
*
* Author: Vincent Penné
*
* Date: Sat 18th October 1997
*
*******************************************************************************/
/***************************************************************/
#ifndef SIDPLAY1_FIXPOINT_H
#define SIDPLAY1_FIXPOINT_H
class fixed {
public:
int v;
inline fixed() {}
inline fixed(const int a, int dummy) { v=a; dummy=dummy; } // basic constructor (ugly !)
inline fixed(const int a) { v=a<<16; }
inline fixed(const unsigned int a) { v=a<<16; }
inline fixed(const long a) { v=a<<16; }
inline fixed(const unsigned long a) { v=a<<16; }
inline fixed(double a) { v=int(a*(1<<16)); }
inline fixed(float a) { v=int(a*(1<<16)); }
// inline fixed make_fixed(int a) { fixed r; r.v=a; return r; }
// inline fixed(fixed &a) { v=a.v; }
inline operator float() { return float(v)/(1<<16); }
inline operator double() { return double(v)/(1<<16); }
// inline &operator fixed() { return make_fixed(a.v); }
// inline fixed(int &a) { v=a<<16; }
// inline fixed(float a) { v=int(a*(1<<16)); }
// inline fixed(double a) { v=int(a*(1<<16)); }
inline operator signed char() { return v>>16; }
inline operator unsigned char() { return v>>16; }
inline operator int() { return v>>16; }
inline operator unsigned int() { return v>>16; }
inline operator long() { return v>>16; }
inline operator unsigned long() { return v>>16; }
inline friend fixed operator - (const fixed &a) { return fixed(-a.v, 0); }
static inline fixed multiply(const fixed &a, const fixed &b) { return fixed((a.v>>8)*(b.v>>8),0); }
static inline fixed divide(const fixed &a, const fixed &b) { return fixed((a.v<<8)/(b.v>>8),0); }
inline fixed operator *(const fixed &b) { return fixed((v>>8)*(b.v>>8),0); }
inline fixed operator /(const fixed &b) { return fixed((v<<8)/(b.v>>8),0); }
inline fixed operator +(const fixed &b) { return fixed(v+b.v,0); }
inline fixed operator -(const fixed &b) { return fixed(v-b.v,0); }
inline fixed& operator +=(const fixed &b) { v+=b.v; return *this; }
inline fixed& operator -=(const fixed &b) { v-=b.v; return *this; }
inline fixed& operator *=(const fixed &b) { v=(v>>8)*(b.v>>8); return *this; }
inline fixed& operator *=(const int b) { v*=b; return *this; }
inline fixed& operator *=(const double b) { *this*=fixed(b); return *this; }
inline fixed& operator *=(const float b) { *this*=fixed(b); return *this; }
inline friend float& operator *=(float &a, fixed &b) { a = a*float(b); return a; }
inline fixed& operator /=(const fixed &b) { v=(v<<8)/(b.v>>8); return *this; }
inline fixed& operator /=(const int b) { v/=b; return *this; }
inline fixed& operator /=(const unsigned int b) { v/=b; return *this; }
inline fixed& operator /=(const double b) { *this/=fixed(b); return *this; }
inline fixed& operator /=(const float b) { *this/=fixed(b); return *this; }
inline bool operator ==(const fixed &b) { return v==b.v; }
inline bool operator !=(const fixed &b) { return v!=b.v; }
inline bool operator !=(const float &b) { return v!=b/(1<<16); }
inline bool operator <(const fixed &b) { return v<b.v; }
inline bool operator <(double b) { return *this<fixed(b); }
inline bool operator >(const fixed &b) { return v>b.v; }
inline bool operator >(const int b) { return v>(b<<16); }
inline bool operator <=(const fixed &b) { return v<=b.v; }
inline bool operator >=(const fixed &b) { return v>=b.v; }
/* friend inline fixed operator * (const double &a, const fixed &b)
{ return make_fixed((a*(1<<16))*b.v); }*/
friend inline fixed operator / (const float a, const fixed &b)
{ return fixed(a)/b; }
friend inline fixed operator / (const double a, const fixed &b)
{ return fixed(a)/b; }
friend inline fixed operator + (const int a, const fixed &b)
{ return fixed((a<<16)+b.v,0); }
friend inline fixed operator + (const double a, const fixed &b)
{ return fixed(int(a*(1<<16))+b.v,0); }
friend inline fixed operator - (const double a, const fixed &b)
{ return fixed(int(a*(1<<16))-b.v,0); }
friend inline fixed operator + (const float a, const fixed &b)
{ return fixed(int(a*(1<<16))+b.v,0); }
friend inline fixed operator - (const float a, const fixed &b)
{ return fixed(int(a*(1<<16))-b.v,0); }
friend inline fixed operator - (const fixed &a, const double b)
{ return fixed(a.v-int(b*(1<<16)),0); }
friend inline fixed operator + (const fixed &a, const float b)
{ return fixed(a.v+int(b*(1<<16)),0); }
friend inline fixed operator / (const int a, const fixed &b)
{ return fixed((a<<24)/(b.v>>8),0); }
friend inline fixed operator / (const fixed &a, const int b)
{ return fixed(a.v/b,0); }
friend inline fixed operator / (const fixed &a, const long int b)
{ return fixed(a.v/b,0); }
friend inline fixed operator * (const int b, const fixed &a)
{ return fixed(a.v*b,0); }
friend inline fixed operator * (const fixed &a, const int b)
{ return fixed(a.v*b,0); }
friend inline fixed operator * (const fixed &a, const long int b)
{ return fixed(a.v*b,0); }
// inline operator float() { return v/(1<<16); }
// inline operator double() { return v/double(1<<16); }
};
inline fixed operator / (const fixed &a, const double b)
{ return fixed::divide(a,fixed(b)); }
inline fixed operator / (const fixed &a, const float b)
{ return fixed::divide(a,fixed(b)); }
inline fixed operator * (const fixed &a, const double b)
{ return fixed::multiply(a,fixed(b)); }
inline fixed operator * (const fixed &a, const float b)
{ return fixed::multiply(a,fixed(b)); }
/***************************************************************/
#endif /* SIDPLAY1_FIXPOINT_H */
|
6e685660d7a1fa55939c78fa83ddc4b39cd75459 | d506f7389997a418f0ecc5b8f6a830bf7df3512a | /MaxLocal.cpp | d302b4dc6a3ca1f58920d84ac2161f34bf564582 | [] | no_license | ali-akhi/Introductory | a64011e4f7f5fc9ba306fe5ce49f5ece7a707b5f | 2aa395f14b74875602dab714175a6b059e5e45c9 | refs/heads/main | 2023-07-10T13:18:09.996086 | 2021-08-22T20:07:53 | 2021-08-22T20:07:53 | 353,035,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | cpp | MaxLocal.cpp |
#include <bits/stdc++.h>
using namespace std;
int findLocalMaxima(int n, int arr[])
{
vector<int> mx, mn;
if (arr[0] > arr[1])
mx.push_back(0);
for(int i = 1; i < n - 1; i++)
{
if ((arr[i - 1] < arr[i]) and
(arr[i] > arr[i + 1]))
mx.push_back(i);
}
if (arr[n - 1] > arr[n - 2])
mx.push_back(n - 1);
else if (arr[n - 1] < arr[n - 2])
mn.push_back(n - 1);
if (mx.size() > 0)
{
cout << "Points of Local maxima are : ";
for(int a : mx)
return a;
}
}
inline int get(int x){
cout<< "?"<< x<< '\n';
cout.flush();
int a;
cin>>a;
return a;
}
inline void submit(int i){
cout<< "1" << i<< '\n';
cout.flush();
}
#define MAX_NAME_LEN 3
int main()
{
int N = 5;
// Given array arr[]
int arr[] = { 1, 2, 3, 4, 5};
char inputUser[100] = {0};
int value;
// Function call
int MaxLog;
MaxLog= findLocalMaxima(N, arr);
cout<< "judge >> "<< N<<endl;
for(int i=0; i<N; i++){
cout <<"solver >> ";
cin.getline(inputUser,100);
if((inputUser[0] == '?' || inputUser[0] == '!') && inputUser[1] == ' ' ){
if(inputUser[0] == '?'){
value=(int) inputUser[2] - 48;
if(value < N){
cout << "judge >> "<< arr[value]<<endl;
}else{
cout<< "is too large !"<< endl;
return 0;
}
}else if(inputUser[0] == '!'){
if(inputUser[2] -48 == MaxLog){
cout<< "accepted !"<<endl;
return 0;
}
}
}else{
cout<< "You are wrong to ask a question";
return 0;
}
}
cout<< "too many question !"<< endl;
}
|
d9b3914ae7aab6fa400958e803ca3d2eea55194a | 9ecbc437bd1db137d8f6e83b7b4173eb328f60a9 | /gcc-build/i686-pc-linux-gnu/libjava/gnu/java/locale/LocaleInformation.h | 3ba9ddd6bf21c4ef9786a6202d9b461911f9fa41 | [] | no_license | giraffe/jrate | 7eabe07e79e7633caae6522e9b78c975e7515fe9 | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | refs/heads/master | 2021-01-10T18:25:37.819466 | 2013-07-20T12:28:23 | 2013-07-20T12:28:23 | 11,545,290 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | h | LocaleInformation.h | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_java_locale_LocaleInformation__
#define __gnu_java_locale_LocaleInformation__
#pragma interface
#include <gnu/java/locale/LocaleInformation_en.h>
extern "Java"
{
namespace gnu
{
namespace java
{
namespace locale
{
class LocaleInformation;
}
}
}
};
class ::gnu::java::locale::LocaleInformation : public ::gnu::java::locale::LocaleInformation_en
{
public:
LocaleInformation ();
static ::java::lang::Class class$;
};
#endif /* __gnu_java_locale_LocaleInformation__ */
|
4e88a09496a711b4c2a9e693ee8490d5cc306c16 | cd954f06232e3b9fe008f9a6291689e75f179a88 | /acwing/每日一题·春季/Week 1/LeetCode 73. 矩阵置零.cpp | 75787514a941b6a122b128aa336942c94d42bef0 | [
"MIT"
] | permissive | upupming/algorithm | 35446f4b15f3a505041ac65c1dc6f825951d8e99 | a3807ba05960b9025e55d668ef95b3375ae71895 | refs/heads/master | 2023-08-09T03:07:18.047084 | 2023-08-01T05:57:13 | 2023-08-01T05:57:13 | 217,478,998 | 239 | 34 | MIT | 2021-08-13T05:42:26 | 2019-10-25T07:41:19 | C++ | UTF-8 | C++ | false | false | 1,596 | cpp | LeetCode 73. 矩阵置零.cpp | /*
用两个变量记录第一行和第一列是否有0。
遍历整个矩阵,用矩阵的第一行和第一列记录对应的行和列是否有0。
把含有0的行和列都置成0。
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int col0 = 1, row0 = 1;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
col0 = 0;
break;
}
}
for (int i = 0; i < n; i++) {
if (matrix[0][i] == 0) {
row0 = 0;
break;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < n; j++) {
matrix[i][j] = 0;
}
}
}
for (int i = 1; i < n; i++) {
if (matrix[0][i] == 0) {
for (int j = 1; j < m; j++) {
matrix[j][i] = 0;
}
}
}
if (col0 == 0) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
if (row0 == 0) {
for (int i = 0; i < n; i++) {
matrix[0][i] = 0;
}
}
}
};
|
66545bb9932d4a0b599d76e213f149afeaf38f6f | 5386865e2ea964397b8127aba4b2592d939cd9f2 | /grupa C/olimpiada/oblasten/2011/raboti/Haskovo/E/AVG/alphabet.cpp | 608da0e9ea0823bf94342ecb64ea9ed3c8be3ea2 | [] | no_license | HekpoMaH/Olimpiads | e380538b3de39ada60b3572451ae53e6edbde1be | d358333e606e60ea83e0f4b47b61f649bd27890b | refs/heads/master | 2021-07-07T14:51:03.193642 | 2017-10-04T16:38:11 | 2017-10-04T16:38:11 | 105,790,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | cpp | alphabet.cpp | #include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int n,m,k=0,br=0,br2=0,r=0;
cin>>n>>m;
char a;
int l=0;
for(int i=0;i<m;i++)
{
cin>>a;
br++;
while(a!='.')
{
if(l==0)
{
if(n==1){if(a=='a'||a=='A'){br2=br;}}
if(n==2){if(a=='b'||a=='B'){br2=br;}}
if(n==3){if(a=='c'||a=='C'){br2=br;}}
if(n==4){if(a=='d'||a=='D'){br2=br;}}
if(n==5){if(a=='e'||a=='E'){br2=br;}}
if(n==6){if(a=='f'||a=='F'){br2=br;}}
if(n==7){if(a=='g'||a=='G'){br2=br;}}
if(n==8){if(a=='h'||a=='H'){br2=br;}}
if(n==9){if(a=='i'||a=='I'){br2=br;}}
if(n==10){if(a=='j'||a=='J'){br2=br;}}
if(n==11){if(a=='k'||a=='K'){br2=br;}}
if(n==12){if(a=='l'||a=='L'){br2=br;}}
if(n==13){if(a=='m'||a=='M'){br2=br;}}
if(n==14){if(a=='n'||a=='N'){br2=br;}}
if(n==15){if(a=='o'||a=='O'){br2=br;}}
if(n==16){if(a=='p'||a=='P'){br2=br;}}
if(n==17){if(a=='q'||a=='Q'){br2=br;}}
if(n==18){if(a=='r'||a=='R'){br2=br;}}
if(n==19){if(a=='s'||a=='S'){br2=br;}}
if(n==20){if(a=='t'||a=='T'){br2=br;}}
if(n==21){if(a=='u'||a=='U'){br2=br;}}
if(n==22){if(a=='v'||a=='V'){br2=br;}}
if(n==23){if(a=='w'||a=='W'){br2=br;}}
if(n==24){if(a=='x'||a=='X'){br2=br;}}
if(n==25){if(a=='y'||a=='Y'){br2=br;}}
if(n==26){if(a=='z'||a=='Z'){br2=br;}}
}
l=1;
cin>>a;
}
l=0;
}
if(br2>0)cout<<"win "<<br2<<endl;
else cout<<"lose"<<endl;
return 0;
}
|
6143f6f2b573058fc3a75ba8970a0472750b7c0c | 8cdf166161d7052422634b872d39d0614438963a | /Tree/CheckSumTree.cpp | 75d087f97e32d8f1a738699349448ed2aa18ffdc | [] | no_license | ravimathur23/DataStructureAndAlgorithms | a13c468c3d3a5f8e291cf5df6e814959645e806d | 099ca1316c766a21a1f5794a308243f2772a2d0f | refs/heads/master | 2021-01-25T12:23:51.060688 | 2016-01-21T11:56:17 | 2016-01-21T11:56:17 | 24,589,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | CheckSumTree.cpp | #include <iostream>
#include <stack>
using namespace std;
class Tree{
int data;
public:
Tree(int d):data(d){left= NULL; right=NULL;};
Tree * left; Tree * right;
int get_data(){return data;}
};
int sum(Tree* node){
if(node == NULL)
return 0;
else
return sum(node->left)+node->get_data()+sum(node->right);
}
bool isSumTree(Tree* node){
if(node == NULL || (node->left == NULL && node->right == NULL))
return true;
int leftSum = sum(node->left);
int rightSum = sum(node->right);
if(leftSum+rightSum == node->get_data() && isSumTree(node->left) && isSumTree(node->right))
return true;
else
return false;
}
int main() {
// your code goes here
Tree* root = new Tree(26);
root->left = new Tree(10);
root->right = new Tree(3);
root->left->left = new Tree(4);
root->left->right = new Tree(6);
root->right->left = new Tree(3);
cout<<(isSumTree(root)==1?"true":"false")<<endl;
return 0;
}
|
68b780ef1b78a7598a4b8125b0e8c8a424cd22d9 | 87b1fdb68e2d21b4c9124b0b2161a25519818b97 | /RobotBuilder/Source/RobotBuilder Source/dmvArticulationData.cpp | fc1f0866bb7a43df44e582b007329dd34e388299 | [
"MIT"
] | permissive | mcmillan03/Robotbuilder | 5d5e37c5513c38b1ff5ab22b804537093d575ecc | 490d35fef532f1220519575021aa39764e3e1afd | refs/heads/master | 2021-07-10T02:25:40.334055 | 2017-10-09T17:55:57 | 2017-10-09T17:55:57 | 106,306,445 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 18,579 | cpp | dmvArticulationData.cpp | // dmvArticulationData.cpp: implementation of the CdmvArticulationData class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "dmvArticulationData.h"
#include "dmvRevoluteLinkData.h"
#include "dmvMobileBaseLinkData.h"
#include "dmvPrismaticLinkData.h"
#include "dmvStaticRootLinkData.h"
#include "dmvZScrewTxLinkData.h"
#include "dmvSphericalLinkData.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// In RB, we decided to make the change between closed and open articulations transparent to
// the user. All of the data for both types will be stored in this class, and the type
// will be determined by seeing if there are any secondary joints allocated.
CdmvArticulationData::CdmvArticulationData()
{
// initialize members to known values
int nCounter; // counter for 'for' loop
for (nCounter = 0; nCounter < sizeof (m_qOrientation) / sizeof (m_qOrientation[0]); nCounter++)
m_qOrientation[nCounter] = 0;
for (nCounter = 0; nCounter < sizeof (m_cvPosition) / sizeof (m_cvPosition[0]); nCounter++)
m_cvPosition[nCounter] = 0;
// note MFC will construct m_arrayLinks as empty already
// Specify the object type
m_ObjectType = ARTICULATION;
// Specify the object type
m_ArticulationType = OPEN_ARTICULATION;
// Set the default name
m_strName = "Articulation";
// Initialize showing axes
ShowWtkAxes (TRUE);
}
CdmvArticulationData::~CdmvArticulationData()
{
// on this guy's destruction, we want to deallocate all of the links in
// the list
CdmvLinkPointer LinkPointer;
// go through the list freeing
int nCounter; // counter for 'for' loop
for (nCounter = 0; nCounter < m_arrayLinks.GetSize (); nCounter ++)
{
LinkPointer = m_arrayLinks.GetAt (nCounter);
// first make sure the pointer is not NULL
if (LinkPointer.pLink)
delete LinkPointer.pLink; // this assumes that new was used
// for the allocation
// it is assumed that the parent is somewhere in the list, so it will be
// deallocated when we get to it in the list
}
// Deallocate any secondary joints
CdmvSecJointData* pSecJoint = NULL;
// go through the list freeing
for (nCounter = 0; nCounter < m_arraySecondaryJoints.GetSize (); nCounter ++)
{
pSecJoint = m_arraySecondaryJoints.GetAt (nCounter);
// first make sure the pointer is not NULL
if (pSecJoint)
delete pSecJoint; // this assumes that new was used
// for the allocation
}
m_arraySecondaryJoints.RemoveAll ();
}
void CdmvArticulationData::SetReferenceSystem(Quaternion quat, CartesianVector pos)
{
int nCounter;
for (nCounter = 0; nCounter < sizeof (m_qOrientation) / sizeof (m_qOrientation[0]); nCounter++)
{
m_qOrientation[nCounter] = quat[nCounter];
}
for (nCounter = 0; nCounter < sizeof (m_cvPosition) / sizeof (m_cvPosition[0]); nCounter++)
m_cvPosition[nCounter] = pos[nCounter];
}
void CdmvArticulationData::AddLink(CdmvLinkData * pLink, CdmvLinkData * pLinkParent)
{
CdmvLinkPointer LinkPointer;
LinkPointer.pLink = pLink;
LinkPointer.pLinkParent = pLinkParent;
m_arrayLinks.Add (LinkPointer);
}
void CdmvArticulationData::GetRefSystem(Quaternion quat, CartesianVector pos) const
{
int nCounter;
for (nCounter = 0; nCounter < 4; nCounter++)
*(quat + nCounter) = m_qOrientation[nCounter];
for (nCounter = 0; nCounter < 3; nCounter++)
*(pos + nCounter) = m_cvPosition[nCounter];
}
void CdmvArticulationData::InsertLinkChild(CdmvLinkData *pLink, CdmvLinkData *pLinkParent)
{
// note the pLinkParent maybe NULL if its the new root
ASSERT (pLink);
// Go through the link array and change all links with the parent as the passed parent
// to point to the new link
int nNumLinks = m_arrayLinks.GetSize ();
int nCounter;
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLinkParent == pLinkParent)
{
// then need to push it down by making pLink its parent
CdmvLinkPointer LinkMap;
LinkMap.pLink = m_arrayLinks.GetAt (nCounter).pLink;
LinkMap.pLinkParent = pLink;
m_arrayLinks.SetAt (nCounter, LinkMap);
}
}
// create a link map to insert
CdmvLinkPointer LinkMap;
LinkMap.pLink = pLink;
LinkMap.pLinkParent = pLinkParent;
// Search for the link array for the parent, and then insert after it
// If the parent is NULL, then insert it first
if (pLinkParent == NULL)
{
m_arrayLinks.InsertAt (0, LinkMap);
}
else
{
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLink == pLinkParent)
{
m_arrayLinks.InsertAt (nCounter + 1, LinkMap);
break;
}
}
// should find the parent
ASSERT (nCounter != nNumLinks);
}
}
void CdmvArticulationData::InsertLinkSibling(CdmvLinkData *pLink, CdmvLinkData *pLinkParent)
{
// This function is similar to InsertLinkChild, but since a sibling is being added
// there isn't a need to move the children down a level
int nNumLinks = m_arrayLinks.GetSize ();
int nCounter;
// create a link map to insert
ASSERT (this);
// note the pLinkParent maybe NULL if its the new root
ASSERT (pLink);
CdmvLinkPointer LinkMap;
LinkMap.pLink = pLink;
LinkMap.pLinkParent = pLinkParent;
// Search for the link array for the parent, and then insert after it
// If the parent is NULL, then insert it first
if (pLinkParent == NULL)
{
m_arrayLinks.InsertAt (0, LinkMap);
}
else
{
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLink == pLinkParent)
{
m_arrayLinks.InsertAt (nCounter + 1, LinkMap);
break;
}
}
// should find the parent
ASSERT (nCounter != nNumLinks);
}
}
void CdmvArticulationData::DeleteLink(CdmvLinkData *pLink)
{
CutLink (pLink);
// Now free the memory for the link
delete pLink;
}
void CdmvArticulationData::DeleteLinkRecursively(CdmvLinkData *pLink)
{
ASSERT (pLink);
int nNumLinks = m_arrayLinks.GetSize ();
int nCounter;
CdmvLinkPointer DeletedLinkMap; // temporarily store the deleted data
// Remove the link from the array
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLink == pLink)
{
// Store for later use when updating the deleted link's children
DeletedLinkMap = m_arrayLinks.GetAt (nCounter);
// Now remove it from the array
m_arrayLinks.RemoveAt (nCounter);
break;
}
}
ASSERT (nCounter != nNumLinks);
// Free the link memory
delete DeletedLinkMap.pLink;
// Decrement the link count since one once removed
nNumLinks --;
// Find all links that have this link as a parent and delete them recursively
for (nCounter = 0; nCounter < m_arrayLinks.GetSize (); nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLinkParent == pLink)
{
DeleteLinkRecursively (m_arrayLinks.GetAt (nCounter).pLink);
// The present implementation shouldn't allow this, but
// restart the counter in case some links before the
// current position were deleted
nCounter = -1;
}
}
}
ArticulationType CdmvArticulationData::GetArticulationType() const
{
// Depends if there are secondary joints allocated
if (m_arraySecondaryJoints.GetSize () > 0)
return CLOSED_ARTICULATION;
else
return OPEN_ARTICULATION;
}
/*
CdmvArticulationData::CdmvArticulationData(const CdmvArticulationData &rArticulation)
{
// initialize members to known values
int nCounter; // counter for 'for' loop
for (nCounter = 0; nCounter < sizeof (m_qOrientation) / sizeof (m_qOrientation[0]); nCounter++)
m_qOrientation[nCounter] = rArticulation.m_qOrientation[nCounter];
for (nCounter = 0; nCounter < sizeof (m_cvPosition) / sizeof (m_cvPosition[0]); nCounter++)
m_cvPosition[nCounter] = rArticulation.m_cvPosition[nCounter];
// create a copy of the array of links -- first go through and
int nNumberOfLinks = rArticulation.m_arrayLinks.GetSize ();
for (nCounter = 0; nCounter < nNumberOfLinks; nCounter++)
{
CdmvLinkPointer LinkPointer;
LinkPointer.pLink = new CdmvLinkData (*(rArticulation.m_arrayLinks.GetAt (nCounter).pLink));
// find the parent
if (rArticulation.m_arrayLinks.GetAt (nCounter).pLinkParent == NULL)
{
LinkPointer.pLinkParent = NULL;
}
else
{
// Otherwise look back through the old link array to find the index number of the
// parent and then set the pLink of that that to the pParentLink of the new link in
// need of a parent
int nInnerCounter;
for (nInnerCounter = 0; nInnerCounter < nCounter; nInnerCounter)
{
if (rArticulation.m_arrayLinks.GetAt (nInnerCounter).pLink ==
rArticulation.m_arrayLinks.GetAt (nCounter).pLink)
{
// Then found the parent index so use that info to find the parent in the new array
LinkPointer.pLinkParent = m_arrayLinks.GetAt (nInnerCounter).pLink;
}
}
// the parent should always be found
ASSERT ((nInnerCounter == nCounter) ? FALSE : TRUE);
}
}
// Specify the object type
m_ObjectType = rArticulation.m_ObjectType;
// Specify the object type
m_ArticulationType = rArticulation.m_ArticulationType;
ASSERT (FALSE); // I don't want to use this in case the pointers change ?!?!?
}
*/
CdmvLinkData* CdmvArticulationData::FindLinkByName(CString strName) const
{
int nCounter;
int nNumLinks = m_arrayLinks.GetSize ();
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
CString strCurrentLinkName = m_arrayLinks.GetAt (nCounter).pLink->GetName ();
if (strCurrentLinkName == strName)
return m_arrayLinks.GetAt (nCounter).pLink;
}
return NULL;
}
void CdmvArticulationData::CutLink(CdmvLinkData *pLink)
{
ASSERT (pLink != NULL);
int nNumLinks = m_arrayLinks.GetSize ();
int nCounter;
CdmvLinkPointer DeletedLinkMap; // temporarily store the deleted data
// Remove the link from the array
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLink == pLink)
{
// Store for later use when updating the deleted link's children
DeletedLinkMap = m_arrayLinks.GetAt (nCounter);
// Now remove it from the array
m_arrayLinks.RemoveAt (nCounter);
break;
}
}
ASSERT (nCounter != nNumLinks);
// Find all links that have this link as a parent and set their
// parent to be this link's parent
// since a link was deleted, decrement the size
nNumLinks --;
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLinkParent == pLink)
{
CdmvLinkPointer LinkMap;
LinkMap.pLink = m_arrayLinks.GetAt (nCounter).pLink;
LinkMap.pLinkParent = DeletedLinkMap.pLinkParent;
m_arrayLinks.SetAt (nCounter, LinkMap);
}
}
// If it is a closed loop, need to check the list of secondary joint for
// this link
if (this->GetArticulationType () == CLOSED_ARTICULATION)
{
DeleteSecJointsByLink (pLink);
}
}
void CdmvArticulationData::CopyLink(CdmvLinkData *pLink, CdmvLinkData **ppNewLink)
{
ASSERT (pLink);
if (pLink->GetLinkType () == REVOLUTE_LINK)
{
CdmvRevoluteLinkData *p = dynamic_cast <CdmvRevoluteLinkData*> (pLink);
*ppNewLink = new CdmvRevoluteLinkData ((*p));
}
else if (pLink->GetLinkType () == MOBILE_BASE_LINK)
{
CdmvMobileBaseLinkData *p = dynamic_cast <CdmvMobileBaseLinkData*> (pLink);
*ppNewLink = new CdmvMobileBaseLinkData ((*p));
}
else if (pLink->GetLinkType () == PRISMATIC_LINK)
{
CdmvPrismaticLinkData *p = dynamic_cast <CdmvPrismaticLinkData*> (pLink);
*ppNewLink = new CdmvPrismaticLinkData ((*p));
}
else if (pLink->GetLinkType () == SPHERICAL_LINK)
{
CdmvSphericalLinkData *p = dynamic_cast <CdmvSphericalLinkData*> (pLink);
*ppNewLink = new CdmvSphericalLinkData ((*p));
}
else if (pLink->GetLinkType () == STATIC_ROOT_LINK)
{
CdmvStaticRootLinkData *p = dynamic_cast <CdmvStaticRootLinkData*> (pLink);
*ppNewLink = new CdmvStaticRootLinkData ((*p));
}
else if (pLink->GetLinkType () == ZSCREW_TX_LINK)
{
CdmvZScrewTxLinkData *p = dynamic_cast <CdmvZScrewTxLinkData*> (pLink);
*ppNewLink = new CdmvZScrewTxLinkData ((*p));
}
else
{
// Unexpected state
ASSERT (FALSE);
}
}
void CdmvArticulationData::InsertLinkAsParent(CdmvLinkData *pNewLink, CdmvLinkData *pOldLink)
{
ASSERT (pNewLink && pOldLink);
// Go through the link array to find the old link
int nNumLinks = m_arrayLinks.GetSize ();
int nCounter;
for (nCounter = 0; nCounter < nNumLinks; nCounter++)
{
if (m_arrayLinks.GetAt (nCounter).pLink == pOldLink)
{
// Get a copy of the link pointer of the old link
CdmvLinkPointer OldLinkMap;
OldLinkMap = m_arrayLinks.GetAt (nCounter);
// Build the new link
CdmvLinkPointer NewLinkMap;
NewLinkMap.pLink = pNewLink;
NewLinkMap.pLinkParent = OldLinkMap.pLinkParent;
// Insert the new link before this one
m_arrayLinks.InsertAt (nCounter, NewLinkMap);
// Change the parent of the old link to the new link
OldLinkMap.pLinkParent = pNewLink;
// Reset the data - note need to increment the index because it was pushed
// back one by the new link
m_arrayLinks.SetAt (nCounter + 1, OldLinkMap);
// Done so return
return;
}
}
// If get here, the old link was not found -- this should never happen
ASSERT (FALSE);
}
void CdmvArticulationData::AddSecJoint (CdmvSecJointData* pSecJoint)
{
ASSERT (pSecJoint);
m_arraySecondaryJoints.Add (pSecJoint);
}
void CdmvArticulationData::DeleteSecJoint(CdmvSecJointData *pSecJoint)
{
ASSERT (pSecJoint);
int nNumSecJoints = m_arraySecondaryJoints.GetSize ();
int nCounter;
// Remove the link from the array
for (nCounter = 0; nCounter < nNumSecJoints; nCounter++)
{
if (m_arraySecondaryJoints.GetAt (nCounter) == pSecJoint)
{
// Now remove it from the array
m_arraySecondaryJoints.RemoveAt (nCounter);
// free the memory
delete pSecJoint;
break;
}
}
ASSERT (nCounter != nNumSecJoints);
}
// to remove a the secondary joints connected to a given link pointer
void CdmvArticulationData::DeleteSecJointsByLink(CdmvLinkData *pLinkData)
{
ASSERT (pLinkData);
int nNumSecJoints = m_arraySecondaryJoints.GetSize ();
int nCurrentIndex = 0;
// Remove the link from the array
while (nCurrentIndex < nNumSecJoints)
{
if ((m_arraySecondaryJoints.GetAt (nCurrentIndex))->GetLinkA () == pLinkData
|| (m_arraySecondaryJoints.GetAt (nCurrentIndex))->GetLinkB () == pLinkData)
{
// Need to remove the secondary joint connected to the link
m_arraySecondaryJoints.RemoveAt (nCurrentIndex);
// Note that the index won't advance because the current index was just deleted
// and everything in the array will shift down. The size needs to be updated
// though to reflect the deletion.
nNumSecJoints --;
}
else
{
// The advance the index and look at the next joint
nCurrentIndex ++;
}
}
}
void CdmvArticulationData::AddSoftSecJoint(CdmvSecJointData *pSecJoint)
{
ASSERT (pSecJoint);
// set the joint as soft
pSecJoint->SetSoftOrHard (SOFT_SEC_JOINT);
AddSecJoint (pSecJoint);
}
void CdmvArticulationData::AddHardSecJoint(CdmvSecJointData *pSecJoint)
{
ASSERT (pSecJoint);
// set the joint as hard
pSecJoint->SetSoftOrHard (HARD_SEC_JOINT);
AddSecJoint (pSecJoint);
}
// This function can be called to determine if the current articulation is valid.
// The return value has information about the error
int CdmvArticulationData::ValidateArticulation() const
{
// Check that there is only one static root link
if (GetNumberOfStaticRootLinks () > 1)
return ART_ERROR_TOO_MANY_STATIC_ROOT_LINK;
// Check if the static root link is anything but the child of the base
if (GetNumberOfStaticRootLinks () == 1)
{
// Find the link
int i;
for (i = 0; i < m_arrayLinks.GetSize (); i++)
{
if (m_arrayLinks.GetAt (i).pLink->GetLinkType () == STATIC_ROOT_LINK)
{
// Found the static root link - check that its parent is the base
if (m_arrayLinks.GetAt (i).pLinkParent != NULL)
return ART_ERROR_STATIC_ROOT_LINK_BAD_PLACE;
}
}
}
// No errors detected
return ART_ERROR_NONE;
}
// Returns the number of static root links in the articulation
int CdmvArticulationData::GetNumberOfStaticRootLinks() const
{
int nCount = 0;
// Go through each link
int i;
for (i = 0; i < m_arrayLinks.GetSize (); i++)
{
if (m_arrayLinks.GetAt (i).pLink->GetLinkType () == STATIC_ROOT_LINK)
nCount ++;
}
return nCount;
}
// Returns number of links in the articulation
int CdmvArticulationData::GetNumberOfLinks() const
{
return m_arrayLinks.GetSize ();
}
WTnode* CdmvArticulationData::GetCameraCenterOfInterest()
{
// Go through each link and check the flag
// Start with the articulation
if (this->IsCameraCenterOfInterest ())
return this->GetWtkNode ();
int i;
for (i = 0; i < m_arrayLinks.GetSize (); i++)
{
if (m_arrayLinks.GetAt (i).pLink->IsCameraCenterOfInterest ())
return m_arrayLinks.GetAt (i).pLink->GetWtkNode ();
}
// else none selected so return NULL
return NULL;
}
CString CdmvArticulationData::GetCenterOfInterestName()
{
// Go through each link and check the flag
// Start with the articulation
if (this->IsCameraCenterOfInterest ())
return this->GetName();
int i;
for (i = 0; i < m_arrayLinks.GetSize (); i++)
{
if (m_arrayLinks.GetAt (i).pLink->IsCameraCenterOfInterest ())
return m_arrayLinks.GetAt (i).pLink->GetName ();
}
// else none selected, so it must be the Inertial Axes
CString strReturn;
strReturn.LoadString(IDS_STRING_INERTIAL_AXES);
return strReturn;
}
// Go through each link and the articulation and set the state false which says
// if the item is a COI
void CdmvArticulationData::ClearCameraCenterOfInterest()
{
// Start with the articulation
this->IsCameraCenterOfInterest (FALSE);
// Go through each link
int i;
for (i = 0; i < m_arrayLinks.GetSize (); i++)
{
m_arrayLinks.GetAt (i).pLink->IsCameraCenterOfInterest (FALSE);
}
}
|
9591369f71a051fc61313cf3a3e9ed5e72aed243 | c400b969e46afb5b230745332e55b27f285b7e52 | /SparseVoxelOctree.cpp | 330ce1ecd182d58c26f356341e7a698beb29d65b | [] | no_license | Jiafeimaochuanqi/Sparse-Voxel-DAGs | 3e3af5bf88cb89d0e37903face571d46dea6d99f | 10caf70e93a8e4071b99361de1dca00dd6605527 | refs/heads/master | 2023-03-17T11:53:13.274768 | 2015-06-10T17:48:57 | 2015-06-10T17:48:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,536 | cpp | SparseVoxelOctree.cpp | /**
* SparseVoxelOctree.cpp
*
* by Brent Williams
*/
#include "SparseVoxelOctree.hpp"
/**
* Instantiates and initializes the SVO.
*/
SparseVoxelOctree::SparseVoxelOctree(const unsigned int levelsVal, const BoundingBox& boundingBoxVal, const std::vector<Triangle> triangles, std::string meshFilePath)
: boundingBox(boundingBoxVal),
numLevels(levelsVal),
size(pow(8, levelsVal)),
dimension(pow(2,levelsVal)),
voxelWidth(0)
{
if (numLevels <= 2)
{
std::string err("\nNumber of levels too small\n");
std::cerr << err;
throw std::out_of_range(err);
}
boundingBox.square();
voxelWidth = (boundingBox.maxs.x - boundingBox.mins.x) / dimension;
levels = new void*[numLevels-1]; // has the -1 because the last two levels are uint64's
levelSizes = new unsigned int[numLevels-1]();
build(triangles,meshFilePath);
}
/**
* Free any allocated data and clean up
*/
SparseVoxelOctree::~SparseVoxelOctree()
{
}
/**
* Build the SVO that works for >= 4 levels.
*
* Tested: 2-16-2014
*/
void SparseVoxelOctree::build(const std::vector<Triangle> triangles, std::string meshFilePath)
{
auto start = chrono::steady_clock::now();
Voxels* leafVoxels = new Voxels(numLevels, boundingBox, triangles, meshFilePath);
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << "\t\tTime Voxelization: " << chrono::duration <double, milli> (diff).count() << " ms" << endl;
auto svoStartTime = chrono::steady_clock::now();
uint64_t* leafVoxelData = leafVoxels->data;
unsigned int numLeafs = leafVoxels->dataSize;
voxelTriangleIndexMap = leafVoxels->voxelTriangleIndexMap;
// std::cout << "levels: " << numLevels << "\n";
// std::cout << "Number of leaf nodes: " << numLeafs << "\n";
// Save the pointer to the leaf nodes
unsigned int currentLevel = numLevels-2;
levels[currentLevel] = (void*)leafVoxelData;
cerr << "Leaf Level = " << currentLevel << endl;
currentLevel--;
if (numLevels <= 3)
{
std::cerr << "CANNOT build SVO with levels <= 3.\nExitting...\n";
exit(EXIT_FAILURE);
}
int numPrevLevelNodes = numLeafs; //512
int numCurrLevelNodes = numPrevLevelNodes / 8; //64
SVONode* prevLevelNodes;
SVONode* currLevelNodes;
currLevelNodes = new SVONode[numCurrLevelNodes]();
levelSizes[numLevels-2] = 0;
// Set the level above the leaf nodes
for (int i = 0; i < numPrevLevelNodes; i++)
{
if (leafVoxelData[i] > 0)
{
currLevelNodes[i/8].childPointers[i%8] = (void *) &(leafVoxelData[i]);
levelSizes[numLevels-2]++;
}
}
levels[currentLevel] = (void*)currLevelNodes;
//levelSizes[currentLevel] = numCurrLevelNodes * sizeof(SVONode);
currentLevel--;
// Set the rest of the non leaf nodes
while(numCurrLevelNodes >= 64)
{
numPrevLevelNodes = numCurrLevelNodes; //64
numCurrLevelNodes /= 8; // 8
prevLevelNodes = currLevelNodes;
currLevelNodes = new SVONode[numCurrLevelNodes];
//levelSizes[currentLevel] = numCurrLevelNodes * sizeof(SVONode);
levelSizes[currentLevel+1] = 0;
// For each of the previous level's nodes we set the child pointers
for (int i = 0; i < numPrevLevelNodes; i++)
{
if (isNodeNotEmpty(&prevLevelNodes[i]))
{
currLevelNodes[i/8].childPointers[i%8] = (void *) &(prevLevelNodes[i]);
levelSizes[currentLevel+1]++;
}
}
// Save the pointer for each level's nodes in the level's array
levels[currentLevel] = currLevelNodes;
currentLevel--;
}
// Set the root node
prevLevelNodes = currLevelNodes;
root = new SVONode;
levelSizes[currentLevel+1] = 0;
for (int i = 0; i < 8; i++)
{
if (isNodeNotEmpty(&prevLevelNodes[i]))
{
root->childPointers[i] = (void *) &(prevLevelNodes[i]);
levelSizes[currentLevel+1]++;
}
}
// Save the pointer for root node in the levels array
levels[currentLevel] = root;
levelSizes[currentLevel] = 1;
uint64_t totalSVOMemory = 0;
cout << "SVO Size: " << endl;
for (int i = 0; i < numLevels-2; ++i)
{
cout << "[" << i << "]: " << levelSizes[i] << endl;
totalSVOMemory += levelSizes[i] * sizeof(SVONode);
}
cout << "[" << numLevels-2 << "]: " << levelSizes[numLevels-2] << endl;
totalSVOMemory += levelSizes[numLevels-2] * sizeof(uint64_t);
cout << "SVO (without materials) Memory Size: " << totalSVOMemory << " (" << getMemorySize(totalSVOMemory) << ")" << endl;
auto svoEndTime = chrono::steady_clock::now();
auto svoDiff = svoEndTime - svoStartTime;
cout << "\t\tTime SVO Building: " << chrono::duration <double, milli> (svoDiff).count() << " ms" << endl;
}
string SparseVoxelOctree::getMemorySize(unsigned int size)
{
string b = " B";
string kb = " KB";
string mb = " MB";
string gb = " GB";
string units[] = {b,kb,mb,gb};
float currentSize = (float)size;
float lastSize = (float)size;
int i;
for (i = 0; i < 4 && currentSize > 1.0f; ++i)
{
lastSize = currentSize;
currentSize /= 1024.0f;
}
return to_string(lastSize) + units[i-1];
}
/**
* Returns a boolean indicating whether all the node's children are not empty.
*
* Tested: 1-16-2015
*/
bool SparseVoxelOctree::isNodeNotEmpty(SVONode *node)
{
for (int i = 0; i < 8; i++)
{
if (node->childPointers[i] != NULL)
{
return true;
}
}
return false;
}
/**
* Returns a boolean indicating whether the node's leaf at the ith bit is set.
*
* Tested: 1-27-2014
*/
bool SparseVoxelOctree::isLeafSet(uint64_t* node, unsigned int i)
{
uint64_t leaf = (uint64_t) *node;
uint64_t toAnd = (1L << i);
return (leaf & toAnd) > 0;
}
/**
* Returns a boolean indicating whether the node's child is set.
*
* Tested: 1-16-2015
*/
bool SparseVoxelOctree::isChildSet(SVONode *node, unsigned int i)
{
return node->childPointers[i] != NULL;
}
/**
* Returns a boolean indicating whether the voxel at the given coordinate is
* set.
*
* Tested: 2-16-2014
*/
bool SparseVoxelOctree::isSet(unsigned int x, unsigned int y, unsigned int z)
{
void* currentNode = root;
int currentLevel = numLevels;
unsigned int mortonIndex = mortonCode(x,y,z,currentLevel);
int divBy = pow(8.0f, (float)currentLevel-1);
int modBy = divBy;
int index = mortonIndex / divBy;
while (divBy >= 64)
{
if (!isChildSet((SVONode*)currentNode, index))
{
return false;
}
currentNode = (void*) ((SVONode*)currentNode)->childPointers[index];
modBy = divBy;
divBy /= 8;
index = (mortonIndex % modBy) / divBy;
}
index = mortonIndex % modBy;
return isLeafSet((uint64_t*)currentNode, index);
}
/**
* Returns a boolean indicating whether the voxel at the given coordinate is
* set.
*
* Tested: 2-16-2014
*/
void SparseVoxelOctree::printBinary()
{
unsigned int i, j, k;
for (k = 0; k < dimension; k++)
{
std::cout << "z = " << k << "\n";
for (j = 0; j < dimension; j++)
{
for (i = 0; i < dimension; i++)
{
if (isSet(i,j,k))
std::cout << "1 ";
else
std::cout << "0 ";
}
std::cout << "\n";
}
std::cout << "\n";
}
}
/**
* Writes the voxel data to tga files where the file name is the z axis voxel number.
*
* Tested: 12-15-2014
*/
void SparseVoxelOctree::writeImages()
{
unsigned int i, j, k;
for (k = 0; k < dimension; k++)
{
cout << "Witing image " << k << endl;
Image image(dimension,dimension);
for (j = 0; j < dimension; j++)
{
for (i = 0; i < dimension; i++)
{
if (isSet(i,j,k))
{
image.setColor(i,j, 1.0f,1.0f,1.0f);
}
}
}
char fileName[30];
sprintf(fileName, "./images/%04d.tga",k);
image.writeTGA((fileName));
}
}
/**
* Given a level as input, it will return a number of active nodes in that level
* Tested:
*/
unsigned int SparseVoxelOctree::countAtLevel(unsigned int level)
{
unsigned int count = 0;
if (level == 0)
return 1;
else if (level == 1)
{
SVONode curr = *root;
for (int i = 0; i < 8; i++)
{
if (curr.childPointers[i] != NULL)
{
count++;
}
}
}
return count;
}
|
ae317675a5b1c83b90bec139ffd2c71ddf544aef | a248cf5584c4d3d0841be339c9c54b14af590b0f | /adding.cpp | 8efc0fbf5f8e05b873acfde0e051c2620ccf7005 | [] | no_license | Patrick-Gemmell/ICS3U-Unit3-01-CPP | aa55a51dee1afb6c12fffd305d48c953f7651d57 | e43f60db5054a27245444cc79c2e26447b058725 | refs/heads/master | 2020-08-01T22:33:55.269236 | 2019-09-26T17:08:16 | 2019-09-26T17:08:16 | 211,139,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | adding.cpp | // Copyright (c) 2019 Patrick Gemmell All rights reserved.
//
// Created by: Patrick Gemmell
// Created on: September 12 2019
// This Program calculates the total of two integers
#include <iostream>
int main() {
// This function calculates area and perimeter
int integer1;
int integer2;
int total;
std::cout << "Enter the first integer: " << std::endl;
std::cin >> integer1;
std::cout << "Enter the second integer: " << std::endl;
std::cin >> integer2;
total = integer1+integer2;
std::cout << "" << std::endl;
std::cout << integer1 << "+" << integer2 << "=" << total << std::endl;
}
|
93d1f5646a5f44d12647f43cbeeb81b2536fc286 | ec3b8fcf4cafe11a7fed25dd9de1304a8e22a6a9 | /src/external/android-jni-wrap/wrap/java.lang.cpp | 523bbaaee110b2c94bb68025b788b2da199a7588 | [
"CC-BY-4.0",
"BSL-1.0"
] | permissive | mateosss/monado | acfcdf105545535c122fe4a720f0e740b028ab75 | a6da40de505b58c28f50dc578d36b7b2f0887ad7 | refs/heads/master | 2023-04-13T22:25:42.732317 | 2021-03-09T17:45:45 | 2021-03-09T18:16:01 | 339,816,160 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | cpp | java.lang.cpp | // Copyright 2020, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
// Author: Ryan Pavlik <ryan.pavlik@collabora.com>
#include "java.lang.h"
namespace wrap {
namespace java::lang {
Class::Meta::Meta()
: MetaBase(Class::getTypeName()),
forName(classRef().getStaticMethod(
"forName", "(Ljava/lang/String;)Ljava/lang/Class;")),
forName1(classRef().getStaticMethod(
"forName",
"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;")),
forName2(classRef().getStaticMethod(
"forName",
"(Ljava/lang/Module;Ljava/lang/String;)Ljava/lang/Class;")),
getCanonicalName(
classRef().getMethod("getCanonicalName", "()Ljava/lang/String;")) {}
ClassLoader::Meta::Meta()
: MetaBaseDroppable(ClassLoader::getTypeName()),
loadClass(classRef().getMethod("loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;")),
findLibrary(classRef().getMethod(
"findLibrary", "(Ljava/lang/String;)Ljava/lang/String;")) {
MetaBaseDroppable::dropClassRef();
}
System::Meta::Meta()
: MetaBase(System::getTypeName()),
mapLibraryName(classRef().getStaticMethod(
"mapLibraryName", "(Ljava/lang/String;)Ljava/lang/String;")) {}
} // namespace java::lang
} // namespace wrap
|
7f7135df978e0babfbd8470b4e55d39c79535ffc | 4a954a2bf42fd7568035c3657b21e48c745db21e | /hacclient/EngineFunctions.cpp | 1897677c9663c1f42f2274019cbb2bd6a1920937 | [
"MIT"
] | permissive | ChadSki/hacclient | bfe6fcf9e12e484f8a95cb9fc3e6c6ffb4a95d61 | f1471e1f74de13dbbc1ae6d92238939e010ff7d6 | refs/heads/master | 2021-01-18T15:26:50.247524 | 2017-03-30T03:15:13 | 2017-03-30T03:15:13 | 86,653,289 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,897 | cpp | EngineFunctions.cpp | #include "EngineFunctions.h"
#include "EngineState.h"
#include "EnginePointers.h"
#include <string>
#include <sstream>
std::uintptr_t HUDPrint, SoundPlay, ChatSend, GenMD5, Connect, CommandExecute,
DisplayMenu, LoadMap, CommandInject, ChatLocalSend,
OverlayResolve;
float* pDrawDistance;
char* VehicleControl;
std::int16_t* stringIndex;
bool* displayAttentionBox;
CRITICAL_SECTION critSection;
using namespace EngineTypes;
namespace {
void RewindBuffer();
}
/* Critical sections are used to protect all engine functions as a precaution
rather than assuming they're all thread safe. Won't help if HAC and Halo
call the same non-thread safe function at the same time. */
void initCritSection() {
InitializeCriticalSectionAndSpinCount(&critSection, 1024);
serverJoinCritSection = CreateSemaphore(NULL, 1, 1, NULL); //temporary
}
void destroyCritSection() {
DeleteCriticalSection(&critSection);
}
void HUDMessage(const std::wstring& message) {
HUDMessage(message.c_str());
}
void HUDMessage(const std::string& message) {
std::wstring wmessage;
wmessage.assign(message.begin(), message.end());
HUDMessage(wmessage.c_str());
}
void HUDMessage(const WCHAR* message) {
wchar_t copy[64];
wcscpy_s(copy, 64, message);
EnterCriticalSection(&critSection);
__asm {
lea eax, copy
push eax
mov eax, 0 // player index
call HUDPrint
add esp, 4
}
LeaveCriticalSection(&critSection);
}
void PlayMPSound(multiplayer_sound index) {
__asm {
push 0
movsx esi, index
or edi, -1
call SoundPlay
add esp, 4
}
}
/* TODO: Not thread safe - should send a copy of the buffer to be sent,
* not the original as it may have been modified by the time the networking
* thread requires it. Warning, memory leak!
*/
void ChatMessage(const WCHAR* message, CHAT_TYPE ctype) {
wchar_t *copy = new wchar_t[64];
wchar_t *copy2 = new wchar_t[64];
wcscpy_s(copy, 64, message);
wcscpy_s(copy2, 64, message);
EnterCriticalSection(&critSection);
__asm {
mov eax, ctype
push ebx
mov edx, copy
mov esi, copy2
push esp
call ChatSend
add esp, 8
}
LeaveCriticalSection(&critSection);
}
void chatLocal(const std::string& message) {
std::wstring wmessage;
wmessage.assign(message.begin(), message.end());
const wchar_t* msg = wmessage.c_str();
__asm {
push msg
call ChatLocalSend
add esp, 4
}
}
void GenerateMD5(const char* data, DWORD data_length, char* output) {
EnterCriticalSection(&critSection);
__asm {
push output
push data_length
push data
call GenMD5
add esp, 0x0C
}
LeaveCriticalSection(&critSection);
}
/*
* Forces Halo to join a server - doesn't seem to have any
* stability problems even when called from another thread.
*/
void serverConnect(const char *address, const wchar_t *password) {
EnterCriticalSection(&critSection);
_asm {
mov edx, password
mov eax, address
push edx
call Connect
add esp, 4
}
LeaveCriticalSection(&critSection);
}
void commandConnect(const std::string& ip, const uint16_t& port, const std::wstring& password) {
std::stringstream info;
char wpassword[33];
sprintf_s(wpassword, 32, "%ws", password.c_str());
info << "connect " << ip << ":" << port << " " << wpassword;
ShowMainMenuHaloThread();
ExecuteCommand(info.str().c_str());
}
void DrawDistance(float distance) {
*pDrawDistance = distance;
}
void ExecuteCommand(const char* command, bool rewind) {
EnterCriticalSection(&critSection);
__asm {
mov edi, command
push edi
call CommandExecute
add esp, 4
}
if(rewind) {
RewindBuffer();
}
LeaveCriticalSection(&critSection);
}
void ShowMainMenu() {
EnterCriticalSection(&critSection);
__asm {
call DisplayMenu
}
LeaveCriticalSection(&critSection);
}
//@todo - make this useful
void attentionBox(const std::string& message, bool quit) {
*stringIndex = 21;
}
/*
* Causes Halo's main thread to load the main menu as opposed
* to one of HAC's threads
*/
void ShowMainMenuHaloThread() {
*stringIndex = -1;
*displayAttentionBox = true;
}
/*
* Calls Halo's map load function to add a map to the table.
* Checksum needs to be added to the hash-map to bypass the game's
* own checksum function or it'll crash (after checksumming)!
*/
void addMap(const char* name) {
__asm {
pushfd
pushad
push 0x13
mov eax, name
call LoadMap
add esp, 4
popad
popfd
}
}
void ToggleMTV(bool state) {
*VehicleControl = state? 0xEB : 0x74; //jmp : je
}
namespace {
/*
* Rewind the console history buffer back by one command and zero it out.
* This is to allow HAC to execute commands without the user seeing them
* in their history. Wipes out their oldest command, an acceptable
* compromise for not having to implement more code for the same effect.
*/
void RewindBuffer() {
void *location = (*histBuffLen * 255) + histBuff;
memset(location, 0, 255);
*histBuffLen = *histBuffLen == 0? 7 : *histBuffLen - 1;
}
} |
db83eaeb46eb6e479d412f360a8f662952ac6510 | fe0fd9a242ae51024f69abe66bcea33435bcf027 | /hooks/DesyncFix.cpp | b9382b8c22c026707952ddda73e5a2376e4131f0 | [] | no_license | Strogoo/FA-Binary-Patches | 320d98fbe4fda7405d6e4e0152503b3533c91034 | f5bcbe7ce4e2880c9339f31bacecb272bd6f2ce2 | refs/heads/master | 2023-07-29T07:26:29.800985 | 2023-02-25T15:21:07 | 2023-02-25T15:21:07 | 221,268,045 | 0 | 0 | null | 2019-11-12T16:56:27 | 2019-11-12T16:56:27 | null | UTF-8 | C++ | false | false | 8,872 | cpp | DesyncFix.cpp | #include "../define.h"
asm(
//HOOK decode
".section h0; .set h0,0x6E4150;"
"jmp "QU(Moho__CDecoder__DecodeMessage)";"
"nop;"
".section h1; .set h1,0x74B8B0;"
"jmp "QU(EndGame)";"
".section h2; .set h2,0x489F90;"
"jmp "QU(Gpg_Net_Entry)";"
"nop;"
"nop;"
//HOOK instance running
".section h3; .set h3,0x8CF0D2;"
"jmp 0x8CF23E;"
"nop;"
//HOOK recvfrom
".section h4; .set h4,0x48A280;"
"jmp "QU(_recvfrom)";"
"nop;"
//HOOK sendto
".section h5; .set h5,0x488D80;"
"jmp "QU(_sendto)";"
"nop;"
"nop;"
".section h6; .set h6,0x8984B0;"
"jmp "QU(SessionEndGame)";"
"nop;"
"nop;"
"nop;"
"nop;"
//HOOK SetPaused
".section h7; .set h7,0x8BC100;"
"cmp dword ptr [0x011FD23F], 0x1;"
"jne run_input_check;"
"xor eax, eax;"
"ret;"
"run_input_check:;"
"push ebp;"
"mov ebp,esp;"
"and esp,0xFFFFFFF8;"
//"mov eax,dword ptr [0x0];"
"push 0xFFFFFFFF;"
"push 0xB8B0A0;"
"push eax;"
//"mov dword ptr [0x0],esp;"
"sub esp,0x50;"
"push ebx;"
"push esi;"
"mov esi,dword ptr [0x10C5A74];"
"push edi;"
"mov edi,ecx;"
"mov eax,dword ptr [edi];"
"push eax;"
"call 0x90C590;"
"add esp,0x4;"
"cmp eax,0x2;"
"je L0xABEL_0x8BC14B;"
"push eax;"
"push 0x2;"
"push esi;"
"push 0xE0A220;"
"push edi;"
"call 0x90C1D0;"
"add esp,0x14;"
"L0xABEL_0x8BC14B:;"
"lea ecx,dword ptr [esp+0x28];"
"push ecx;"
"mov ebx,0x1;"
"lea ecx,dword ptr [esp+0x34];"
"mov dword ptr [esp+0x2C],edi;"
"mov dword ptr [esp+0x30],ebx;"
"call 0x908A70;"
"mov dword ptr [esp+0x64],0x0;"
"lea esi,dword ptr [esp+0x20];"
"mov dword ptr [esp+0x20],edi;"
"mov dword ptr [esp+0x24],0x2;"
"call 0x415560;"
"lea ecx,dword ptr [esp+0x30];"
"mov byte ptr [esp+0x13],al;"
"call 0x907310;"
"test al,al;"
"je L0xABEL_0x8BC256;"
"lea ecx,dword ptr [esp+0x30];"
"call 0x907F50;"
"cmp eax,ebx;"
"mov dword ptr [esp+0x14],eax;"
"jl L0xABEL_0x8BC256;"
"lea ecx,dword ptr [ecx];"
"L0xABEL_0x8BC1B0:;"
"push ebx;"
"lea edx,dword ptr [esp+0x48];"
"push edx;"
"lea ecx,dword ptr [esp+0x38];"
"call 0x9091E0;"
"mov byte ptr [esp+0x64],0x1;"
"call 0x822B80;"
"lea ecx,dword ptr [esp+0x44];"
"mov esi,eax;"
"mov byte ptr [esp+0x64],0x0;"
"call 0x9075D0;"
"test esi,esi;"
"je L0xABEL_0x8BC249;"
"mov eax,dword ptr [esi+0x148];"
"mov edx,dword ptr [eax+0x28];"
"lea ecx,dword ptr [esi+0x148];"
"call edx;"
"test al,al;"
"jne L0xABEL_0x8BC249;"
"cmp byte ptr [esp+0x13],0x0;"
"mov ecx,dword ptr [0x10C4F50];"
"push ecx;"
"mov dword ptr [esp+0x1C],esp;"
"mov eax,esp;"
"push ecx;"
"mov dword ptr [esp+0x20],esp;"
"je L0xABEL_0x8BC22B;"
"mov dword ptr [eax],0xE0120C;"
"mov eax,esp;"
"mov dword ptr [eax],0xE2B32C;"
"mov esi,dword ptr [esi+0x44];"
"mov eax,dword ptr [ecx];"
"mov eax,dword ptr [eax+0x60];"
"push esi;"
"lea edx,dword ptr [esp+0x28];"
"push edx;"
"call eax;"
"jmp L0xABEL_0x8BC249;"
"L0xABEL_0x8BC22B:;"
"mov dword ptr [eax],0xE01204;"
"mov eax,esp;"
"mov dword ptr [eax],0xE2B32C;"
"mov esi,dword ptr [esi+0x44];"
"mov edx,dword ptr [ecx];"
"mov edx,dword ptr [edx+0x60];"
"push esi;"
"lea eax,dword ptr [esp+0x2C];"
"push eax;"
"call edx;"
"L0xABEL_0x8BC249:;"
"add ebx,0x1;"
"cmp ebx,dword ptr [esp+0x14];"
"jle L0xABEL_0x8BC1B0;"
"L0xABEL_0x8BC256:;"
"lea ecx,dword ptr [esp+0x30];"
"mov dword ptr [esp+0x64],0xFFFFFFFF;"
"call 0x9075D0;"
"mov ecx,dword ptr [esp+0x5C];"
"pop edi;"
"pop esi;"
"xor eax,eax;"
//"mov dword ptr [0x0],ecx;"
"pop ebx;"
"mov esp,ebp;"
"pop ebp;"
"ret;"
//HOOK SimCallback
".section h8; .set h8,0x8BA770;"
"cmp dword ptr [0x011FD23F], 0x1;"
"jne run_input_check2;"
"xor eax, eax;"
"ret;"
"run_input_check2:;"
"push ebp;"
"mov ebp,esp;"
"and esp,0xFFFFFFF8;"
//"mov eax,dword ptr [0x0];"
"push 0xFFFFFFFF;"
"push 0xBA28C8;"
"push eax;"
//"mov dword ptr [0x0],esp;"
"sub esp,0x88;"
"push ebx;"
"push esi;"
"mov esi,ecx;"
"mov eax,dword ptr [esi];"
"push edi;"
"mov edi,dword ptr [0x10C5954];"
"push eax;"
"call 0x90C590;"
"add esp,0x4;"
"cmp eax,0x1;"
"jl L0xABEL_0x8BA7B1;"
"cmp eax,0x2;"
"jle L0xABEL_0x8BA7C5;"
"L0xABEL_0x8BA7B1:;"
"push eax;"
"push 0x2;"
"push 0x1;"
"push edi;"
"push 0xE0A270;"
"push esi;"
"call 0x90C1D0;"
"add esp,0x18;"
"L0xABEL_0x8BA7C5:;"
"mov ecx,dword ptr [esi];"
"push 0x2;"
"push ecx;"
"call 0x90C5A0;"
"mov edx,dword ptr [esi];"
"push 0xE4C7A4;"
"push edx;"
"call 0x90CDF0;"
"mov eax,dword ptr [esi];"
"push 0x1;"
"push eax;"
"call 0x90D000;"
"mov ecx,dword ptr [esi];"
"push ecx;"
"call 0x90C590;"
"add esp,0x1C;"
"mov dword ptr [esp+0x1C],esi;"
"mov dword ptr [esp+0x20],eax;"
"mov edx,dword ptr [esi];"
"push eax;"
"push edx;"
"call 0x90CA90;"
"mov edi,eax;"
"xor ebx,ebx;"
"add esp,0x8;"
"cmp edi,ebx;"
"jne L0xABEL_0x8BA81B;"
"push 0xE00AD0;"
"lea ecx,dword ptr [esp+0x20];"
"call 0x4154B0;"
"L0xABEL_0x8BA81B:;"
"mov eax,edi;"
"mov dword ptr [esp+0x64],0xF;"
"mov dword ptr [esp+0x60],ebx;"
"mov byte ptr [esp+0x50],bl;"
"lea edx,dword ptr [eax+0x1];"
"L0xABEL_0x8BA830:;"
"mov cl,byte ptr [eax];"
"add eax,0x1;"
"test cl,cl;"
"jne L0xABEL_0x8BA830;"
"sub eax,edx;"
"push eax;"
"push edi;"
"lea ecx,dword ptr [esp+0x54];"
"call 0x4059E0;"
"mov dword ptr [esp+0x9C],ebx;"
"mov eax,dword ptr [esi];"
"push 0xE4C7AC;"
"push eax;"
"call 0x90CDF0;"
"mov ecx,dword ptr [esi];"
"push 0x1;"
"push ecx;"
"call 0x90D000;"
"mov edx,dword ptr [esi];"
"push edx;"
"call 0x90C590;"
"mov dword ptr [esp+0x2C],eax;"
"add esp,0x14;"
"lea eax,dword ptr [esp+0x14];"
"push eax;"
"lea ecx,dword ptr [esp+0x3C];"
"mov dword ptr [esp+0x18],esi;"
"call 0x908A70;"
"lea ecx,dword ptr [esp+0x88];"
"mov edx,ecx;"
"lea eax,dword ptr [esp+0x90];"
"mov dword ptr [esp+0x24],esi;"
"mov dword ptr [esp+0x28],0x2;"
"mov dword ptr [esp+0x70],ebx;"
"mov dword ptr [esp+0x78],ecx;"
"mov dword ptr [esp+0x7C],edx;"
"mov dword ptr [esp+0x80],eax;"
"mov dword ptr [esp+0x84],ecx;"
"lea esi,dword ptr [esp+0x24];"
"mov byte ptr [esp+0x9C],0x2;"
"call 0x415560;"
"test al,al;"
"je L0xABEL_0x8BA945;"
"mov ebx,dword ptr [0x10A6470];"
"mov eax,dword ptr [ebx+0x4A4];"
"mov eax,dword ptr [eax];"
"add ebx,0x4A0;"
"push eax;"
"lea edi,dword ptr [esp+0x14];"
"mov esi,ebx;"
"call 0x66A330;"
"mov eax,dword ptr [eax];"
"cmp eax,dword ptr [ebx+0x4];"
"mov dword ptr [esp+0x14],ebx;"
"mov dword ptr [esp+0x18],eax;"
"je L0xABEL_0x8BA945;"
"nop;"
"L0xABEL_0x8BA900:;"
"mov eax,dword ptr [eax+0x10];"
"test eax,eax;"
"je L0xABEL_0x8BA90C;"
"add eax,0xFFFFFFF8;"
"jmp L0xABEL_0x8BA90E;"
"L0xABEL_0x8BA90C:;"
"xor eax,eax;"
"L0xABEL_0x8BA90E:;"
"mov esi,dword ptr [eax+0x44];"
"lea edx,dword ptr [esp+0x2C];"
"push edx;"
"lea edi,dword ptr [esp+0x74];"
"call 0x4036A0;"
"lea edx,dword ptr [esp+0x18];"
"call 0x66ADD0;"
"mov eax,dword ptr [esp+0x18];"
"mov esi,dword ptr [esp+0x14];"
"push eax;"
"lea edi,dword ptr [esp+0x14];"
"call 0x66A330;"
"mov eax,dword ptr [eax];"
"cmp eax,dword ptr [ebx+0x4];"
"mov dword ptr [esp+0x18],eax;"
"jne L0xABEL_0x8BA900;"
"L0xABEL_0x8BA945:;"
"mov ecx,dword ptr [0x10C4F50];"
"lea edx,dword ptr [esp+0x68];"
"push edx;"
"lea eax,dword ptr [esp+0x3C];"
"push eax;"
"mov eax,dword ptr [esp+0x58];"
"push ecx;"
"mov esi,0x10;"
"cmp dword ptr [esp+0x70],esi;"
"mov dword ptr [esp+0x1C],esp;"
"mov edx,esp;"
"jae L0xABEL_0x8BA96F;"
"lea eax,dword ptr [esp+0x5C];"
"L0xABEL_0x8BA96F:;"
"mov dword ptr [edx],eax;"
"mov edx,dword ptr [ecx];"
"mov edx,dword ptr [edx+0x88];"
"lea eax,dword ptr [esp+0x1C];"
"push eax;"
"call edx;"
"mov eax,dword ptr [esp+0x78];"
"cmp eax,dword ptr [esp+0x84];"
"je L0xABEL_0x8BA9AA;"
"push eax;"
"call 0xA82542;"
"mov eax,dword ptr [esp+0x88];"
"mov dword ptr [esp+0x7C],eax;"
"mov ecx,dword ptr [eax];"
"add esp,0x4;"
"mov dword ptr [esp+0x80],ecx;"
"L0xABEL_0x8BA9AA:;"
"lea ecx,dword ptr [esp+0x38];"
"mov dword ptr [esp+0x7C],eax;"
"mov byte ptr [esp+0x9C],0x0;"
"call 0x9075D0;"
"cmp dword ptr [esp+0x64],esi;"
"jb L0xABEL_0x8BA9D2;"
"mov edx,dword ptr [esp+0x50];"
"push edx;"
"call 0x957A60;"
"add esp,0x4;"
"L0xABEL_0x8BA9D2:;"
"mov ecx,dword ptr [esp+0x94];"
"pop edi;"
"pop esi;"
"xor eax,eax;"
//"mov dword ptr [0x0],ecx;"
"pop ebx;"
"mov esp,ebp;"
"pop ebp;"
"ret;"
".section h9; .set h9,0x73D8C0;"
"jmp "QU(sim_dispatch)";"
"nop;"
".section h10; .set h10,0x53F010;"
"jmp "QU(Update_Pipeline_Stream)";"
"nop;"
//HOOK user input
".section h11; .set h11,0x8704B0;"
"jmp "QU(MOHO_USER_INPUT)";"
"nop;"
);
|
740086d874d4ed734020203e788f2ec65ba0eba9 | a7de84b76e5bd1adf6689fc85010966680719cf8 | /BusRoute.h | 81d14f9a617a53f3e7b23364e85d059db1202b4a | [] | no_license | konrad-kalinowski/BusArrival | ac84ded8b826db38f1a56bf264554d987d028a32 | 493728e23ad0ce9fbacc2a213c07bae6252f5412 | refs/heads/master | 2021-09-01T22:19:16.725457 | 2017-12-28T21:56:55 | 2017-12-28T21:56:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | h | BusRoute.h | #ifndef BUSROUTE_H
#define BUSROUTE_H
#include <list>
#include "BusStop.h"
#include "RouteSegment.h"
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
using namespace std;
class BusRoute {
public:
BusRoute(const string& name, const list<RouteSegment>& r, list<ptime> departureTimeMinutes);
virtual ~BusRoute();
void printRoute(BusStop& b);
string getName() const;
BusStop getDirection();
vector<BusStop> getBusStops();
list<ptime> getDepartureTime(BusStop& stop);
bool operator< (const BusRoute& other) const;
bool contains(vector<BusStop> busStops, BusStop stop);
private:
list<RouteSegment> route;
list <ptime> departureTimesFromOrigin;
string name;
int distanceInMinutes(BusStop from, BusStop to);
};
#endif /* BUSROUTE_H */
|
f188f146aa451a519a25b99f874df936eb208d0c | 6fc66dfe9c818e0295df74e11d132cdc400243ca | /lib/bsp/device/dvp.cpp | 238e7c79649a311f3883f8310be9d9681759a2dc | [
"Apache-2.0"
] | permissive | kendryte/kendryte-freertos-sdk | 600d8acc5900f532bf44823ad758e602dbac8d38 | b9dd7678f4c6549b0458a8ba9d80198691a2504d | refs/heads/develop | 2022-07-15T22:45:47.458472 | 2021-02-01T02:23:27 | 2021-02-01T02:23:27 | 147,630,962 | 206 | 75 | Apache-2.0 | 2020-09-26T14:44:26 | 2018-09-06T06:56:36 | C | UTF-8 | C++ | false | false | 7,215 | cpp | dvp.cpp | /* Copyright 2018 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <FreeRTOS.h>
#include <dvp.h>
#include <fpioa.h>
#include <hal.h>
#include <kernel/driver_impl.hpp>
#include <plic.h>
#include <semphr.h>
#include <stdio.h>
#include <sysctl.h>
#include <utility.h>
#include <iomem.h>
using namespace sys;
class k_dvp_driver : public dvp_driver, public static_object, public exclusive_object_access
{
public:
k_dvp_driver(uintptr_t base_addr, sysctl_clock_t clock)
: dvp_(*reinterpret_cast<volatile dvp_t *>(base_addr)), clock_(clock)
{
}
virtual void install() override
{
sysctl_clock_disable(clock_);
pic_set_irq_handler(IRQN_DVP_INTERRUPT, dvp_frame_event_isr, this);
pic_set_irq_priority(IRQN_DVP_INTERRUPT, 1);
}
virtual void on_first_open() override
{
sysctl_clock_enable(clock_);
}
virtual void on_last_close() override
{
sysctl_clock_disable(clock_);
}
virtual uint32_t get_output_num() override
{
return 2;
}
virtual void config(uint32_t width, uint32_t height, bool auto_enable) override
{
configASSERT(width % 8 == 0 && width && height);
uint32_t dvp_cfg = dvp_.dvp_cfg;
if (width / 8 % 4 == 0)
{
dvp_cfg |= DVP_CFG_BURST_SIZE_4BEATS;
set_bit_mask(&dvp_cfg, DVP_AXI_GM_MLEN_MASK | DVP_CFG_HREF_BURST_NUM_MASK, DVP_AXI_GM_MLEN_4BYTE | DVP_CFG_HREF_BURST_NUM(width / 8 / 4));
}
else
{
dvp_cfg &= (~DVP_CFG_BURST_SIZE_4BEATS);
set_bit_mask(&dvp_cfg, DVP_AXI_GM_MLEN_MASK, DVP_AXI_GM_MLEN_1BYTE | DVP_CFG_HREF_BURST_NUM(width / 8));
}
set_bit_mask(&dvp_cfg, DVP_CFG_LINE_NUM_MASK, DVP_CFG_LINE_NUM(height));
if (auto_enable)
dvp_cfg |= DVP_CFG_AUTO_ENABLE;
else
dvp_cfg &= ~DVP_CFG_AUTO_ENABLE;
dvp_.dvp_cfg = dvp_cfg;
dvp_.cmos_cfg |= DVP_CMOS_CLK_DIV(xclk_devide_) | DVP_CMOS_CLK_ENABLE;
width_ = width;
height_ = height;
}
virtual void enable_frame() override
{
dvp_.sts = DVP_STS_DVP_EN | DVP_STS_DVP_EN_WE;
}
virtual void set_signal(dvp_signal_type_t type, bool value) override
{
switch (type)
{
case DVP_SIG_POWER_DOWN:
if (value)
dvp_.cmos_cfg |= DVP_CMOS_POWER_DOWN;
else
dvp_.cmos_cfg &= ~DVP_CMOS_POWER_DOWN;
break;
case DVP_SIG_RESET:
if (value)
dvp_.cmos_cfg |= DVP_CMOS_RESET;
else
dvp_.cmos_cfg &= ~DVP_CMOS_RESET;
break;
default:
configASSERT(!"Invalid signal type.");
break;
}
}
virtual void set_output_enable(uint32_t index, bool enable) override
{
configASSERT(index < 2);
if (index == 0)
{
if (enable)
dvp_.dvp_cfg |= DVP_CFG_AI_OUTPUT_ENABLE;
else
dvp_.dvp_cfg &= ~DVP_CFG_AI_OUTPUT_ENABLE;
}
else
{
if (enable)
dvp_.dvp_cfg |= DVP_CFG_DISPLAY_OUTPUT_ENABLE;
else
dvp_.dvp_cfg &= ~DVP_CFG_DISPLAY_OUTPUT_ENABLE;
}
}
virtual void set_output_attributes(uint32_t index, video_format_t format, void *output_buffer) override
{
configASSERT(index < 2);
#if FIX_CACHE
configASSERT(!is_memory_cache((uintptr_t)output_buffer));
#endif
if (index == 0)
{
configASSERT(format == VIDEO_FMT_RGB24_PLANAR);
uintptr_t buffer_addr = (uintptr_t)output_buffer;
size_t planar_size = width_ * height_;
dvp_.r_addr = buffer_addr;
dvp_.g_addr = buffer_addr + planar_size;
dvp_.b_addr = buffer_addr + planar_size * 2;
}
else
{
configASSERT(format == VIDEO_FMT_RGB565);
dvp_.rgb_addr = (uintptr_t)output_buffer;
}
}
virtual void set_frame_event_enable(dvp_frame_event_t event, bool enable) override
{
switch (event)
{
case VIDEO_FE_BEGIN:
if (enable)
{
dvp_.sts |= DVP_STS_FRAME_START | DVP_STS_FRAME_START_WE;
dvp_.dvp_cfg |= DVP_CFG_START_INT_ENABLE;
}
else
{
dvp_.dvp_cfg &= ~DVP_CFG_START_INT_ENABLE;
}
break;
case VIDEO_FE_END:
if (enable)
{
dvp_.sts |= DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE;
dvp_.dvp_cfg |= DVP_CFG_FINISH_INT_ENABLE;
}
else
{
dvp_.dvp_cfg &= ~DVP_CFG_FINISH_INT_ENABLE;
}
break;
default:
configASSERT(!"Invalid event.");
break;
}
pic_set_irq_enable(IRQN_DVP_INTERRUPT, 1);
}
virtual void set_on_frame_event(dvp_on_frame_event_t callback, void *userdata) override
{
frame_event_callback_data_ = userdata;
frame_event_callback_ = callback;
}
virtual double xclk_set_clock_rate(double clock_rate) override
{
uint32_t apb1_pclk = sysctl_clock_get_freq(SYSCTL_CLOCK_APB1);
int16_t xclk_divide = apb1_pclk / clock_rate / 2 - 1;
configASSERT((xclk_divide >= 0) && (xclk_divide < (1 << 8)));
xclk_devide_ = xclk_divide;
return apb1_pclk / (xclk_divide + 1);
}
private:
static void dvp_frame_event_isr(void *userdata)
{
auto &driver = *reinterpret_cast<k_dvp_driver *>(userdata);
if (driver.dvp_.sts & DVP_STS_FRAME_START)
{
dvp_on_frame_event_t callback;
if ((callback = driver.frame_event_callback_))
callback(VIDEO_FE_BEGIN, driver.frame_event_callback_data_);
driver.dvp_.sts |= DVP_STS_FRAME_START | DVP_STS_FRAME_START_WE;
}
if (driver.dvp_.sts & DVP_STS_FRAME_FINISH)
{
dvp_on_frame_event_t callback;
if ((callback = driver.frame_event_callback_))
callback(VIDEO_FE_END, driver.frame_event_callback_data_);
driver.dvp_.sts |= DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE;
}
}
private:
volatile dvp_t &dvp_;
sysctl_clock_t clock_;
dvp_on_frame_event_t frame_event_callback_;
void *frame_event_callback_data_;
size_t width_;
size_t height_;
uint32_t xclk_devide_;
};
static k_dvp_driver dev0_driver(DVP_BASE_ADDR, SYSCTL_CLOCK_DVP);
driver &g_dvp_driver_dvp0 = dev0_driver;
|
c1efa693f0a6e71c0bded454fd8b321d951dc927 | 63ee03dd1baa698a30d643afbf92ea72f6a10648 | /src/ArsUIMapControlState.cpp | 5eb25413ed65c0cb06c1305750e841557f1f84cb | [] | no_license | imclab/prix-ars-2013-UI | 761fc97fe9a513ecb89808abcbac84ee072bc185 | 4f17e094897470be701e7fa6a333c9392e704d3a | refs/heads/master | 2020-12-31T03:56:36.628112 | 2013-03-15T12:33:26 | 2013-03-15T12:33:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,872 | cpp | ArsUIMapControlState.cpp | //
// MapControlState.cpp
// arsUI
//
// Created by Circuit Lab. Mac mini on 3/12/13.
//
//
#include "ArsUIMapControlState.h"
//--------------------------------------------------------------
ArsUIMapControlState::ArsUIMapControlState()
{
init();
}
//--------------------------------------------------------------
ArsUIMapControlState::~ArsUIMapControlState()
{
}
//--------------------------------------------------------------
void ArsUIMapControlState::init()
{
//setupGUI();
}
//--------------------------------------------------------------
void ArsUIMapControlState::stateEnter()
{
bShowStatus = true;
fujiPoint.set(964, 600);
json.clear();
if (json.open(ofToDataPath("cameras.json"))) {
for (int i = 0; i < json["cameras"].size(); ++i) {
ofxJSONElement camera = json["cameras"][i];
if (true == camera["operable"].asBool()) {
operableCameras.push_back(createOperableCamera(camera, i));
} else {
inoperableCameras.push_back(createCamera(camera, i));
}
}
}
cam1Position = ofPoint(operableCameras[0].getPosition().x, operableCameras[0].getPosition().y);
cam2Position = ofPoint(operableCameras[1].getPosition().x, operableCameras[1].getPosition().y);
eyes[0] = -1;
eyes[1] = -1;
selectedEye = EYE_LEFT;
fujiMap.loadImage("map.png");
ofAddListener(getSharedData().tuioClient.cursorAdded, this, &ArsUIMapControlState::tuioAdded);
ofAddListener(getSharedData().tuioClient.cursorRemoved, this, &ArsUIMapControlState::tuioRemoved);
ofAddListener(getSharedData().tuioClient.cursorUpdated, this, &ArsUIMapControlState::tuioUpdated);
ofAddListener(getSharedData().oscReceiverFromServer.onMessageReceived, this, &ArsUIMapControlState::onOscMessageReceived);
ofxOscMessage msg;
msg.setAddress("/gianteyes/hello");
msg.addIntArg(getSharedData().incomingPort);
getSharedData().oscSenderToServer.sendMessage(msg);
sendViewpointToServer(operableCameras[0]);
sendViewpointToServer(operableCameras[1]);
for (int i = 0; i < operableCameras.size(); ++i) {
sendViewpointToServer(operableCameras[i]);
sendImageUrlToDisplay(operableCameras[i].getEyeDirection(), "http://pds.exblog.jp/pds/1/200802/18/73/d0116173_14571347.jpg");
}
}
//--------------------------------------------------------------
void ArsUIMapControlState::stateExit()
{
inoperableCameras.clear();
operableCameras.clear();
fujiMap.clear();
ofRemoveListener(getSharedData().tuioClient.cursorAdded, this, &ArsUIMapControlState::tuioAdded);
ofRemoveListener(getSharedData().tuioClient.cursorRemoved, this, &ArsUIMapControlState::tuioRemoved);
ofRemoveListener(getSharedData().tuioClient.cursorUpdated, this, &ArsUIMapControlState::tuioUpdated);
ofRemoveListener(getSharedData().oscReceiverFromServer.onMessageReceived, this, &ArsUIMapControlState::onOscMessageReceived);
ofRemoveListener(gui->newGUIEvent, this, &ArsUIMapControlState::guiEvent);
}
//--------------------------------------------------------------
void ArsUIMapControlState::update()
{
getSharedData().tuioClient.getMessage();
for (int i = 0; i < getSharedData().tappedPoints.size(); ++i) {
getSharedData().tappedPoints[i].update();
if (false == getSharedData().tappedPoints[i].alive()) {
vector<ArsUITappedPoint>::iterator it = getSharedData().tappedPoints.begin();
getSharedData().tappedPoints.erase(it + i);
}
}
for (int i = 0; i < inoperableCameras.size(); ++i) {
inoperableCameras[i].update();
}
operableCameras[0].setPosition(cam1Position);
operableCameras[1].setPosition(cam2Position);
operableCameras[0].update();
operableCameras[1].update();
}
//--------------------------------------------------------------
void ArsUIMapControlState::draw()
{
// tuioClient.drawCursors();
//drawUpdated();
ofSetColor(255, 255, 255);
fujiMap.draw(-350, -10, 1920 * 1.4, 907 * 1.4);
// ofCircle(fujiPoint, 1);
ofSetColor(255, 255, 255, 255);
for (int i = 0; i < getSharedData().tappedPoints.size(); ++i){
getSharedData().tappedPoints[i].draw();
}
for (int i = 0; i<inoperableCameras.size(); ++i) {
inoperableCameras[i].draw();
}
for (int i = 0; i < operableCameras.size(); ++i) {
operableCameras[i].draw();
}
ofPushStyle();
ofSetColor(255, 0, 0);
if (bShowStatus) {
drawCamStatuses(operableCameras[0]);
drawCamStatuses(operableCameras[1]);
} else {
if (isCam1Draggable) {
drawCamStatuses(operableCameras[0]);
}
if (isCam2Draggable) {
drawCamStatuses(operableCameras[1]);
}
}
double cam1deg = operableCameras[0].degreesAgainstFuji();
double cam2deg = operableCameras[1].degreesAgainstFuji();
if (0 <= cam1deg && 0 <= cam2deg) {
if (cam1deg < cam2deg) {
operableCameras[0].setEyeDirection(EYE_RIGHT);
operableCameras[1].setEyeDirection(EYE_LEFT);
} else {
operableCameras[0].setEyeDirection(EYE_LEFT);
operableCameras[1].setEyeDirection(EYE_RIGHT);
}
} else if (0 <= cam1deg && 0 > cam2deg) {
operableCameras[0].setEyeDirection(EYE_RIGHT);
operableCameras[1].setEyeDirection(EYE_LEFT);
} else if (0 > cam1deg && 0 > cam2deg) {
if (cam1deg < cam2deg) {
operableCameras[0].setEyeDirection(EYE_RIGHT);
operableCameras[1].setEyeDirection(EYE_LEFT);
} else {
operableCameras[0].setEyeDirection(EYE_LEFT);
operableCameras[1].setEyeDirection(EYE_RIGHT);
}
} else if (0 > cam1deg && 0 <= cam2deg) {
operableCameras[0].setEyeDirection(EYE_LEFT);
operableCameras[1].setEyeDirection(EYE_RIGHT);
}
ofPopStyle();
}
//--------------------------------------------------------------
string ArsUIMapControlState::getName()
{
return "map";
}
//--------------------------------------------------------------
void ArsUIMapControlState::keyPressed(int key)
{
}
//--------------------------------------------------------------
void ArsUIMapControlState::keyReleased(int key)
{
}
//--------------------------------------------------------------
void ArsUIMapControlState::mousePressed(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ArsUIMapControlState::mouseDragged(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ArsUIMapControlState::setupGUI()
{
gui = new ofxUICanvas(0, 0, GUI_CANVAS_WIDTH, GUI_CANVAS_HEIGHT);
gui->setColorBack(ofColor(255, 255, 255, 127));
gui->setColorFill(ofColor(0));
gui->addWidgetDown(new ofxUILabel("CONTROL PANEL", OFX_UI_FONT_LARGE));
gui->addSpacer();
gui->addFPSSlider("FPS SLIDER", GUI_CANVAS_WIDTH - 10, 18, 60);
gui->addSpacer();
gui->addLabelButton("SHOOT", false, true);
gui->autoSizeToFitWidgets();
ofAddListener(gui->newGUIEvent, this, &ArsUIMapControlState::guiEvent);
}
//--------------------------------------------------------------
ArsUICamera ArsUIMapControlState::createCamera(ofxJSONElement json, int bid)
{
return ArsUICamera(json["latitude"].asDouble(), json["longitude"].asDouble(), json["udid"].asString(), json["angle"].asInt(), json["compass"].asInt(), bid, fujiPoint);
}
//--------------------------------------------------------------
ArsUIOperableCamera ArsUIMapControlState::createOperableCamera(ofxJSONElement json, int bid)
{
return ArsUIOperableCamera(json["latitude"].asDouble(), json["longitude"].asDouble(), json["udid"].asString(), json["angle"].asInt(), json["compass"].asInt(), json["battery"].asInt(), json["living"].asBool(), bid, fujiPoint);
}
//--------------------------------------------------------------
void ArsUIMapControlState::setEye(int bid)
{
int lastEye = eyes[selectedEye];
if (-1 != lastEye) {
for (int i = 0; i < inoperableCameras.size(); ++i) {
if(inoperableCameras[i].getButtonId() == lastEye){
inoperableCameras[i].setStatus(0);
}
}
for (int i = 0; i < operableCameras.size(); ++i) {
if(operableCameras[i].getButtonId() == lastEye){
operableCameras[i].setStatus(0);
}
}
}
eyes[selectedEye] = bid;
selectedEye = !selectedEye ? EYE_RIGHT : EYE_LEFT;
}
//--------------------------------------------------------------
void ArsUIMapControlState::tuioAdded(ofxTuioCursor &tuioCursor)
{
ofPoint loc = ofPoint(tuioCursor.getX() * ofGetWidth(), tuioCursor.getY() * ofGetHeight());
cout << "TUIO added, x: " << loc.x << ", y: " << loc.y << endl;
ArsUITappedPoint tappedPoint(loc.x, loc.y, tuioCursor.getFingerId());
getSharedData().tappedPoints.push_back(tappedPoint);
for (int i = 0; i < inoperableCameras.size(); ++i) {
int bid = inoperableCameras[i].hitTestPoint(loc);
if (0 <= bid && bid != eyes[0] && bid != eyes[1]) {
setEye(bid);
inoperableCameras[i].setStatus(1);
}
}
for (int i = 0; i < operableCameras.size(); ++i) {
int bid = operableCameras[i].hitTestPoint(loc);
if (0 <= bid && bid != eyes[0] && bid != eyes[1]){
setEye(bid);
operableCameras[i].setStatus(1);
}
}
ofPoint cam1Pos = operableCameras[0].getPosition();
ofPoint cam2Pos = operableCameras[1].getPosition();
float dist1 = ArsUIUtil::distance(loc, cam1Pos);
float dist2 = ArsUIUtil::distance(loc, cam2Pos);
if (dist1 < dist2 && dist1 <= 10) {
cam1TouchedStartedAt = ofGetElapsedTimeMillis();
cam1FingerId = tuioCursor.getFingerId();
cout << "CAM 1 touched, time(millis): " << cam1TouchedStartedAt << endl;
} else if (dist2 < dist1 && dist2 <= 10) {
cam2TouchedStartedAt = ofGetElapsedTimeMillis();
cam2FingerId = tuioCursor.getFingerId();
cout << "CAM 2 touched, time(millis): " << cam2TouchedStartedAt << endl;
}
// cout << "Point n" << tuioCursor.getSessionId() << " add at " << loc << endl;
}
//--------------------------------------------------------------
void ArsUIMapControlState::tuioRemoved(ofxTuioCursor &tuioCursor)
{
ofPoint loc = ofPoint(tuioCursor.getX() * ofGetWidth(), tuioCursor.getY() * ofGetHeight());
cout << "TUIO removed, id: " << tuioCursor.getFingerId() << endl;
//cout << "Point n" << tuioCursor.getSessionId() << " remove at " << loc << endl;
if (tuioCursor.getFingerId() == cam1FingerId) {
cam1TouchedStartedAt = 0;
cam1FingerId = -1;
isCam1Draggable = false;
sendViewpointToServer(operableCameras[0]);
sendImageUrlToDisplay(operableCameras[0].getEyeDirection(), "http://cache5.amanaimages.com/cen3tzG4fTr7Gtw1PoeRer/22973000320.jpg");
} else if (tuioCursor.getFingerId() == cam2FingerId) {
cam2TouchedStartedAt = 0;
cam2FingerId = -1;
isCam2Draggable = false;
sendViewpointToServer(operableCameras[1]);
sendImageUrlToDisplay(operableCameras[1].getEyeDirection(), "http://cache5.amanaimages.com/cen3tzG4fTr7Gtw1PoeRer/22973000320.jpg");
}
}
//--------------------------------------------------------------
void ArsUIMapControlState::tuioUpdated(ofxTuioCursor &tuioCursor)
{
ofPoint loc = ofPoint(tuioCursor.getX() * ofGetWidth(), tuioCursor.getY() * ofGetHeight());
// cout << "TUIO updated, id: " << tuioCursor.getFingerId() << endl;
if (0 < cam1TouchedStartedAt && 1000 <= ofGetElapsedTimeMillis() - cam1TouchedStartedAt && tuioCursor.getFingerId() == cam1FingerId) {
isCam1Draggable = true;
cam1Position = loc;
} else {
isCam1Draggable = false;
operableCameras[0].dragAngle(loc.x, loc.y);
}
if (0 < cam2TouchedStartedAt && 1000 <= ofGetElapsedTimeMillis() - cam2TouchedStartedAt && tuioCursor.getFingerId() == cam2FingerId) {
isCam2Draggable = true;
cam2Position = loc;
} else {
isCam2Draggable = false;
operableCameras[1].dragAngle(loc.x, loc.y);
}
}
//--------------------------------------------------------------
void ArsUIMapControlState::drawTuioCursors()
{
list<ofxTuioCursor*> cursorList = getSharedData().tuioClient.getTuioCursors();
if (0 < cursorList.size()) {
list<ofxTuioCursor*>::iterator tcursor;
for (tcursor = cursorList.begin(); tcursor != cursorList.end(); ++tcursor) {
ofxTuioCursor *cursor = (*tcursor);
float x = (*cursor).getX() * ofGetWidth();
float y = (*cursor).getY() * ofGetHeight();
// cout << "x" << (*cursor).getXSpeed() <<" ";
// ofSetColor(100,100, (*cursor).getFingerId() ,127);
ofSetColor(55, 55, 55, 100);
ofCircle(x, y, 5 - (*cursor).getXSpeed() * ofGetWidth() * 5 + 5 - (*cursor).getYSpeed() * ofGetWidth() * 5);
}
}
}
//--------------------------------------------------------------
void ArsUIMapControlState::drawCamStatuses(ArsUIOperableCamera cam)
{
string str = "X : " + ofToString(cam.getPosition().x) +
"\nY : " + ofToString(cam.getPosition().y) +
"\nANGLE : " + ofToString(cam.degreesAgainstFuji()) +
"\nCOMPASS: " + ofToString(cam.getCompass()) +
"\nEYE : " + ofToString(EYE_LEFT == cam.getEyeDirection() ? "LEFT" : "RIGHT");
ofDrawBitmapString(str, cam.getPosition() + ofPoint(70, -80));
}
//--------------------------------------------------------------
void ArsUIMapControlState::onOscMessageReceived(ofxOscMessage &msg)
{
json.clear();
string addr = msg.getAddress();
cout << "OSC received. address: " << addr << endl;
if ("/gianteyes/camera" == addr) {
string jsonString = msg.getArgAsString(0);
cout << "jsonString: " << jsonString << endl;
if (0 < jsonString.length()) {
if (json.parse(jsonString)) {
string udid = json["udid"].asString();
if (true == json["operable"].asBool()) {
for (int i = 0; i < operableCameras.size(); ++i) {
if (operableCameras[i].getUDID() == udid) {
operableCameras[i].setCameraStatus(json);
}
}
} else {
for (int i = 0; i < inoperableCameras.size(); ++i) {
if (inoperableCameras[i].getUDID() == udid) {
inoperableCameras[i].setCameraStatus(json);
}
}
}
}
}
} else if ("/gianteyes/photo" == addr) {
string jsonString = msg.getArgAsString(0);
if (0 < jsonString.length()) {
if (json.parse(jsonString)) {
for (int i = 0; i < operableCameras.size(); ++i) {
if (json["udid"] == operableCameras[i].getUDID()) {
sendImageUrlToDisplay(operableCameras[i].getEyeDirection(), json["url"].asString());
}
}
}
}
} else if ("/gianteyes/cameras" == addr) {
string jsonString = msg.getArgAsString(0);
cout << "jsonString: " << jsonString << endl;
if (0 < jsonString.length()) {
if (json.parse(jsonString)) {
inoperableCameras.clear();
operableCameras.clear();
for (int i = 0; i < json["cameras"].size(); ++i) {
ofxJSONElement camera = json["cameras"][i];
if (true == camera["operable"].asBool()) {
operableCameras.push_back(createOperableCamera(camera, i));
} else {
inoperableCameras.push_back(createCamera(camera, i));
}
}
}
}
}
}
//--------------------------------------------------------------
void ArsUIMapControlState::sendViewpointToServer(ArsUIOperableCamera cam)
{
ofxOscMessage msg;
msg.setAddress("/gianteyes/viewpoint");
msg.addIntArg(cam.getButtonId());
msg.addIntArg(cam.getCompass());
msg.addIntArg(cam.getAngle());
getSharedData().oscSenderToServer.sendMessage(msg);
}
//--------------------------------------------------------------
void ArsUIMapControlState::sendShootingTriggerToServer(int camId)
{
ofxOscMessage msg;
msg.setAddress("/gianteyes/take");
msg.addIntArg(camId);
getSharedData().oscSenderToServer.sendMessage(msg);
}
//--------------------------------------------------------------
void ArsUIMapControlState::sendImageUrlToDisplay(int whichEye, string url)
{
ofxOscMessage msg;
EYE_RIGHT == whichEye ? msg.setAddress("/url/right") : msg.setAddress("/url/left");
msg.addStringArg(url);
getSharedData().oscSenderToDisplay.sendMessage(msg);
}
//--------------------------------------------------------------
void ArsUIMapControlState::guiEvent(ofxUIEventArgs &e)
{
string name = e.widget->getName();
int kind = e.widget->getKind();
if(kind == OFX_UI_WIDGET_LABELBUTTON) {
ofxUILabelButton *button = (ofxUILabelButton *) e.widget;
cout << name << "\t value: " << button->getValue() << endl;
}
} |
fee5dc50a42fdd78ee3e8be648ab6db9a1c5bb34 | 1ae555d3088dc123836060371fc520bf0ff13e52 | /atcoder/abc111/c2.cpp | ea8be89a25f9edb1765af8128ffd8c5765aa3cfd | [] | no_license | knagakura/procon | a87b9a1717674aeb5ee3da0301d465e95c758fde | c6ac49dbaaa908ff13cb0d9af439efe5439ec691 | refs/heads/master | 2022-01-31T19:46:33.535685 | 2022-01-23T11:59:02 | 2022-01-23T11:59:02 | 161,764,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | c2.cpp |
//偶数番目の頻度最大と奇数番目の頻度最大
#include <bits/stdc++.h>
using namespace std;
#define rep(i,N) for(int i=0;i<int(N);++i)
#define rep1(i,N) for(int i=1;i<int(N);++i)
#define all(a) (a).begin(),(a).end() //sort(all(vi S)) sort(all(string S))
typedef long long ll;
typedef vector<int> vi;
typedef set<int> seti;
typedef vector<string> vs;
const int MOD = 1e9+7;
const int INF = 1e9;
int main() {
int N;
cin>>N;
vector<int> v(N);
rep(i,N)cin>>v[i];
vector<int> cnt0(100000),cnt1(100000);
for (int i = 0; i < N; i+=2){
cnt0[v[i]]++;
}
for (int i = 1; i < N; i+=2){
cnt1[v[i]]++;
}
int ans;
rep(i,100000){
}
cout<<ans<<endl;
} |
c7f1211a8f94591763153b65b9c6bfac01af712a | 791df5c6abb554b9e91cca853171b9a78c5e0104 | /Condition/break.cpp | 72b17b9605a7d399ea963d9beda36d41fab24f5b | [] | no_license | hudacse6/Beginner-and-Intermediate-level-Programming-Codes | 38dbd7112611e97f0fda15d196f438fd6591c731 | ec92c676efa077509bf483416b90aecc6078422a | refs/heads/master | 2021-03-02T19:45:35.381762 | 2020-03-08T22:42:53 | 2020-03-08T22:42:53 | 245,899,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | cpp | break.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
/// This loop is used to break
//int n=1;
//while( n<=100 )
for(int n=0 ; n<100 ;n++)
{
printf("%d\n",n);
//n++;
if( n>10 )
{
break;
}
}
return 0;
}
|
d503e730829bc3bc439e85264cfd2f7e8aac3144 | 53b0ba368c4a6647f772b30c111cf523a386a33d | /include/operators/bivectorOperators.hpp | 04b5e733a9a321929fd881d1f6939bf6cea897d5 | [] | no_license | L-Naej/Grassman | 0ab0b069248c88a1725c401719ecd9958ebe5490 | e2a8cb16e64574b0c33aa6cca921b6af36f2a2d2 | refs/heads/master | 2021-01-10T19:31:16.001036 | 2014-01-06T15:35:28 | 2014-01-06T15:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | hpp | bivectorOperators.hpp | #pragma once
#include "scalar.hpp"
#include "vector.hpp"
#include "bivector.hpp"
#include "trivector.hpp"
#include "quadvector.hpp"
namespace gca
{
class GCA_antibivector;
class GCA_antitrivector;
class GCA_antiquadvector;
GCA_quadvector operator^(const GCA_bivector& a, const GCA_bivector& b);
GCA_quadvector operator^(const GCA_bivector& a, const GCA_antibivector& b);
GCA_trivector operator^(const GCA_bivector& a, const GCA_antitrivector& b);
GCA_bivector operator^(const GCA_bivector& a, const GCA_antiquadvector& b);
GCA_antibivector operator~(const GCA_bivector& bivec);
} //namespace gca
|
5bf8c12477d61164f1e4d79ee24ce31b5ae528ef | 830e850a98e3d9140ad67da84d612e2738ed2b88 | /raytracer/include/materials/Matte.h | 82cfd367455ccdfa0a34e370a9a2786b60af298b | [
"MIT"
] | permissive | phaser/raytracer | b6047104be6b1a58eaad47bfe58878934d15c731 | 2f1506b03b0240ee89a06c8bb3429e5392c5a48e | refs/heads/master | 2021-05-04T11:33:02.565654 | 2016-09-11T16:52:48 | 2016-09-11T16:52:48 | 36,222,057 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 309 | h | Matte.h | #pragma once
#include <materials/Material.h>
class Lambertian;
class Matte : public Material
{
public:
Matte();
RGBColor shade(HitRec& hr);
Matte& SetAmbient(Lambertian* ambient);
Matte& SetDiffuse(Lambertian* diffuse);
private:
Lambertian* ambient_brdf;
Lambertian* diffuse_brdf;
}; |
77282f0854a4599d985d231e0d13c6e64f14bc89 | 5c6a0a26dcc7e784876f06375c52ddbb59ec7608 | /final-project-laurenho025/src/tuner.cpp | 42547a5a071077781690d344a35d55f8dd3090de | [] | no_license | laurenho025/face-tuner | 6f6f402df10f3d9b6eae946dc86590ee01d735ce | 5b3ee3caa46964adc544cce8a051527e049f530a | refs/heads/master | 2020-05-30T09:59:48.613113 | 2019-05-02T03:44:06 | 2019-05-02T03:44:06 | 189,662,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,598 | cpp | tuner.cpp | #include "tuner.hpp"
#include <vector>
#include <string>
#include <math.h>
using std::vector;
using std::find;
using std::pair;
float Tuner::GetDifference() {
return difference;
}
float Tuner::FindClosestPitch(string selectednote, float measuredmidi) {
// A valid MIDI note number can only be between 21-127
if (selectednote == "" || measuredmidi < 21 || measuredmidi > 127) {
difference = 0;
return 0;
}
// Cycle through the possible pitches for the selected note and find the smallest difference
float selectedmidi = kNoteToMidi.find(selectednote[0])->second;
difference = abs(selectedmidi - measuredmidi);
float targetmidi = selectedmidi;
for (double i = selectedmidi; i <= 127; i += 12) {
if (abs(i - measuredmidi) < difference) {
difference = abs(i - measuredmidi);
targetmidi = i;
}
}
return targetmidi;
}
map<string, float> Tuner::ClassifyDifference() {
map<string, float> emotionclassifications;
// Classify the difference as a corresponding facial emotion,
// and populate a map of emotions corresponding to their initial "weights"
if (difference >= 4 && difference <= 6) {
emotionclassifications.insert(pair<string, float>("fury", 1));
emotionclassifications.insert(pair<string, float>("rage", 1));
} else if (difference >= 2 && difference < 4) {
emotionclassifications.insert(pair<string, float>("cry", 1));
emotionclassifications.insert(pair<string, float>("sad", 1));
} else if (difference >= 0 && difference < 2) {
emotionclassifications.insert(pair<string, float>("grin", 0.5));
emotionclassifications.insert(pair<string, float>("laugh", 0.5));
emotionclassifications.insert(pair<string, float>("smile", 0.5));
}
return emotionclassifications;
}
map<string, float> Tuner::CalculateEmotionWeight(map<string, float> emotionclassifications) {
// If the difference is negligible, do not alter the initial emotion weight
if (difference <= 0.1) {
return emotionclassifications;
}
// Weight each emotion according to the size of the current MIDI difference
map<string, float> emotionswithweight;
map<string, float>::iterator it;
float standardized_diff = fmod(difference, 2.0);
for (it = emotionclassifications.begin(); it != emotionclassifications.end(); it++) {
it->second = (1 - (standardized_diff / 2)) * it->second;
emotionswithweight.insert(pair<string, float>(it->first, it->second));
}
return emotionswithweight;
}
|
3c16b48c2524aa219ae7e7933ca503ba3e7b4016 | 71f88b70aec1c1b3224e18f0c31abf64fb1332bf | /codeFiles/ChuangkouDlg.cpp | 544a424784e3f00427d1e0410dacae78ba8da039 | [] | no_license | llllllfff233/VCPictureProcessing | 6efc53de8b6b9af2f89f8cb609213b6e1a379739 | d6990ab023aebe4b17555972a16690208f08dcb2 | refs/heads/master | 2021-05-21T00:44:27.666030 | 2017-11-19T14:04:01 | 2017-11-19T14:04:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | cpp | ChuangkouDlg.cpp | // ChuangkouDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MfcPictureProcessing.h"
#include "ChuangkouDlg.h"
#include "afxdialogex.h"
// ChuangkouDlg dialog
IMPLEMENT_DYNAMIC(ChuangkouDlg, CDialogEx)
ChuangkouDlg::ChuangkouDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(ChuangkouDlg::IDD, pParent)
, low(0)
, high(0)
{
ifok=false;
}
ChuangkouDlg::~ChuangkouDlg()
{
}
void ChuangkouDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, low);
DDX_Text(pDX, IDC_EDIT2, high);
}
BEGIN_MESSAGE_MAP(ChuangkouDlg, CDialogEx)
ON_BN_CLICKED(IDOK, &ChuangkouDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// ChuangkouDlg message handlers
int ChuangkouDlg::GetLow()
{
return low;
}
int ChuangkouDlg::GetHigh()
{
return high;
}
void ChuangkouDlg::OnBnClickedOk()
{
UpdateData(true);
UpdateData(false);
ifok=true;
CDialogEx::OnOK();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.