blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95034cf7c2cd8bbaf6b1c3ffbd93a7bfcb64b508 | 30626e6504ddf7ff9de133700a6cebe86bcf331b | /sig/src/sigogl/ws_run.cpp | 5e765b2cb378fd461aec047ec77d0e03dfdc43c1 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | kelvin331/Robot-Simulation | 173a033b133316768e2cffd6c293a8438cc9b78b | 3bb2d82a3081b5250b3a675ea9ed9b9fcbe0e9ec | refs/heads/master | 2020-04-27T14:59:34.565337 | 2019-03-07T22:55:49 | 2019-03-07T22:55:49 | 174,427,803 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,256 | cpp | /*=======================================================================
Copyright (c) 2018 Marcelo Kallmann.
This software is distributed under the Apache License, Version 2.0.
All copies must contain the full copyright notice licence.txt located
at the base folder of the distribution.
=======================================================================*/
# include <stdlib.h>
# include <sig/gs_string.h>
# include <sigogl/ws_run.h>
# include <sigogl/ws_window.h>
# include <sigogl/ws_osinterface.h>
//===================================== xx =================================================
struct SwTimerData
{ double interval;
double lasttime;
WsWindow* window;
void (*callback) (void*);
union { void* udata; int evid; };
};
static GsArray<SwTimerData> Timers;
static int NumTimers=0;
static double Time0=0;
static double TimeCur=0;
void ws_check_timers ()
{
TimeCur = gs_time()-Time0;
for ( int i=0; i<NumTimers; i++ )
{ if ( TimeCur-Timers[i].lasttime > Timers[i].interval )
{ if ( Timers[i].callback )
{ Timers[i].callback ( Timers[i].udata ); }
else
{ WsWindow* win = Timers[i].window;
if ( !win->minimized() )
win->timer ( Timers[i].evid );
}
Timers[i].lasttime = TimeCur;
}
}
}
static void add_timer ( double interval, WsWindow* win, void(*cb)(void*) )
{
if ( Time0==0 ) Time0 = gs_time();
SwTimerData& t = Timers.push();
t.interval = interval;
t.lasttime = TimeCur;
t.window = win;
t.callback = cb;
NumTimers++;
}
void ws_add_timer ( double interval, void(*cb)(void*), void* udata )
{
add_timer ( interval, 0, cb );
Timers.top().udata = udata;
}
void ws_add_timer ( double interval, WsWindow* win, int ev )
{
add_timer ( interval, win, 0 );
Timers.top().evid = ev;
}
void ws_remove_timer ( void(*cb)(void*) )
{
for ( int i=0; i<Timers.size(); i++ )
{ if ( Timers[i].callback == cb )
{ Timers[i] = Timers.pop();
NumTimers--;
return;
}
}
}
void ws_remove_timer ( WsWindow* win, int ev )
{
for ( int i=0; i<Timers.size(); i++ )
{ if ( Timers[i].window==win && Timers[i].evid==ev )
{ Timers[i] = Timers.pop();
NumTimers--;
return;
}
}
}
void ws_remove_timers ( WsWindow* win )
{
for ( int i=0; i<Timers.size(); i++ )
{ if ( Timers[i].window==win )
{ Timers[i] = Timers.pop();
NumTimers--;
i--;
}
}
}
void ws_run ( int sleepms )
{
if ( sleepms>0 )
{ while ( wsi_check() )
{ gs_sleep ( sleepms );
if ( NumTimers ) ws_check_timers ();
}
}
else if ( sleepms<0 )
{ int n=sleepms;
while ( wsi_check() )
{ if ( NumTimers ) ws_check_timers ();
if ( ++n==0 ) { gs_sleep(1); n=sleepms; }
}
}
else
{ while ( wsi_check() )
{ if ( NumTimers ) ws_check_timers ();
}
}
}
void ws_check ( int sleepms )
{
static int counter=0;
if ( sleepms>0 ) gs_sleep ( sleepms );
else if ( sleepms<0 && ++counter%-sleepms==0 ) gs_sleep(1);
if ( NumTimers ) ws_check_timers ();
if ( wsi_check()==0 ) exit(0);
}
int ws_fast_check ()
{
if ( NumTimers ) ws_check_timers ();
return wsi_check ();
}
void ws_exit ( int c )
{
exit ( c );
}
void ws_screen_resolution ( int& w, int& h )
{
wsi_screen_resolution ( w, h );
}
//================================ End of File =================================================
| [
"44008857+kelvin331@users.noreply.github.com"
] | 44008857+kelvin331@users.noreply.github.com |
b213b02731974134602d63d813bdea26291ed7b1 | 4ac425b5a07f9a8ddcc124a51e62d7dd24e9bba3 | /Actividades/Builder/builder.cpp | 2bc34767bbdb337b9abc1a63e98163e807d00ca1 | [] | no_license | jehor737/AYMSSHR2017 | d809b68a0798036a66add36c27b441a0549b4fbf | 9a2de20a11257274dec781e3c08f82b8db476abb | refs/heads/master | 2021-01-15T19:06:35.932984 | 2017-10-28T02:42:13 | 2017-10-28T02:42:13 | 99,808,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,861 | cpp | #include <iostream>
#include <string>
using namespace std;
class Motor{
int potencia;
int numSerie;
public:
Motor()=default;
Motor(int pot, int nS) : potencia(pot), numSerie(nS){}
int getPotencia(){ return potencia; }
int getNumSerie(){ return numSerie; }
};
class Alas{
string marca;
int numSerie;
int hiper;
int spoilers;
public:
Alas()=default;
Alas(string m, int nS, int h, int sp) : marca(m), numSerie(nS), hiper(h), spoilers(sp){}
string getMarca(){ return marca; }
int getNumSerie(){ return numSerie; }
int getHiper(){ return hiper; }
int getSpoiler(){ return spoilers; }
};
class Avion{
Motor * motor;
Alas * alas;
string marca;
string modelo;
int numSerie;
public:
void setAlas(Alas * a){ alas = a;}
void setMotor(Motor * m){ motor = m; }
void setMarca(string m){ marca = m; }
void setModelo(string m){ modelo = m;}
void setNumSerie(int n){numSerie= n; }
string getMarca(){ return marca; }
string getModelo(){ return modelo; }
int getNumSerie(){ return numSerie; }
Alas * getAlas(){ return alas; }
Motor * getMotor(){ return motor; }
};
class Builder{
protected:
Avion * avion;
public:
Avion * getAvion(){ return avion; }
void createAvion()
{
avion = new Avion;
}
virtual Motor * buildMotor() = 0;
virtual Alas * buildAlas() = 0;
virtual string buildModelo() = 0;
virtual string buildMarca() = 0;
virtual int buildNumSerie() = 0;
};
class BoeingBuilder : public Builder{
public:
Motor * buildMotor()
{
Motor * motor = new Motor(10000, 1111111);
avion->setMotor(motor);
return motor;
}
Alas * buildAlas()
{
Alas * alas = new Alas("Boeing", 10101010, 10, 10);
avion->setAlas(alas);
return alas;
}
string buildMarca(){
avion->setMarca("boeing");
return "boeing";
}
string buildModelo(){
avion->setModelo("754");
return "754";
}
int buildNumSerie(){
avion->setNumSerie(123456789);
return 123456789;
}
};
class Director{
Builder * builder;
public:
void setBuilder(string tipoAvion){
if(tipoAvion == "Boeing")
{
builder = new BoeingBuilder;
}
}
Avion * getAvion()
{
return builder->getAvion();
}
void construct()
{
builder->createAvion();
builder->buildAlas();
builder->buildMotor();
builder->buildModelo();
builder->buildMarca();
builder->buildNumSerie();
}
};
int main(int argc, char const *argv[]) {
Director d;
d.setBuilder("Boeing");
d.construct();
Avion * a = d.getAvion();
std::cout << a->getMarca() <<'\n';
return 0;
}
| [
"horaciorojas737@hotmail.com"
] | horaciorojas737@hotmail.com |
5fd6802b47a253765d8f3c6f9b653faa6129ef95 | 872770c5323aa17120f2f708a1f0be09e663c9a8 | /Elastos/LibCore/inc/Elastos/Microedition/Khronos/Egl/EGLSurfaceImpl.h | 555c6c80228e2e7daea41a58fde607d9f77076af | [] | no_license | xianjimli/Elastos | 76a12b58db23dbf32ecbcefdaf6179510362dd21 | f9f019d266a7e685544596b365cfbc05bda9cb70 | refs/heads/master | 2021-01-11T08:26:17.180908 | 2013-08-21T02:31:17 | 2013-08-21T02:31:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | h |
#ifndef __EGLSURFACEIMPL_H__
#define __EGLSURFACEIMPL_H__
#include "_EGLSurface.h"
#include "Elastos.Microedition.Khronos.Egl_server.h"
#include <elastos/ElRefBase.h>
#include <elastos/AutoPtr.h>
#include <EGL/egl.h>
#include <skia/core/SkPixelRef.h>
class EGLSurfaceImpl
: public ElRefBase
, public _EGLSurface
, public IEGLSurface
{
public:
EGLSurfaceImpl();
EGLSurfaceImpl(
/* [in] */ EGLSurface surface);
CARAPI_(PInterface) Probe(
/* [in] */ REIID riid);
CARAPI_(UInt32) AddRef();
CARAPI_(UInt32) Release();
CARAPI GetInterfaceID(
/* [in] */ IInterface *pObject,
/* [out] */ InterfaceID *pIID);
CARAPI_(EGLSurface) Get();
CARAPI_(SkPixelRef*) GetNativePixelRef();
private:
EGLSurface mEGLSurface;
SkPixelRef* mNativePixelRef;
};
#endif //__EGLSURFACEIMPL_H__
| [
"cao.jing@kortide.com.cn"
] | cao.jing@kortide.com.cn |
c048365bafa7240edda4a871ab44f06ead34a325 | ea79d33460755420ee9f249b5a88527585b04ccf | /Eye-NAB/StartingEffortAndReferenceCode/newface.cpp | 8061a71a471abce28c2500a7de68c3d51c2fe0fa | [] | no_license | akshaypardeshi26/akshaypardeshi26 | 1c6a7dec8b7a7296872e1dc4e79727be100b2f72 | 2bb61426b0bdeec18d2d62325dc74b1323f97932 | refs/heads/master | 2021-05-04T10:48:39.120456 | 2017-07-11T00:51:32 | 2017-07-11T00:51:32 | 43,851,437 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,816 | cpp | /*
* Display video from webcam and detect faces
*/
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
#include "conio.h"
CvHaarClassifierCascade *cascade;
CvMemStorage *storage;
int detectFaces( IplImage *img );
int main( int argc, char** argv )
{
CvCapture *capture;
IplImage *frame[30];
IplImage *f;
char *filename = ".\\data\\haarcascades\\haarcascade_eye.xml";
/* load the classifier
note that I put the file in the same directory with
this code */
cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );
/* setup memory buffer; needed by the face detector */
storage = cvCreateMemStorage( 0 );
/* initialize camera */
capture = cvCaptureFromCAM( 0 );
/* always check */
assert( cascade && storage && capture );
/* create a window */
cvNamedWindow( "video", 1 );
int count=0;
int cnt=0;
while(1)
{
/* get a frame */
//f = cvQueryFrame( capture );
frame=cvLoadImage("c:\\tv\\images\\phine\\50rs\\w (15).jpg",1);
/* always check */
//cvShowImage("video1",frame[count]);
if( !f ) break;
/* 'fix' frame */
// cvFlip( f, f, -1 );
f->origin = 0;
/* detect faces and display video */
if(detectFaces(f ))
{
frame[count]=cvCreateImage(cvSize(320,240),8,3);
cvCopyImage(f,frame[count],NULL);
count++;
}
/* quit if user press 'q' */
cvWaitKey(200);
cnt++;
if(cnt==21) break;
}
printf("count= %d",count);
char a[50];
char count1[2]="a";
for(int k=0;k<count;k++)
{
cvShowImage("video",frame[k]);
cvWaitKey(300);
}
cvDestroyWindow( "result" );
/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "video" );
cvReleaseHaarClassifierCascade( &cascade );
cvReleaseMemStorage( &storage );
return 0;
}
int detectFaces( IplImage *img )
{
int i;
int s=-1;
/* detect faces */
CvSeq *faces = cvHaarDetectObjects(
img,
cascade,
storage,
1.1,
1,
0 /*CV_HAAR_DO_CANNY_PRUNNING*/,
cvSize(40,40 ) );
CvRect *r1;
int fl=0;
/* for each face found, draw a red box */
for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) {
r1 = ( CvRect* )cvGetSeqElem( faces, i );
if((r1->height<100)&&(r1->width<100))
{
fl=1;
cvRectangle( img,
cvPoint( r1->x, r1->y ),
cvPoint( r1->x + r1->width, r1->y + r1->height ),
CV_RGB( 255, 0, 0 ), 1, 8, 0 );
printf("width %d height %d\n",r1->width,r1->height);
}
} /* display video */
cvShowImage( "video", img );
return fl;
}
| [
"akshaypardeshi@akshays-mbp.dynamic.ucsd.edu"
] | akshaypardeshi@akshays-mbp.dynamic.ucsd.edu |
c4e4bc8f0041eb812b04dfdcf4846153646b755d | aa1d7d75f127131604ec2fd4c4153242ff6d9671 | /Game4InARow/twoplayersfield.h | ab3f6374ab39b1ff9e3623e9251548fa71734c04 | [] | no_license | scientist19/Game-4-in-a-row | 36b4974906e13b93354b923f055983c6b9cd58b7 | 755abd674a154e4cd63e66b982a8f4dfa1a8466b | refs/heads/master | 2020-04-07T18:15:58.515266 | 2018-12-13T19:37:28 | 2018-12-13T19:37:28 | 158,603,936 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | h | #ifndef TWOPLAYERSFIELD_H
#define TWOPLAYERSFIELD_H
#include "field.h"
class TwoPlayersField : public Field
{
public:
TwoPlayersField(Scene* scene, int cellSize);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void changePlayer();
void playerWin();
};
#endif // TWOPLAYERSFIELD_H
| [
"40214489+scientist19@users.noreply.github.com"
] | 40214489+scientist19@users.noreply.github.com |
45e4cff99d63817ecd0d0e74d3d1770e62735324 | 02b2ad77aa5c0ae72d8a0d8fac88e780a4759f66 | /483D.cpp | 13208ca8fc4816344c42df7f02f431c5a30053c5 | [] | no_license | shavidze/Codeforces | 34ef0081e52b0a7316752a1fb08e0d439e84348b | 06bb3689e20598431be6eb9ee1b2e614d956e157 | refs/heads/master | 2023-07-21T02:12:07.201943 | 2023-07-16T13:37:49 | 2023-07-16T13:37:49 | 184,745,816 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <iostream>
#include <sstream>
#include <cassert>
#include <fstream>
#include <cstring>
#include <numeric>
#include <ctype.h>
#define MOD 1000000009
#define exit return 0
#define inf 1000000000000000000LL
typedef long long ll;
#define exit return 0
#define PS system("pause")
#define S 100007
#define mx(a,b) a>b?a:b
#define R0(i,n) for (i = 0; i < n; i++)
#define R1(i,n) for (i = 1; i <= n; i++)
#define MS(a,x) memset(x, a, sizeof(x));
#define left (v+v)
#define right (v+v+1)
#define mid ((tl+tr)>>1)
#define SZ(x) ((int)x.size())
const double eps = 1e-10;
using namespace std;
const int NN = 100003;
const int need = (1 << 30) - 1;
int N, M;
int i, j, p;
int le[NN], ri[NN], q[NN];
int in[NN];
int sum[NN];
int tree[4*NN];
void build(int v, int tl, int tr){
if (tl == tr){
tree[v] = in[tl];
return;
}
build(left, tl, mid);
build(right, mid + 1, tr);
tree[v] = tree[v + v] & tree[v + v + 1];
}
int query(int v, int tl, int tr, int l, int r){
if (tl > r || tr < l || tl>tr)return -1;
if (tl >= l&&tr <= r){
return tree[v];
}
int a = query(v + v, tl, mid, l, r);
int b = query(v + v + 1, mid + 1, tr, l, r);
if (a == -1)return b;
if (b == -1)return a;
return a&b;
}
int main(){
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++){
scanf("%d %d %d ", &le[i], &ri[i], &q[i]);
le[i]--, ri[i]--;
}
for (int x = 0; x <= 30; x++){
for (int i = 0; i < N; i++)sum[i] = 0;
for (int i = 0; i < M; i++){
if ((q[i] >> x) & 1){
sum[le[i]] += 1;
sum[ri[i] + 1] -= 1;
}
}
for (int i = 0; i < N; i++){
if (i>0){
sum[i] += sum[i - 1];
}
if (sum[i]>0){
in[i] |= (1 << x);
}
}
}
build(1, 0, N - 1);
for (int i = 0; i < M; i++){
if (query(1, 0, N - 1, le[i], ri[i]) != q[i]){
puts("NO");
return 0;
}
}
puts("YES");
for (int i = 0; i < N; i++){
if (i>0)printf(" ");
printf("%d", in[i]);
}
exit;
}
| [
"saba.shavidze@wandio.com"
] | saba.shavidze@wandio.com |
209e02daa4d0234c7728a6ad2446906818f65503 | da003cc5e0bfd9053eaef6a090b3604d4d74ca2c | /MFCDemo/MFCDemo.cpp | 216c35f12c2d19a769a0d43c8f10ffd085869e9c | [] | no_license | NearlyDeadline/JLUCG02 | a34589292d663ba51affebadba98c6cd65d1d227 | ebfb8b31b100eb71e7fab0d25539c83d882aa6ed | refs/heads/master | 2020-09-13T09:40:14.750457 | 2019-12-16T12:45:30 | 2019-12-16T12:45:30 | 222,729,576 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 4,534 | cpp |
// MFCDemo.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "MFCDemo.h"
#include "MainFrm.h"
#include "MFCDemoDoc.h"
#include "MFCDemoView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMFCDemoApp
BEGIN_MESSAGE_MAP(CMFCDemoApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CMFCDemoApp::OnAppAbout)
// 基于文件的标准文档命令
ON_COMMAND(ID_FILE_NEW, &CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
// 标准打印设置命令
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
// CMFCDemoApp 构造
CMFCDemoApp::CMFCDemoApp()
{
// 支持重新启动管理器
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// 如果应用程序是利用公共语言运行时支持(/clr)构建的,则:
// 1) 必须有此附加设置,“重新启动管理器”支持才能正常工作。
// 2) 在您的项目中,您必须按照生成顺序向 System.Windows.Forms 添加引用。
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: 将以下应用程序 ID 字符串替换为唯一的 ID 字符串;建议的字符串格式
//为 CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("MFCDemo.AppID.NoVersion"));
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CMFCDemoApp 对象
CMFCDemoApp theApp;
// CMFCDemoApp 初始化
BOOL CMFCDemoApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。 否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// 初始化 OLE 库
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
EnableTaskbarInteraction(FALSE);
// 使用 RichEdit 控件需要 AfxInitRichEdit2()
// AfxInitRichEdit2();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU)
// 注册应用程序的文档模板。 文档模板
// 将用作文档、框架窗口和视图之间的连接
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CMFCDemoDoc),
RUNTIME_CLASS(CMainFrame), // 主 SDI 框架窗口
RUNTIME_CLASS(CMFCDemoView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// 分析标准 shell 命令、DDE、打开文件操作的命令行
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// 调度在命令行中指定的命令。 如果
// 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// 唯一的一个窗口已初始化,因此显示它并对其进行更新
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
int CMFCDemoApp::ExitInstance()
{
//TODO: 处理可能已添加的附加资源
AfxOleTerm(FALSE);
return CWinApp::ExitInstance();
}
// CMFCDemoApp 消息处理程序
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
public:
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// 用于运行对话框的应用程序命令
void CMFCDemoApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CMFCDemoApp 消息处理程序
| [
"1289790957@qq.com"
] | 1289790957@qq.com |
bd0e20869ade3d87369ccca004e9b0c2ec771ad7 | d8891f0cd573b3e8b344e07307de1840c6c8d482 | /src/nes/cpu/cpu.cc | 2ecae0dd05d0f2e8dd3cdd5f948b99c422d6e9d3 | [
"MIT"
] | permissive | mukerjee/nes-2a03 | 77305d8d671fff0986c9a27a7b891b3e4b3aa23f | 6cfd8d6b7ae4b437e6bc5bc4bb612fd9ce7fd2d3 | refs/heads/master | 2021-01-21T06:24:45.817931 | 2017-02-26T17:44:23 | 2017-02-26T17:44:23 | 83,228,079 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,474 | cc | #include "cpu.h"
Cpu::Cpu(Nes *nes, int clock_speed) : nes_(nes), clock_speed_(clock_speed) {}
Cpu::~Cpu() {
if (log_)
fclose(log_);
if (correct_log_)
fclose(correct_log_);
}
/**
* @brief loop through all instructions, executing them in sequence.
* Returns when it encounters a STP instruction.
*
* @return total number of cycles run.
*/
int Cpu::Run() {
uint32_t total_cycles = 0;
uint8_t cycles;
for(;;) {
uint8_t opcode = nes_->GetByte(register_pc_++);
if (opcode == 0xF2) {
#ifdef DEBUG
instr_pc_ = register_pc_-1;
opcode_ = opcode;
instr_ = "(HLT)";
AMImplied();
if(PrintState())
return -1;
#endif
break; // STP
}
cycles = RunInstruction(opcode);
RanCycles(cycles);
total_cycles += cycles;
#ifdef DEBUG
if(PrintState())
return -1;
#endif
}
#ifdef DEBUG
PrintHeader();
#endif
return total_cycles;
}
/**
* @brief runs an instruction given an opcode and returns the number of 6502
* cycles it took to run that instruction.
*
* @param opcode
*
* @return number of cycles to run instruction
*/
uint8_t Cpu::RunInstruction(uint8_t opcode) {
opcode_ = opcode;
#ifdef DEBUG
instr_pc_ = register_pc_ - 1;
#endif
int i = int(opcode);
uint16_t addr = (this->*opcodes[i].am)();
uint8_t extra_cycles = (this->*opcodes[i].op)(addr);
uint8_t cycles = opcodes[i].cycles;
bool cross_page = (addr % 0x100 == 0xFF);
if (cross_page)
cycles += opcodes[i].penalty;
return cycles + extra_cycles;
}
/*************** INSTRUCTIONS ***************/
// Descriptions from: http://www.obelisk.demon.co.uk/6502/reference.html
/**
* @brief This instruction adds the contents of a memory location to the
* accumulator together with the carry bit. If overflow occurs the carry bit is
* set, this enables multiple byte addition to be performed.
*
* @param address
*/
uint8_t Cpu::ADC(uint16_t address) {
uint8_t value = nes_->GetByte(address);
uint8_t original_a = register_a_;
register_a_= register_a_ + value + carry_flag_;
// set if sign of result is different than the sign of both
// the inputs.
overflow_flag_ = (original_a ^ register_a_) & (value ^ register_a_) & 0x80;
uint16_t resultu16 = original_a + value + carry_flag_;
carry_flag_ = resultu16 > 0xFF;
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "ADC";
#endif
return 0;
}
/**
* @brief A logical AND is performed, bit by bit, on the accumulator contents
* using the contents of a byte of memory.
*
* @param address
*/
uint8_t Cpu::AND(uint16_t address) {
uint8_t value = nes_->GetByte(address);
register_a_ &= value;
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "AND";
#endif
return 0;
}
/**
* @brief This operation shifts all the bits of the accumulator or memory
* contents one bit left. Bit 0 is set to 0 and bit 7 is placed in the carry
* flag. The effect of this operation is to multiply the memory contents by 2
* (ignoring 2's complement considerations), setting the carry if the result will
* not fit in 8 bits.
*
* @param address
*/
uint8_t Cpu::ASL(uint16_t address) {
uint8_t value;
if (opcode_ == 0x0A)
value = register_a_;
else
value = nes_->GetByte(address);
carry_flag_ = value & 0x80;
value <<= 1;
if (opcode_ == 0x0A)
register_a_ = value;
else
nes_->SetByte(address, value);
zero_flag_ = value == 0;
negative_flag_ = value & 0x80;
#ifdef DEBUG
instr_ = "ASL";
if (opcode_ != 0x0A) {
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", value);
}
#endif
return 0;
}
/**
* @brief If the carry flag is clear then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BCC(uint16_t address) {
uint8_t rc = 0;
if (!carry_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BCC";
#endif
return rc;
}
/**
* @brief If the carry flag is set then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BCS(uint16_t address) {
uint8_t rc = 0;
if (carry_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BCS";
#endif
return rc;
}
/**
* @brief If the zero flag is set then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BEQ(uint16_t address) {
uint8_t rc = 0;
if (zero_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BEQ";
#endif
return rc;
}
/**
* @brief This instructions is used to test if one or more bits are set in a
* target memory location. The mask pattern in A is ANDed with the value in
* memory to set or clear the zero flag, but the result is not kept. Bits 7 and 6
* of the value from memory are copied into the N and V flags.
*
* @param address
*/
uint8_t Cpu::BIT(uint16_t address) {
uint8_t mem = nes_->GetByte(address);
uint8_t result = register_a_ & mem;
zero_flag_ = result == 0;
overflow_flag_ = mem & 0x40;
negative_flag_ = mem & 0x80;
#ifdef DEBUG
instr_ = "BIT";
#endif
return 0;
}
/**
* @brief If the negative flag is set then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BMI(uint16_t address) {
uint8_t rc = 0;
if (negative_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BMI";
#endif
return rc;
}
/**
* @brief If the zero flag is clear then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BNE(uint16_t address) {
uint8_t rc = 0;
if (!zero_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BNE";
#endif
return rc;
}
/**
* @brief If the negative flag is clear then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BPL(uint16_t address) {
uint8_t rc = 0;
if (!negative_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BPL";
#endif
return rc;
}
/**
* @brief The BRK instruction forces the generation of an interrupt request. The
* program counter and processor status are pushed on the stack then the IRQ
* interrupt vector at $FFFE/F is loaded into the PC and the break flag in the
* status set to one.
*/
uint8_t Cpu::BRK(uint16_t address) {
register_pc_++; // brk increments the pc first
PushToStack(register_pc_ >> 8);
PushToStack(register_pc_ & 0xFF);
PushToStack(GetProcessorStatus());
register_pc_ = nes_->GetWord(0xFFFE);
break_command_ = 1;
#ifdef DEBUG
instr_ = "BRK";
#endif
return 0;
}
/**
* @brief If the overflow flag is clear then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BVC(uint16_t address) {
uint8_t rc = 0;
if (!overflow_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BVC";
#endif
return rc;
}
/**
* @brief If the overflow flag is set then add the relative displacement to the
* program counter to cause a branch to a new location.
*
* @param address
*
* @return
*/
uint8_t Cpu::BVS(uint16_t address) {
uint8_t rc = 0;
if (overflow_flag_) {
uint8_t old_page = register_pc_ >> 8;
register_pc_ += (int8_t)nes_->GetByte(address);
rc = 1 + abs(old_page - (register_pc_ >> 8));
}
#ifdef DEBUG
instr_ = "BVS";
#endif
return rc;
}
/**
* @brief Set the carry flag to zero.
*/
uint8_t Cpu::CLC(uint16_t address) {
carry_flag_ = 0;
#ifdef DEBUG
instr_ = "CLC";
#endif
return 0;
}
/**
* @brief Sets the decimal mode flag to zero.
*/
uint8_t Cpu::CLD(uint16_t address) {
decimal_mode_flag_ = 0;
#ifdef DEBUG
instr_ = "CLD";
#endif
return 0;
}
/**
* @brief Clears the interrupt disable flag allowing normal interrupt requests to
* be serviced.
*/
uint8_t Cpu::CLI(uint16_t address) {
interrupt_disable_ = 0;
#ifdef DEBUG
instr_ = "CLI";
#endif
return 0;
}
/**
* @brief Clears the overflow flag.
*/
uint8_t Cpu::CLV(uint16_t address) {
overflow_flag_ = 0;
#ifdef DEBUG
instr_ = "CLV";
#endif
return 0;
}
/**
* @brief This instruction compares the contents of the accumulator with another
* memory held value and sets the zero and carry flags as appropriate.
*
* @param address
*/
uint8_t Cpu::CMP(uint16_t address) {
uint8_t value = nes_->GetByte(address);
uint8_t result = register_a_ - value;
carry_flag_ = register_a_ >= value;
zero_flag_ = register_a_ == value;
negative_flag_ = result & 0x80;
#ifdef DEBUG
instr_ = "CMP";
#endif
return 0;
}
/**
* @brief This instruction compares the contents of the X register with another
* memory held value and sets the zero and carry flags as appropriate.
*
* @param address
*/
uint8_t Cpu::CPX(uint16_t address) {
uint8_t value = nes_->GetByte(address);
uint8_t result = register_x_ - value;
carry_flag_ = register_x_ >= value;
zero_flag_ = register_x_ == value;
negative_flag_ = result & 0x80;
#ifdef DEBUG
instr_ = "CPX";
#endif
return 0;
}
/**
* @brief This instruction compares the contents of the Y register with another
* memory held value and sets the zero and carry flags as appropriate.
*
* @param address
*/
uint8_t Cpu::CPY(uint16_t address) {
uint8_t value = nes_->GetByte(address);
uint8_t result = register_y_ - value;
carry_flag_ = register_y_ >= value;
zero_flag_ = register_y_ == value;
negative_flag_ = result & 0x80;
#ifdef DEBUG
instr_ = "CPY";
#endif
return 0;
}
/**
* @brief Subtracts one from the value held at a specified memory location
* setting the zero and negative flags as appropriate.
*
* @param address
*/
uint8_t Cpu::DEC(uint16_t address) {
uint8_t result = nes_->GetByte(address) - 1;
nes_->SetByte(address, result);
zero_flag_ = result == 0;
negative_flag_ = result & 0x80;
#ifdef DEBUG
instr_ = "DEC";
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", result);
#endif
return 0;
}
/**
* @brief Subtracts one from the X register setting the zero and negative flags
* as appropriate.
*/
uint8_t Cpu::DEX(uint16_t address) {
register_x_--;
zero_flag_ = register_x_ == 0;
negative_flag_ = register_x_ & 0x80;
#ifdef DEBUG
instr_ = "DEX";
#endif
return 0;
}
/**
* @brief Subtracts one from the Y register setting the zero and negative flags
* as appropriate.
*/
uint8_t Cpu::DEY(uint16_t address) {
register_y_--;
zero_flag_ = register_y_ == 0;
negative_flag_ = register_y_ & 0x80;
#ifdef DEBUG
instr_ = "DEY";
#endif
return 0;
}
/**
* @brief An exclusive OR is performed, bit by bit, on the accumulator contents
* using the contents of a byte of memory.
*
* @param address
*/
uint8_t Cpu::EOR(uint16_t address) {
register_a_ = register_a_ ^ nes_->GetByte(address);
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "EOR";
#endif
return 0;
}
/**
* @brief Adds one to the value held at a specified memory location setting the
* zero and negative flags as appropriate.
*
* @param address
*/
uint8_t Cpu::INC(uint16_t address) {
uint8_t result = nes_->GetByte(address) + 1;
nes_->SetByte(address, result);
zero_flag_ = result == 0;
negative_flag_ = result & 0x80;
#ifdef DEBUG
instr_ = "INC";
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", result);
#endif
return 0;
}
/**
* @brief Adds one to the X register setting the zero and negative flags as
* appropriate.
*/
uint8_t Cpu::INX(uint16_t address) {
register_x_++;
zero_flag_ = register_x_ == 0;
negative_flag_ = register_x_ & 0x80;
#ifdef DEBUG
instr_ = "INX";
#endif
return 0;
}
/**
* @brief Adds one to the Y register setting the zero and negative flags as
* appropriate.
*/
uint8_t Cpu::INY(uint16_t address) {
register_y_++;
zero_flag_ = register_y_ == 0;
negative_flag_ = register_y_ & 0x80;
#ifdef DEBUG
instr_ = "INY";
#endif
return 0;
}
/**
* @brief Sets the program counter to the address specified by the operand.
*
* @param address
*/
uint8_t Cpu::JMP(uint16_t address) {
register_pc_ = address;
#ifdef DEBUG
instr_ = "JMP";
if(opcode_ == 0x4C) {
int i = strlen(context_) - 3;
sprintf(&context_[i], "00]");
}
#endif
return 0;
}
/**
* @brief The JSR instruction pushes the address (minus one) of the return point
* on to the stack and then sets the program counter to the target memory
* address.
*
* @param address
*/
uint8_t Cpu::JSR(uint16_t address) {
PushToStack((register_pc_ - 1) >> 8);
PushToStack((register_pc_ - 1) & 0xFF);
register_pc_ = address;
#ifdef DEBUG
instr_ = "JSR";
int i = strlen(context_) - 3;
sprintf(&context_[i], "00]");
#endif
return 0;
}
/**
* @brief Loads a byte of memory into the accumulator setting the zero and
* negative flags as appropriate.
*
* @param address
*/
uint8_t Cpu::LDA(uint16_t address) {
register_a_ = nes_->GetByte(address);
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "LDA";
#endif
return 0;
}
/**
* @brief Loads a byte of memory into the X register setting the zero and
* negative flags as appropriate.
*
* @param address
*/
uint8_t Cpu::LDX(uint16_t address) {
register_x_ = nes_->GetByte(address);
zero_flag_ = register_x_ == 0;
negative_flag_ = register_x_ & 0x80;
#ifdef DEBUG
instr_ = "LDX";
#endif
return 0;
}
/**
* @brief Loads a byte of memory into the Y register setting the zero and
* negative flags as appropriate.
*
* @param address
*/
uint8_t Cpu::LDY(uint16_t address) {
register_y_ = nes_->GetByte(address);
zero_flag_ = register_y_ == 0;
negative_flag_ = register_y_ & 0x80;
#ifdef DEBUG
instr_ = "LDY";
#endif
return 0;
}
/**
* @brief Each of the bits in A or M is shift one place to the right. The bit
* that was in bit 0 is shifted into the carry flag. Bit 7 is set to zero.
*
* @param address
*/
uint8_t Cpu::LSR(uint16_t address) {
uint8_t value;
if (opcode_ == 0x4A)
value = register_a_;
else
value = nes_->GetByte(address);
carry_flag_ = value & 0x01;
value >>= 1;
if (opcode_ == 0x4A)
register_a_ = value;
else
nes_->SetByte(address, value);
zero_flag_ = value == 0; // not just register_a_
negative_flag_ = value & 0x80;
#ifdef DEBUG
instr_ = "LSR";
if (opcode_ != 0x4A) {
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", value);
}
#endif
return 0;
}
/**
* @brief The NOP instruction causes no changes to the processor other than the
* normal incrementing of the program counter to the next instruction.
*/
uint8_t Cpu::NOP(uint16_t address) {
#ifdef DEBUG
instr_ = "NOP";
#endif
return 0;
}
/**
* @brief An inclusive OR is performed, bit by bit, on the accumulator contents
* using the contents of a byte of memory.
*
* @param address
*/
uint8_t Cpu::ORA(uint16_t address) {
register_a_ |= nes_->GetByte(address);
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "ORA";
#endif
return 0;
}
/**
* @brief Pushes a copy of the accumulator on to the stack.
*/
uint8_t Cpu::PHA(uint16_t address) {
PushToStack(register_a_);
#ifdef DEBUG
instr_ = "PHA";
#endif
return 0;
}
/**
* @brief Pushes a copy of the status flags on to the stack.
*/
uint8_t Cpu::PHP(uint16_t address) {
PushToStack(GetProcessorStatus());
#ifdef DEBUG
instr_ = "PHP";
#endif
return 0;
}
/**
* @brief Pulls an 8 bit value from the stack and into the accumulator. The zero
* and negative flags are set as appropriate.
*/
uint8_t Cpu::PLA(uint16_t address) {
register_a_ = PopFromStack();
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "PLA";
#endif
return 0;
}
/**
* @brief Pulls an 8 bit value from the stack and into the processor flags. The
* flags will take on new states as determined by the value pulled.
*/
uint8_t Cpu::PLP(uint16_t address) {
SetProcessorStatus(PopFromStack());
#ifdef DEBUG
instr_ = "PLP";
#endif
return 0;
}
/**
* @brief Move each of the bits in either A or M one place to the left. Bit 0 is
* filled with the current value of the carry flag whilst the old bit 7 becomes
* the new carry flag value.
*
* @param address
*/
uint8_t Cpu::ROL(uint16_t address) {
uint8_t value;
if (opcode_ == 0x2A)
value = register_a_;
else
value = nes_->GetByte(address);
uint8_t b_0 = carry_flag_;
carry_flag_ = value & 0x80;
value <<= 1;
value |= b_0;
if (opcode_ == 0x2A)
register_a_ = value;
else
nes_->SetByte(address, value);
zero_flag_ = value == 0;
negative_flag_ = value & 0x80;
#ifdef DEBUG
instr_ = "ROL";
if (opcode_ != 0x2A) {
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", value);
}
#endif
return 0;
}
/**
* @brief Move each of the bits in either A or M one place to the right. Bit 7 is
* filled with the current value of the carry flag whilst the old bit 0 becomes
* the new carry flag value.
*
* @param address
*/
uint8_t Cpu::ROR(uint16_t address) {
uint8_t value;
if (opcode_ == 0x6A)
value = register_a_;
else
value = nes_->GetByte(address);
uint8_t b_7 = carry_flag_;
carry_flag_ = value & 0x01;
value >>= 1;
value |= (b_7 << 7);
if (opcode_ == 0x6A)
register_a_ = value;
else
nes_->SetByte(address, value);
zero_flag_ = register_a_ == 0; // not value
negative_flag_ = value & 0x80;
#ifdef DEBUG
instr_ = "ROR";
if (opcode_ != 0x6A) {
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", value);
}
#endif
return 0;
}
/**
* @brief The RTI instruction is used at the end of an interrupt processing
* routine. It pulls the processor flags from the stack followed by the program
* counter.
*/
uint8_t Cpu::RTI(uint16_t address) {
SetProcessorStatus(PopFromStack());
register_pc_ = PopFromStack();
register_pc_ |= (PopFromStack() << 8);
#ifdef DEBUG
instr_ = "RTI";
#endif
return 0;
}
/**
* @brief The RTS instruction is used at the end of a subroutine to return to the
* calling routine. It pulls the program counter (minus one) from the stack.
*/
uint8_t Cpu::RTS(uint16_t address) {
register_pc_ = PopFromStack();
register_pc_ |= (PopFromStack() << 8);
register_pc_++;
#ifdef DEBUG
instr_ = "RTS";
#endif
return 0;
}
/**
* @brief This instruction subtracts the contents of a memory location to the
* accumulator together with the not of the carry bit. If overflow occurs the
* carry bit is clear, this enables multiple byte subtraction to be performed.
*
* @param address
*/
uint8_t Cpu::SBC(uint16_t address) {
uint8_t value = nes_->GetByte(address);
uint8_t original_a = register_a_;
register_a_ = register_a_ - value - (1 - carry_flag_);
int16_t result16 = (int8_t)original_a - (int8_t)value - (1 - carry_flag_);
overflow_flag_ = result16 > 127 || result16 < -128;
carry_flag_ = original_a >= value + (1 - carry_flag_);
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "SBC";
#endif
return 0;
}
/**
* @brief Set the carry flag to one.
*/
uint8_t Cpu::SEC(uint16_t address) {
carry_flag_ = 1;
#ifdef DEBUG
instr_ = "SEC";
#endif
return 0;
}
/**
* @brief Set the decimal mode flag to one.
*/
uint8_t Cpu::SED(uint16_t address) {
decimal_mode_flag_ = 1;
#ifdef DEBUG
instr_ = "SED";
#endif
return 0;
}
/**
* @brief Set the interrupt disable flag to one.
*/
uint8_t Cpu::SEI(uint16_t address) {
interrupt_disable_ = 1;
#ifdef DEBUG
instr_ = "SEI";
#endif
return 0;
}
/**
* @brief Stores the contents of the accumulator into memory.
*
* @param address
*/
uint8_t Cpu::STA(uint16_t address) {
nes_->SetByte(address, register_a_);
#ifdef DEBUG
instr_ = "STA";
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", register_a_);
#endif
return 0;
}
/**
* @brief Stores the contents of the X register into memory.
*
* @param address
*/
uint8_t Cpu::STX(uint16_t address) {
nes_->SetByte(address, register_x_);
#ifdef DEBUG
instr_ = "STX";
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", register_x_);
#endif
return 0;
}
/**
* @brief Stores the contents of the Y register into memory.
*
* @param address
*/
uint8_t Cpu::STY(uint16_t address) {
nes_->SetByte(address, register_y_);
#ifdef DEBUG
instr_ = "STY";
int i = strlen(context_) - 3;
sprintf(&context_[i], "%02X]", register_y_);
#endif
return 0;
}
/**
* @brief Copies the current contents of the accumulator into the X register and
* sets the zero and negative flags as appropriate.
*/
uint8_t Cpu::TAX(uint16_t address) {
register_x_ = register_a_;
zero_flag_ = register_x_ == 0;
negative_flag_ = register_x_ & 0x80;
#ifdef DEBUG
instr_ = "TAX";
#endif
return 0;
}
/**
* @brief Copies the current contents of the accumulator into the Y register and
* sets the zero and negative flags as appropriate.
*/
uint8_t Cpu::TAY(uint16_t address) {
register_y_ = register_a_;
zero_flag_ = register_y_ == 0;
negative_flag_ = register_y_ & 0x80;
#ifdef DEBUG
instr_ = "TAY";
#endif
return 0;
}
/**
* @brief Copies the current contents of the stack register into the X register
* and sets the zero and negative flags as appropriate.
*/
uint8_t Cpu::TSX(uint16_t address) {
register_x_ = register_s_;
zero_flag_ = register_x_ == 0;
negative_flag_ = register_x_ & 0x80;
#ifdef DEBUG
instr_ = "TSX";
#endif
return 0;
}
/**
* @brief Copies the current contents of the X register into the accumulator and
* sets the zero and negative flags as appropriate.
*/
uint8_t Cpu::TXA(uint16_t address) {
register_a_ = register_x_;
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "TXA";
#endif
return 0;
}
/**
* @brief Copies the current contents of the X register into the stack register.
*/
uint8_t Cpu::TXS(uint16_t address) {
register_s_ = register_x_;
#ifdef DEBUG
instr_ = "TXS";
#endif
return 0;
}
/**
* @brief Copies the current contents of the Y register into the accumulator and
* sets the zero and negative flags as appropriate.
*/
uint8_t Cpu::TYA(uint16_t address) {
register_a_ = register_y_;
zero_flag_ = register_a_ == 0;
negative_flag_ = register_a_ & 0x80;
#ifdef DEBUG
instr_ = "TYA";
#endif
return 0;
}
/*************** HELPER FUNCTIONS ***************/
/**
* @brief pushes the input byte onto the stack and adjusts the stack pointer.
*
* @param value
*/
void Cpu::PushToStack(uint8_t value) {
nes_->SetByte(0x100 + register_s_, value);
register_s_--;
}
/**
* @brief pops a byte off the stack and returns it, adjusting the stack pointer.
*
* @return
*/
uint8_t Cpu::PopFromStack() {
register_s_++;
uint8_t result = nes_->GetByte(0x100 + register_s_);
return result;
}
// Descriptions from: http://nesdev.com/6502.txt
/**
* @brief sets the processors status flags based on the bits in the input.
*
* @param value
*/
void Cpu::SetProcessorStatus(uint8_t value) {
carry_flag_ = value & 0x01;
zero_flag_ = value & 0x02;
interrupt_disable_ = value & 0x04;
decimal_mode_flag_ = value & 0x08;
break_command_ = value & 0x10;
overflow_flag_ = value & 0x40;
negative_flag_ = value & 0x80;
}
/**
* @brief returns the set of current processor status flags as a byte.
*
* @return
*/
uint8_t Cpu::GetProcessorStatus() {
uint8_t status = 0;
status += carry_flag_;
status += zero_flag_ << 1;
status += interrupt_disable_ << 2;
status += decimal_mode_flag_ << 3;
status += break_command_ << 4;
status += 1 << 5;
status += overflow_flag_ << 6;
status += negative_flag_ << 7;
return status;
}
/*************** ADDRESSING MODES ***************/
// Descriptions from: http://www.obelisk.demon.co.uk/6502/addressing.html
uint16_t Cpu::AMImplied() {
#ifdef DEBUG
sprintf(context_, " ");
#endif
return 0;
}
/**
* @brief Some instructions have an option to operate directly upon the
* accumulator. The programmer specifies this by using a special operand value,
* 'A'.
*
* @return
*/
uint16_t Cpu::AMAccumulator() {
#ifdef DEBUG
sprintf(context_, "A ");
#endif
return 0;
}
/**
* @brief Immediate addressing allows the programmer to directly specify an 8
* bit constant within the instruction. It is indicated by a '#' symbol followed
* by an numeric expression.
*
* @return
*/
uint16_t Cpu::AMImmediate() {
#ifdef DEBUG
sprintf(context_, "#%02X ", nes_->GetByte(register_pc_));
#endif
return register_pc_++;
}
/**
* @brief An instruction using zero page addressing mode has only an 8 bit
* address operand. This limits it to addressing only the first 256 bytes of
* memory (e.g. $0000 to $00FF) where the most significant byte of the address is
* always zero. In zero page mode only the least significant byte of the address
* is held in the instruction making it shorter by one byte (important for space
* saving) and one less memory fetch during execution (important for speed).
*
* @return
*/
uint16_t Cpu::AMZeroPage() {
#ifdef DEBUG
uint8_t addr = nes_->GetByte(register_pc_);
uint8_t value = nes_->GetByte(addr);
sprintf(context_, "%02X [%02X]", addr, value);
#endif
return nes_->GetByte(register_pc_++);
}
/**
* @brief The address to be accessed by an instruction using indexed zero page
* addressing is calculated by taking the 8 bit zero page address from the
* instruction and adding the current value of the X register to it. For example
* if the X register contains $0F and the instruction LDA $80,X is executed then
* the accumulator will be loaded from $008F (e.g. $80 + $0F => $8F).
*
* @return
*/
uint16_t Cpu::AMZeroPageX() {
#ifdef DEBUG
uint8_t addr = nes_->GetByte(register_pc_);
uint8_t value = nes_->GetByte((addr + register_x_) % 0x100);
sprintf(context_, "%02X,X [00%02X=%02X]", addr,
(addr+register_x_) % 0x100, value);
#endif
return (nes_->GetByte(register_pc_++) + register_x_) % 0x100;
}
/**
* @brief The address to be accessed by an instruction using indexed zero page
* addressing is calculated by taking the 8 bit zero page address from the
* instruction and adding the current value of the Y register to it. This mode can
* only be used with the LDX and STX instructions.
*
* @return
*/
uint16_t Cpu::AMZeroPageY() {
#ifdef DEBUG
uint8_t addr = nes_->GetByte(register_pc_);
uint8_t value = nes_->GetByte((addr + register_y_) % 0x100);
sprintf(context_, "%02X,Y [00%02X=%02X]", addr,
(addr+register_x_) % 0x100, value);
#endif
return (nes_->GetByte(register_pc_++) + register_y_) % 0x100;
}
/**
* @brief Relative addressing mode is used by branch instructions (e.g. BEQ, BNE,
* etc.) which contain a signed 8 bit relative offset (e.g. -128 to +127) which
* is added to program counter if the condition is true. As the program counter
* itself is incremented during instruction execution by two the effective
* address range for the target instruction must be with -126 to +129 bytes of
* the branch.
*
* @return
*/
uint16_t Cpu::AMRelative() {
#ifdef DEBUG
int8_t addr = nes_->GetByte(register_pc_);
sprintf(context_, "%02X [%04X]", (uint8_t)addr, addr+register_pc_+1);
#endif
return register_pc_++;
}
/**
* @brief Instructions using absolute addressing contain a full 16 bit address
* to identify the target location.
*
* @return
*/
uint16_t Cpu::AMAbsolute() {
#ifdef DEBUG
uint16_t addr = nes_->GetWord(register_pc_);
uint8_t value = nes_->GetByte(addr);
sprintf(context_, "%04X [%02X]", addr, value);
#endif
uint16_t address = nes_->GetWord(register_pc_);
register_pc_ += 2;
return address;
}
/**
* @brief The address to be accessed by an instruction using X register indexed
* absolute addressing is computed by taking the 16 bit address from the
* instruction and added the contents of the X register. For example if X contains
* $92 then an STA $2000,X instruction will store the accumulator at $2092 (e.g.
* $2000 + $92).
*
* @return
*/
uint16_t Cpu::AMAbsoluteX() {
#ifdef DEBUG
uint16_t addr = nes_->GetWord(register_pc_);
uint8_t value = nes_->GetByte(addr+register_x_);
sprintf(context_, "%04X,X [%04X=%02X]", addr, addr+register_x_,
value);
#endif
uint16_t address = nes_->GetWord(register_pc_) + register_x_;
register_pc_ += 2;
return address;
}
/**
* @brief The Y register indexed absolute addressing mode is the same as the
* previous mode only with the contents of the Y register added to the 16 bit
* address from the instruction.
*
* @return
*/
uint16_t Cpu::AMAbsoluteY() {
#ifdef DEBUG
uint16_t addr = nes_->GetWord(register_pc_);
uint8_t value = nes_->GetByte(addr+register_y_);
sprintf(context_, "%04X,Y [%04X=%02X]", addr, addr+register_y_,
value);
#endif
uint16_t address = nes_->GetWord(register_pc_) + register_y_;
register_pc_ += 2;
return address;
}
/**
* @brief JMP is the only 6502 instruction to support indirection. The
* instruction contains a 16 bit address which identifies the location of the
* least significant byte of another 16 bit memory address which is the real
* target of the instruction.
*
* For example if location $0120 contains $FC and location $0121 contains $BA then
* the instruction JMP ($0120) will cause the next instruction execution to occur
* at $BAFC (e.g. the contents of $0120 and $0121).
*
* @return
*/
uint16_t Cpu::AMIndirect() {
#ifdef DEBUG
uint16_t addr = nes_->GetWord(register_pc_);
uint16_t value = nes_->GetWord(addr);
sprintf(context_, "(%04X) [%04X]", addr, value);
#endif
uint16_t address = nes_->GetWord(nes_->GetWord(register_pc_));
register_pc_ += 2;
return address;
}
/**
* @brief Indexed indirect addressing is normally used in conjunction with a
* table of address held on zero page. The address of the table is taken from the
* instruction and the X register added to it (with zero page wrap around) to give
* the location of the least significant byte of the target address.
*
* @return
*/
uint16_t Cpu::AMIndexedIndirect() {
#ifdef DEBUG
uint8_t addr = nes_->GetByte(register_pc_);
uint8_t value = nes_->GetByte(nes_->GetWord((addr+register_x_) % 0x100));
sprintf(context_, "(%02X,X) [%04X=%02X]", addr,
nes_->GetWord((addr+register_x_) % 0x100), value);
#endif
return nes_->GetWord((nes_->GetByte(register_pc_++) +
register_x_) % 0x100);
}
/**
* @brief Indirect indirect addressing is the most common indirection mode used
* on the 6502. In instruction contains the zero page location of the least
* significant byte of 16 bit address. The Y register is dynamically added to this
* value to generated the actual target address for operation.
*
* @return
*/
uint16_t Cpu::AMIndirectIndexed() {
#ifdef DEBUG
uint8_t addr = nes_->GetByte(register_pc_);
uint8_t value = nes_->GetByte(nes_->GetWord(addr) +
register_y_);
sprintf(context_, "(%02X),Y [%04X=%02X]", addr,
nes_->GetWord(addr) + register_y_, value);
#endif
return nes_->GetWord(nes_->GetByte(register_pc_++)) +
register_y_;
}
/*************** LOGGING ***************/
#define write_log(format, args...) \
if (should_print_) { \
printf(format, ## args); \
} \
fprintf(log_, format, ## args);
void Cpu::PrintHeader() {
write_log("\n\n\n");
write_log("%s\n", file_name_.c_str());
write_log("Track Number %d, Call number %d\n\n", track_, call_number_);
write_log("PC Instr. Context A X Y Status SP\n");
write_log("===========================================================\n");
call_number_++;
}
void Cpu::SetLogging(std::string file_name, int track) {
file_name_ = file_name;
track_ = track;
#ifdef DEBUG
log_ = fopen("./test.log", "w");
PrintHeader();
#endif
}
void Cpu::SetLogChecking(std::string correct_log) {
correct_log_ = fopen(correct_log.c_str(), "r");
size_t buffer_size = 1024;
char *throw_away = (char *)malloc(buffer_size * sizeof(char));
for(int i = 0; i < 8; i++) {
getline(&throw_away, &buffer_size, correct_log_);
}
free(throw_away);
}
int Cpu::PrintState() {
int invalid = 0;
std::string extra_space;
extra_space = (instr_.length() == 3) ? " " : "";
std::string flags;
flags += negative_flag_ ? "N" : ".";
flags += overflow_flag_ ? "V" : ".";
flags += interrupt_disable_ ? "I" : ".";
flags += zero_flag_ ? "Z" : ".";
flags += carry_flag_ ? "C" : ".";
size_t state_buffer_size = 1024;
char *current_state = (char *)malloc(state_buffer_size * sizeof(char));
char *correct_state = (char *)malloc(state_buffer_size * sizeof(char));
sprintf(current_state, "%04X %02X %s%s%s %s %02X %02X %02X [%s] %02X\n",
instr_pc_, opcode_, extra_space.c_str(),
instr_.c_str(), extra_space.c_str(),
context_, register_a_,
register_x_, register_y_,
flags.c_str(), register_s_);
write_log("%s", current_state);
if (correct_log_) {
ssize_t bytes = getline(&correct_state, &state_buffer_size, correct_log_);
if (bytes == 1) {
for(int i = 0; i < 8; i++) {
getline(&correct_state, &state_buffer_size, correct_log_);
}
}
if (bytes > 0) {
if (strcmp(current_state, correct_state)) {
printf("error!\n");
printf("current: %scorrect: %s", current_state, correct_state);
printf("bytes: %zu\n", bytes);
invalid = 1;
}
}
}
free(current_state);
free(correct_state);
return invalid;
}
| [
"mukerjee@cs.cmu.edu"
] | mukerjee@cs.cmu.edu |
2e404058775c66a55b5652f7b371a6a1461ac749 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/110/795/CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_04.cpp | 2df700580e0297a9f402fec352f3bd5cf8ecfec6 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,128 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_04.cpp
Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__new.label.xml
Template File: sources-sink-04.tmpl.cpp
*/
/*
* @description
* CWE: 680 Integer Overflow to Buffer Overflow
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Small number greater than zero that will not cause an integer overflow in the sink
* Sink:
* BadSink : Attempt to allocate array using length value from source
* Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE)
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
/* The two variables below are declared "const", so a tool should
be able to identify that reads of these will always return their
initialized values. */
static const int STATIC_CONST_TRUE = 1; /* true */
static const int STATIC_CONST_FALSE = 0; /* false */
namespace CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_04
{
#ifndef OMITBAD
void bad()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_TRUE)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
data = atoi(inputBuffer);
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
{
size_t dataBytes,i;
int *intPointer;
/* POTENTIAL FLAW: dataBytes may overflow to a small value */
dataBytes = data * sizeof(int); /* sizeof array in bytes */
intPointer = (int*)new char[dataBytes];
for (i = 0; i < (size_t)data; i++)
{
intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */
}
printIntLine(intPointer[0]);
delete [] intPointer;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Set data to a relatively small number greater than zero */
data = 20;
}
{
size_t dataBytes,i;
int *intPointer;
/* POTENTIAL FLAW: dataBytes may overflow to a small value */
dataBytes = data * sizeof(int); /* sizeof array in bytes */
intPointer = (int*)new char[dataBytes];
for (i = 0; i < (size_t)data; i++)
{
intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */
}
printIntLine(intPointer[0]);
delete [] intPointer;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_TRUE)
{
/* FIX: Set data to a relatively small number greater than zero */
data = 20;
}
{
size_t dataBytes,i;
int *intPointer;
/* POTENTIAL FLAW: dataBytes may overflow to a small value */
dataBytes = data * sizeof(int); /* sizeof array in bytes */
intPointer = (int*)new char[dataBytes];
for (i = 0; i < (size_t)data; i++)
{
intPointer[i] = 0; /* may write beyond limit of intPointer if integer overflow occured above */
}
printIntLine(intPointer[0]);
delete [] intPointer;
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE680_Integer_Overflow_to_Buffer_Overflow__new_listen_socket_04; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
a5293b55ea71b121d6cec905b8195d55813db97c | 33eaafc0b1b10e1ae97a67981fe740234bc5d592 | /tests/RandomSAT/z3-master/src/parsers/smt/smtparser.h | 9a09d1f4ff79b51747c2fe288ba8032625ae0ffa | [
"MIT"
] | permissive | akinanop/mvl-solver | 6c21bec03422bb2366f146cb02e6bf916eea6dd0 | bfcc5b243e43bddcc34aba9c34e67d820fc708c8 | refs/heads/master | 2021-01-16T23:30:46.413902 | 2021-01-10T16:53:23 | 2021-01-10T16:53:23 | 48,694,935 | 6 | 2 | null | 2016-08-30T10:47:25 | 2015-12-28T13:55:32 | C++ | UTF-8 | C++ | false | false | 964 | h | /*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smtparser.h
Abstract:
SMT parsing utilities
Author:
Nikolaj Bjorner (nbjorner) 2006-09-25
Revision History:
--*/
#ifndef SMT_PARSER_H_
#define SMT_PARSER_H_
#include<iostream>
#include"ast.h"
#include"vector.h"
#include"smtlib.h"
namespace smtlib {
class parser {
public:
static parser * create(ast_manager & ast_manager, bool ignore_user_patterns = false);
virtual ~parser() {}
virtual void add_builtin_op(char const *, family_id fid, decl_kind kind) = 0;
virtual void add_builtin_type(char const *, family_id fid, decl_kind kind) = 0;
virtual void initialize_smtlib() = 0;
virtual void set_error_stream(std::ostream& strm) = 0;
virtual bool parse_file(char const * path) = 0;
virtual bool parse_string(char const * string) = 0;
virtual benchmark * get_benchmark() = 0;
};
};
#endif
| [
"nikaponens@gmail.com"
] | nikaponens@gmail.com |
f9b74bec0f3b5c5941e0e654264c5c71102e8b61 | 837e173ac570b1b3d2845a23acef3ea54ca80d21 | /Game/Source/Transition.h | 9478cb6c08dd6198276e91cda8a4bc4c344f29a2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | TitoLuce/PlatformerGame | f26ab8c6142ed7607f47c260a9e9ec7a6004d3a4 | 1694032bc25f742643fca1f9764f11438083aebb | refs/heads/master | 2023-02-14T01:56:34.494164 | 2021-01-10T22:20:59 | 2021-01-10T22:20:59 | 301,351,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | h | #ifndef __TRANSITION_H__
#define __TRANSITION_H__
#include "Module.h"
#include "SDL\include\SDL_rect.h"
class Transition : public Module
{
public:
//Constructor
Transition();
//Destructor
~Transition();
// Called when the module is activated
// Enables the blending mode for transparency
bool Start();
// Called at the middle of the application loop
// Updates the fade logic
bool Update(float dt);
// Called at the end of the application loop
// Performs the render call of a black rectangle with transparency
bool PostUpdate();
// Called from another module
// Starts the fade process which has two steps, fade_out and fade_in
// After the first step, the modules should be switched
bool TransitionStep(Module* toDisable, Module* toEnable, bool onlyFadeIn = false, float frames = 60);
private:
enum Transition_Step
{
NONE,
TO_BLACK,
FROM_BLACK
} currentStep = Transition_Step::NONE;
// A frame count system to handle the fade time and ratio
Uint32 frameCount = 0;
Uint32 maxFadeFrames = 0;
// The rectangle of the screen, used to render the black rectangle
SDL_Rect screenRect;
// The modules that should be switched after the first step
Module* moduleToEnable = nullptr;
Module* moduleToDisable = nullptr;
};
#endif //__MODULEFADETOBLACK_H__ | [
"59049803+TitoLuce@users.noreply.github.com"
] | 59049803+TitoLuce@users.noreply.github.com |
3a78bdc43a9c65cc82e2841c7f7fb7a226d2fa9b | 04fee3ff94cde55400ee67352d16234bb5e62712 | /csp-s2019.luogu/source/XJ-00109/partition/partition.cpp | 0c9401b818e7d4abc22536c72d3429db86ea2eac | [] | no_license | zsq001/oi-code | 0bc09c839c9a27c7329c38e490c14bff0177b96e | 56f4bfed78fb96ac5d4da50ccc2775489166e47a | refs/heads/master | 2023-08-31T06:14:49.709105 | 2021-09-14T02:28:28 | 2021-09-14T02:28:28 | 218,049,685 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,449 | cpp | #include<stdio.h>
#include<string.h>
#define maxn (5010)
#define lenth (110)
#include<algorithm>
using namespace std;
int n,type,cnt,lens,lenans;
long long int a[maxn],b[maxn];
int s[lenth],ans[lenth],c[lenth];
void multi(int x)
{
memset(s,0,sizeof(s));
lens=0;
int len=0;
while(x)
{
len++;
c[len]=x%10;
x/=10;
}
lens=len*2;
for(int i=1;i<=len;i++)
{
for(int j=1;j<=len;j++)
{
s[i+j-1]+=c[i]*c[j];
}
}
int q=0;
for(int i=1;i<=lens;i++)
{
s[i]+=q;
q=s[i]/10;
s[i]%=10;
}
while(s[lens]==0)lens--;
}
void add( )
{
lenans=lens+lenans;
for(int i=1;i<=lenans;i++)
{
ans[i]=ans[i]+s[i];
}
int q=0;
for(int i=1;i<=lenans;i++)
{
ans[i]+=q;
q=ans[i]/10;
ans[i]%=10;
}
while(ans[lenans]==0)lenans--;
}
int main ( )
{
freopen("partition.in","r",stdin);
freopen("partition.out","w",stdout);
scanf("%d %d",&n,&type);
if(type==0)
{
for(int i=1;i<=n;i++)
scanf("%I64d",&a[i]);
cnt=0;
for(int i=1;i<=n;i++)
{
if(a[i]<b[cnt])
{
if((a[i]+b[cnt]<=a[i]+a[i+1]&&a[i]+b[cnt]<=a[i+1])||i==n)b[cnt]+=a[i];
else a[i+1]+=a[i];
}
else b[++cnt]=a[i];
}
for(int i=1;i<=cnt;i++)
{
multi(b[i]);
add();
}
for(int i=lenans;i>=1;i--)
printf("%d",ans[i]);
fclose(stdin);
fclose(stdout);
return 0;
}
}
//我猜这是动归 但是我不会 所以写了贪心 但并不对
| [
"15276671309@163.com"
] | 15276671309@163.com |
87797c47b44608202129b2346e178d59a4151770 | 122544beba52884fdb656d8189c76134f8f1d8c5 | /1512418_Dll/Source code/1512418.Paint/MyDll/Lib.cpp | 859e496600a24007c90ed5c243353ca45715d6e1 | [] | no_license | Duy-Phuong/Windows | 767bcf5455cf337f6f8f674db4b05554c31f0841 | 7b2dbc6a964dfe29de19c1632df0a29586ae8aee | refs/heads/master | 2021-08-22T21:49:53.607553 | 2017-12-01T10:18:53 | 2017-12-01T10:18:53 | 111,682,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,743 | cpp | #include "stdafx.h"
#include "Lib.h"
//2 ham ve hinh cho nguoi dung xem truoc
void DrawRect_Square(ObjectFactory* prototype1, int isChosen, int shift, bool isDrawing, int currentX, int currentY, int lastX, int lastY, HDC memHDC, Graphics* graphics)
{
if (isDrawing && (isChosen == RECTANGLE))
{
if (shift & 0x8000)//hinh vuong
{
int width = abs(lastX - currentX);
if (lastX > currentX && lastY > currentY)//góc 2
{
prototype1->DrawSquare(memHDC, currentX, currentY, width, width, graphics);//mau prototype
}
if (lastX < currentX && lastY < currentY)//góc 4
{
prototype1->DrawSquare(memHDC, lastX, lastY + (abs(lastY - currentY) - width), width, width, graphics);//mau prototype
}
if (lastX > currentX && lastY < currentY)//góc 1
{
prototype1->DrawSquare(memHDC, currentX, lastY + (abs(lastY - currentY) - width), width, width, graphics);//mau prototype
}
if (lastX < currentX && lastY > currentY)//góc 3
{
prototype1->DrawSquare(memHDC, lastX, currentY, width, width, graphics);//mau prototype
}
}
else
{
//x, y, dài, rộng
if (lastX > currentX && lastY > currentY)//góc 2
{
prototype1->DrawRetangle(memHDC, currentX, currentY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX < currentX && lastY < currentY)//góc 4
{
prototype1->DrawRetangle(memHDC, lastX, lastY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX > currentX && lastY < currentY)//góc 1
{
prototype1->DrawRetangle(memHDC, currentX, lastY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX < currentX && lastY > currentY)//góc 3
{
prototype1->DrawRetangle(memHDC, lastX, currentY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
}
}
}
void DrawEllipse_Circle(ObjectFactory* prototype1, int isChosen, int shift, bool isDrawing, int currentX, int currentY, int lastX, int lastY, HDC memHDC, Graphics* graphics)
{
if (isDrawing && (isChosen == ELLIPSE)) {
if (shift & 0x8000)
{
int width1 = abs(lastX - currentX);
if (lastX > currentX && lastY > currentY)//góc 2
{
prototype1->DrawCircle(memHDC, currentX, currentY, width1, width1, graphics);//mau prototype
}
if (lastX < currentX && lastY < currentY)//góc 4
{
prototype1->DrawCircle(memHDC, lastX, lastY + (abs(lastY - currentY) - width1), width1, width1, graphics);//mau prototype
}
if (lastX > currentX && lastY < currentY)//góc 1
{
prototype1->DrawCircle(memHDC, currentX, lastY + (abs(lastY - currentY) - width1), width1, width1, graphics);//mau prototype
}
if (lastX < currentX && lastY > currentY)//góc 3
{
prototype1->DrawCircle(memHDC, lastX, currentY, width1, width1, graphics);//mau prototype
}
}
else
{
if (lastX > currentX && lastY > currentY)//góc 2
{
prototype1->DrawEllipse(memHDC, currentX, currentY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX < currentX && lastY < currentY)//góc 4
{
prototype1->DrawEllipse(memHDC, lastX, lastY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX > currentX && lastY < currentY)//góc 1
{
prototype1->DrawEllipse(memHDC, currentX, lastY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
if (lastX < currentX && lastY > currentY)//góc 3
{
prototype1->DrawEllipse(memHDC, lastX, currentY, abs(lastX - currentX), abs(lastY - currentY), graphics);//mau prototype
}
}
}
}
//2 hàm vẽ khi nhả chuột
void DrawRect_Square1(AbstracFactory* factory, int isChosen, int shift, bool isDrawing, int currentX, int currentY, int x, int y, vector<CShape*> &shapes)
{
if (isDrawing && (isChosen == RECTANGLE)) {
if (shift & 0x8000)
{
CShape* rect = factory->Create(SQUARE); //su dang mau thiet ke factory de tao doi tuong
int l = abs(x - currentX);
if (x > currentX && y > currentY)//góc 2
{
rect->SetData(currentX, currentY, l, l);
}
if (x < currentX && y < currentY)//góc 4
{
rect->SetData(x, y + (abs(y - currentY) - l), l, l); //phai cong them 1 khoang de khi width = l thi ve hinh ra goc duoi se k change
}
if (x > currentX && y < currentY)//góc 1
{
rect->SetData(currentX, y + (abs(y - currentY) - l), l, l);
}
if (x < currentX && y > currentY)//góc 3
{
rect->SetData(x, currentY, l, l);
}
shapes.push_back(rect);
}
else
{
CShape* rect = factory->Create(RECTANGLE); //su dang mau thiet ke factory de tao doi tuong
if (x > currentX && y > currentY)//góc 2
{
rect->SetData(currentX, currentY, abs(x - currentX), abs(y - currentY));
}
if (x < currentX && y < currentY)//góc 4
{
rect->SetData(x, y, abs(x - currentX), abs(y - currentY));
}
if (x > currentX && y < currentY)//góc 1
{
rect->SetData(currentX, y, abs(x - currentX), abs(y - currentY));
}
if (x < currentX && y > currentY)//góc 3
{
rect->SetData(x, currentY, abs(x - currentX), abs(y - currentY));
}
shapes.push_back(rect);
}
}
}
void DrawEllipse_Circle1(AbstracFactory* factory, int isChosen, int shift, bool isDrawing, int currentX, int currentY, int x, int y, vector<CShape*> &shapes)
{
if (isDrawing && (isChosen == ELLIPSE)) {
if (shift & 0x8000)
{
CShape* rect = factory->Create(CIRCLE); //su dang mau thiet ke factory de tao doi tuong
int length1 = 0;
length1 = abs(x - currentX);
if (x > currentX && y > currentY)//góc 2
{
rect->SetData(currentX, currentY, length1, length1);
}
if (x < currentX && y < currentY)//góc 4
{
rect->SetData(x, y + (abs(y - currentY) - length1), length1, length1);
}
if (x > currentX && y < currentY)//góc 1
{
rect->SetData(currentX, y + (abs(y - currentY) - length1), length1, length1);
}
if (x < currentX && y > currentY)//góc 3
{
rect->SetData(x, currentY, length1, length1);
}
shapes.push_back(rect);
}
else
{
CShape* rect = factory->Create(ELLIPSE); //su dang mau thiet ke factory de tao doi tuong
if (x > currentX && y > currentY)//góc 2
{
rect->SetData(currentX, currentY, abs(x - currentX), abs(y - currentY));
}
if (x < currentX && y < currentY)//góc 4
{
rect->SetData(x, y, abs(x - currentX), abs(y - currentY));
}
if (x > currentX && y < currentY)//góc 1
{
rect->SetData(currentX, y, abs(x - currentX), abs(y - currentY));
}
if (x < currentX && y > currentY)//góc 3
{
rect->SetData(x, currentY, abs(x - currentX), abs(y - currentY));
}
shapes.push_back(rect);
}
}
} | [
"tranduyphuong20100@gmail.com"
] | tranduyphuong20100@gmail.com |
a21e569383467a8906338ca231ab51e8c4637185 | bfb1c7ff905065f0e3914b66c9a932bc811640a5 | /.svn/pristine/a2/a21e569383467a8906338ca231ab51e8c4637185.svn-base | a7a484c5755980b8fc48279dc8907acc75980687 | [] | no_license | djskual/savegame-manager-gx | 1ddcdcfcdaf7a4043b7fd756136ec8cca0fbf5f3 | ae3cb59cb5bbae91bf65d48cb61961ed49d896d3 | refs/heads/master | 2020-06-03T05:11:20.735987 | 2015-04-14T13:16:49 | 2015-04-14T13:16:49 | 33,944,551 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,338 | /****************************************************************************
* libwiigui Template
* Tantric 2009
*
* main.cpp
* Basic template/demonstration of libwiigui capabilities. For a
* full-featured app using many more extensions, check out Snes9x GX.
***************************************************************************/
#include <gccore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ogcsys.h>
#include <unistd.h>
#include <locale.h>
#include "main.h"
#include "menu/menu.h"
#include "menu/MainWindow.h"
extern bool geckoinit;
extern bool textVideoInit;
unsigned int *xfb = NULL;
NAVINFO navinfo;
WINDOWINFO windowinfo;
GuiBGM * bgMusic = NULL;
void InitTextVideo ()
{
gprintf("\n\nInitTextVideo ()");
if (textVideoInit)
{
gprintf("...0");
return;
}
VIDEO_Init();
// get default video mode
GXRModeObj *vmode = VIDEO_GetPreferredMode(NULL);
// widescreen fix
VIDEO_Configure (vmode);
// Allocate the video buffers
xfb = (u32 *) MEM_K0_TO_K1 (SYS_AllocateFramebuffer (vmode));
// A console is always useful while debugging
console_init (xfb, 20, 64, vmode->fbWidth, vmode->xfbHeight, vmode->fbWidth * 2);
// Clear framebuffers etc.
VIDEO_ClearFrameBuffer (vmode, xfb, COLOR_BLACK);
VIDEO_SetNextFramebuffer (xfb);
VIDEO_SetBlack (FALSE);
VIDEO_Flush ();
VIDEO_WaitVSync ();
if (vmode->viTVMode & VI_NON_INTERLACE)
VIDEO_WaitVSync ();
//send console output to the gecko
if (geckoinit)CON_EnableGecko(1, true);
textVideoInit = true;
gprintf("...1");
}
int main(int argc UNUSED, char *argv[] UNUSED)
{
geckoinit = InitGecko();
InitTextVideo();
int ret = IOS_ReloadIOS(249);
if (ret < 0)
{
IOS_ReloadIOS(250);
}
Sys_Init(); // Initialize wii button call back
InitVideo(); // Initialize video
SetupPads(); // Initialize input
InitAudio(); // Initialize audio
SDCard_Init(); // Initialize file system
USBDevice_Init(); // Initialize file system
ISFS_Initialize();// Initialize Wii file system
ResetNavInfo();
ResetWindowInfo();
InitApp();
bgMusic = new GuiBGM(bg_music_ogg, bg_music_ogg_size, cfg.MusicVolume);
bgMusic->SetLoop(cfg.BgMusicLoop);
bgMusic->Load(cfg.BgMusicPath);
bgMusic->Play();
MainWindow::Instance()->Show();
}
| [
"dj_skual@hotmail.com"
] | dj_skual@hotmail.com | |
18a3ddd7d8c1b86155b49f0b8f7b40f76c661e1f | 6482b755c9daaa91a3961b92d1ab38356374bb18 | /template1/template1/typename.cpp | fdbc9cd00dd77373041895e2a052c9f0aeeed7e8 | [] | no_license | y2jinc/cpp_template_edu | dc61d9d7ac891a3f50469eb5a3ec693b468891dc | 948add986c49efc7420c2e5fd10e7aae260cbdad | refs/heads/master | 2020-03-16T06:22:39.024412 | 2018-06-26T14:28:35 | 2018-06-26T14:28:35 | 132,552,841 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 477 | cpp | #include <iostream>
using namespace std;
class Test
{
public:
//...
//enum { DWORD = 5 };
typedef int DWORD;
};
template<typename T>
typename T::DWORD foo(T t) // T : test
{
// 아래 한줄을 해석해 보세요.
// T::DWORD* p; // 값 : 5 * p -> ms compiler 에서는 에러나지 않음.
// 타입 : 지역변수 p(포인터)를 선언한다.
// typename T::DWORD * p; // => 타입으로 해석
return 0;
}
int main()
{
Test t;
foo(t);
return 0;
} | [
"y2jinc@gmail.com"
] | y2jinc@gmail.com |
0db18d302664c698262a44157ae9cc65ab8f6261 | 975d70d51334a1a231116fa167e8d3c89f0bd6c8 | /inc/parsers/shaderparser.h | aa42e445c9616ecaae3505daff19ab1ea6986946 | [] | no_license | carolmb/raytracer | e66d26dbaa487d70becdf63b0197ef372aaaed8b | bbeb9609b945a7f636b3d26611470d9f950d86a4 | refs/heads/master | 2021-01-20T03:03:41.383680 | 2017-12-07T21:13:01 | 2017-12-07T21:13:01 | 101,342,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | h | #ifndef SHADERPARSER__
#define SHADERPARSER__
#include "parsers/parser.h"
#include "package.h"
#include <sstream>
class ShaderParser : public Parser {
public:
bool getShader(std::istringstream &reader, Package *p);
};
#endif | [
"carolmedeirosbrito@gmail.com"
] | carolmedeirosbrito@gmail.com |
a1f6ceb45a8a3c0daa42284f375764807acb1727 | 39c1673b3bb230861d2b42bad8d0fbd899d3f4fa | /Contest8/Bai13.cpp | ddc91eea609f93cc33f3ad4ffc1a35940618125e | [] | no_license | trickstarcandina/CTDL | 69b9b205f1b792cce9db894520d4b1a4c0ad9a4a | 5ab3e7e8be6f1a6e2f26e9de880495383d95dd84 | refs/heads/master | 2022-12-28T05:36:00.146268 | 2020-10-17T08:51:39 | 2020-10-17T08:51:39 | 304,835,997 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,873 | cpp | #include <bits/stdc++.h>
using namespace std;
bool F[100001];
bool check(int n){
priority_queue<int> q;
while(n){
q.push(n%10);
n/=10;
}
if(!q.empty() && q.top()>5)
return false;
else{
while(!q.empty()){
int temp=q.top();
q.pop();
if(!q.empty() && q.top()==temp)
return false;
}
}
return true;
}
int main() {
int t; cin>>t;
for(int i=0;i<=100000;i++)
F[i]=check(i);
while(t--){
int l,r;
cin>>l>>r;
int d=0;
for(int i=l;i<=r;i++)
if(F[i]==true) d++;
cout<<d<<endl;
}
return 0;
}
/*
Trickstar Candina
_,add8ba,
,d888888888b,
d8888888888888b _,ad8ba,_
d888888888888888) ,d888888888b,
I8888888888888888 _________ ,8888888888888b
__________`Y88888888888888P"""""""""""baaa,__ ,888888888888888,
,adP"""""""""""9888888888P""^ ^""Y8888888888888888I
,a8"^ ,d888P"888P^ ^"Y8888888888P'
,a8^ ,d8888' ^Y8888888P'
a88' ,d8888P' I88P"^
,d88' d88888P' "b,
,d88' d888888' `b,
,d88' d888888I `b,
d88I ,8888888' ___ `b,
,888' d8888888 ,d88888b, ____ `b,
d888 ,8888888I d88888888b, ,d8888b, `b
,8888 I8888888I d8888888888I ,88888888b 8,
I8888 88888888b d88888888888' 8888888888b 8I
d8886 888888888 Y888888888P' Y8888888888, ,8b
88888b I88888888b `Y8888888^ `Y888888888I d88,
Y88888b `888888888b, `""""^ `Y8888888P' d888I
`888888b 88888888888b, `Y8888P^ d88888
Y888888b ,8888888888888ba,_ _______ `""^ ,d888888
I8888888b, ,888888888888888888ba,_ d88888888b ,ad8888888I
`888888888b, I8888888888888888888888b, ^"Y888P"^ ____.,ad88888888888I
88888888888b,`888888888888888888888888b, "" ad888888888888888888888'
8888888888888698888888888888888888888888b_,ad88ba,_,d88888888888888888888888
88888888888888888888888888888888888888888b,`"""^ d8888888888888888888888888I
8888888888888888888888888888888888888888888baaad888888888888888888888888888'
Y8888888888888888888888888888888888888888888888888888888888888888888888888P
I888888888888888888888888888888888888888888888P^ ^Y8888888888888888888888'
`Y88888888888888888P88888888888888888888888888' ^88888888888888888888I
`Y8888888888888888 `8888888888888888888888888 8888888888888888888P'
`Y888888888888888 `888888888888888888888888, ,888888888888888888P'
`Y88888888888888b `88888888888888888888888I I888888888888888888'
"Y8888888888888b `8888888888888888888888I I88888888888888888'
"Y88888888888P `888888888888888888888b d8888888888888888'
^""""""""^ `Y88888888888888888888, 888888888888888P'
"8888888888888888888b, Y888888888888P^
`Y888888888888888888b `Y8888888P"^
"Y8888888888888888P `""""^
`"YY88888888888P'
^""""""""'
*/ | [
"61593963+rinnegan101220@users.noreply.github.com"
] | 61593963+rinnegan101220@users.noreply.github.com |
00396fb36f1b1729bcef761a1e92f7e369343a26 | 254ed88cbbe5616af024b2e6abb567433f16892c | /assignments and info/assn12/Dijkstra.h | 917910dcc0c01c0130c639d325e5771a2090cbf5 | [] | no_license | TheRizz/CS1D | afab853f96485573295c6eca55887e7f7c8e4902 | 6223f5bcf88020071bb224a8c3d89a9a534d62aa | refs/heads/master | 2020-06-21T14:47:36.443385 | 2019-07-18T01:00:30 | 2019-07-18T01:00:30 | 197,484,217 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,711 | h | #ifndef DIJKSTRA_H_
#define DIJKSTRA_H_
#define INFINITY 9999
#include "header.h"
// Graph utilizing Dijkstra's Algorithm
class Dijkstra
{
public:
void initArray();
void read();
void initialize();
int getClosestUnmarkedNode();
void calculateDistance();
void output();
void printPath(int);
private:
int adjMatrix[12][12];
int predecessor[15],distance[15];
bool mark[15];
int source;
int numOfVertices;
};
// Initializes the matrix
void Dijkstra::initialize()
{
numOfVertices = 12;
source = 2;
for(int i=0;i<numOfVertices;i++)
{
mark[i] = false;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance[source]= 0;
}
// Finds the closest unmarked node
int Dijkstra::getClosestUnmarkedNode()
{
int minDistance = INFINITY;
int closestUnmarkedNode;
for(int i=0;i<numOfVertices;i++)
{
if((!mark[i]) && ( minDistance >= distance[i]))
{
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}
// Calculates the shortest distance
void Dijkstra::calculateDistance()
{
initialize();
int closestUnmarkedNode;
int count = 0;
while(count < numOfVertices)
{
closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = true;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && (inMatrix[closestUnmarkedNode][i]>0) )
{
if(distance[i] > distance[closestUnmarkedNode]+inMatrix[closestUnmarkedNode][i])
{
distance[i] = distance[closestUnmarkedNode]+inMatrix[closestUnmarkedNode][i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
}
// Prints the flight path - recursive function
void Dijkstra::printPath(int node)
{
if(node == source)
cout<< AirPorts[node] <<"..";
else if(predecessor[node] == -1)
cout<<"No path from “<<source<<”to "<<AirPorts[node] <<endl;
else
{
printPath(predecessor[node]);
cout<<AirPorts[node]<<"..";
}
}
// Outputs flight path
void Dijkstra::output()
{
cout <<"//////////////////////////////////////////////////////////////////\n"
" Dijkstra's Algorithm \n"
"/////////////////////////////////////////////////////////////////\n\n";
for(int i=0;i<numOfVertices;i++)
{
if(i == source)
cout<<AirPorts[source]<<".."<<AirPorts[source];
else
printPath(i);
cout << endl << "DISTANCE: "<<distance[i] << " MILES" << endl << endl;
}
}
#endif /* DIJKSTRA_H_ */ | [
"TheRizz@users.noreply.github.com"
] | TheRizz@users.noreply.github.com |
2d8134903779baa39fe6d022e20fc65768814d87 | d54242a0f60842bf3f4906748c6aebb635ffb013 | /IDE_src/11_example_1/11_example_1.ino | 89215a082d11b6b99c310c607b1dc8f26e08325b | [] | no_license | D4m1nK1m/kmu-sw-ied | 456c4ee3af4174a08459e96c4a356ee1f5616d84 | 050afa47c4d76ac134e63e2ae6ca0b03887023d2 | refs/heads/master | 2023-01-27T11:55:07.169070 | 2020-12-10T15:39:11 | 2020-12-10T15:39:11 | 294,613,302 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,039 | ino | #include <Servo.h>
// Arduino pin assignment
#define PIN_LED 9
#define PIN_SERVO 10
#define PIN_TRIG 12
#define PIN_ECHO 13
// configurable parameters
#define SND_VEL 346.0 // sound velocity at 24 celsius degree (unit: m/s)
#define INTERVAL 25 // sampling interval (unit: ms)
#define _DIST_MIN 180 // minimum distance to be measured (unit: mm)
#define _DIST_MAX 400 // maximum distance to be measured (unit: mm)
#define _DUTY_MIN 550 // servo full clockwise position (0 degree)
#define _DUTY_NEU 1500 // servo neutral position (90 degree)
#define _DUTY_MAX 2400 // servo full counterclockwise position (180 degree)
// global variables
float timeout; // unit: us
float dist_min, dist_max, dist_raw, dist_prev,dist_ema; // unit: mm
unsigned long last_sampling_time; // unit: ms
float scale; // used for pulse duration to distance conversion
Servo myservo;
void setup() {
// initialize GPIO pins
pinMode(PIN_LED,OUTPUT);
pinMode(PIN_TRIG,OUTPUT);
digitalWrite(PIN_TRIG, LOW);
pinMode(PIN_ECHO,INPUT);
myservo.attach(PIN_SERVO);
myservo.writeMicroseconds(_DUTY_NEU);
// initialize USS related variables
dist_min = _DIST_MIN;
dist_max = _DIST_MAX;
timeout = (INTERVAL / 2) * 1000.0; // precalculate pulseIn() timeout value. (unit: us)
dist_raw = dist_prev = 0.0; // raw distance output from USS (unit: mm)
scale = 0.001 * 0.5 * SND_VEL;
// initialize serial port
Serial.begin(57600);
// initialize last sampling time
last_sampling_time = 0;
}
void loop() {
// wait until next sampling time.
// millis() returns the number of milliseconds since the program started. Will overflow after 50 days.
if(millis() < last_sampling_time + INTERVAL) return;
// get a distance reading from the USS
dist_raw = USS_measure(PIN_TRIG,PIN_ECHO);
float a=0.3;
dist_ema = a * dist_raw + (1-a)*dist_ema;
// output the read value to the serial port
// Serial.print("Min:100,Low:180,raw:");
// adjust servo position according to the USS read valudist_emaadd your code here!
if(dist_ema < 180.0) {
myservo.writeMicroseconds(_DUTY_MIN);
analogWrite(PIN_LED, 255);
}
else if(dist_ema > 360.0){
myservo.writeMicroseconds(_DUTY_MAX);
analogWrite(PIN_LED, 255);
}
else {
myservo.writeMicroseconds(_DUTY_MIN +(_DUTY_MAX-_DUTY_MIN)*(dist_ema-180)/180);
analogWrite(PIN_LED, 0);
}
Serial.print("Min:100,raw:");
Serial.print(dist_raw);
Serial.print(",ema:");
Serial.print(dist_ema);
Serial.print(",servo:");
Serial.print(myservo.read());
Serial.println(",Max:400");
// update last sampling time
last_sampling_time += INTERVAL;
}
// get a distance reading from USS. return value is in millimeter.
float USS_measure(int TRIG, int ECHO)
{
float reading;
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
reading = pulseIn(ECHO, HIGH, timeout) * scale; // unit: mm
if(reading < dist_min || reading > dist_max) reading = 0.0; // return 0 when out of range.
if(reading == 0.0) reading = dist_prev;
else dist_prev = reading;
return reading;
}
| [
"adgdsda@naver.com"
] | adgdsda@naver.com |
fa58d8daf53eaafde3e29a648b4dc676a2b5b93d | 73c6d103352abf45cad913ab900592cbc0befb6d | /ex01/RadScorpion.cpp | 6bdeb20520d3e398016331a10f3214c2df5810dd | [] | no_license | Spontox42/piscine_cpp_d10 | c43e912ad597a6454f87c6125b8451b5931598d2 | 98fd3d8ebab440ec13440e0844f07f7900813bcf | refs/heads/master | 2016-08-12T12:18:31.976358 | 2016-01-18T11:06:54 | 2016-01-18T11:06:54 | 49,951,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | /*
** RadScorpion.cpp for RadScorpion/home/petit_x/Epitech/rendu/piscine_cpp/piscine_cpp_d10/ex01/RadScorpion.cpp
**
** Made by petit_x - Marlon Petit
** Login < petit_x@epitech.net >
**
** Started on Fri Jan 15 12:12:40 2016 petit_x - Marlon Petit
** Last update Mon Jan 18 12:06:34 2016 Marlon Petit
*/
#include "RadScorpion.hh"
RadScorpion::RadScorpion() : AEnemy(80, "RadScorpion")
{
std::cout << "* click click click *" << std::endl;
}
RadScorpion::~RadScorpion()
{
std::cout << "* SPROTCH *" << std::endl;
}
void RadScorpion::takeDamage(int damage)
{
if (damage >= 0)
this->hp_ -= damage;
}
| [
"petit_x@epitech.eu"
] | petit_x@epitech.eu |
b0397d72bd11593e85704824cffe30f269ee9ebe | efbe79479f3e9c556a69b5e8c7bae4b4c6098904 | /c++/classes/main.cpp | af690602c66ecdd886826710caf6e156df412e5c | [
"MIT"
] | permissive | comphonia/mini-projects | f0a72d1d91c39a5fad63f69fb077dffb5e38fe8c | fb7e73d68adf6e18284b861de215ea61813a64f7 | refs/heads/master | 2022-12-10T05:07:38.470752 | 2019-07-28T19:31:28 | 2019-07-28T19:31:28 | 159,382,592 | 0 | 0 | MIT | 2022-12-09T13:36:42 | 2018-11-27T18:42:32 | C++ | UTF-8 | C++ | false | false | 744 | cpp | #include <iostream>
#include <string>
using namespace std;
#include "bankaccount.h"
int main()
{
int n;
bankaccount b1 = bankaccount(1,"John");
cout << "Account for " << b1.get_name() << " with id: " << b1.get_id() << " has been created. " << endl;
b1.deposit(200);
b1.withdrawal(50);
cout << "Balance for account with id " << b1.get_id() << " is: " << b1.get_balance() << endl << endl;
bankaccount b2 = bankaccount(2,"Alice");
cout << "Account for " << b2.get_name() << " with id: " << b2.get_id() << " has been created. " << endl;
b1.set_id(2);
b2.deposit(50);
b2.withdrawal(10);
cout << "Balance for account with id " << b2.get_id() << " is: " << b2.get_balance() << endl << endl;
} | [
"online.comphonia@gmail.com"
] | online.comphonia@gmail.com |
779de56328e266509b0ca73770049e92149768f3 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /dcdn/include/alibabacloud/dcdn/model/CreateDcdnSLSRealTimeLogDeliveryRequest.h | ee8ace69bc361acf2c818bfadb0eca18d01de4b7 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,407 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_DCDN_MODEL_CREATEDCDNSLSREALTIMELOGDELIVERYREQUEST_H_
#define ALIBABACLOUD_DCDN_MODEL_CREATEDCDNSLSREALTIMELOGDELIVERYREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/dcdn/DcdnExport.h>
namespace AlibabaCloud
{
namespace Dcdn
{
namespace Model
{
class ALIBABACLOUD_DCDN_EXPORT CreateDcdnSLSRealTimeLogDeliveryRequest : public RpcServiceRequest
{
public:
CreateDcdnSLSRealTimeLogDeliveryRequest();
~CreateDcdnSLSRealTimeLogDeliveryRequest();
std::string getSLSLogStore()const;
void setSLSLogStore(const std::string& sLSLogStore);
std::string getSLSProject()const;
void setSLSProject(const std::string& sLSProject);
std::string getBusinessType()const;
void setBusinessType(const std::string& businessType);
std::string getSLSRegion()const;
void setSLSRegion(const std::string& sLSRegion);
std::string getProjectName()const;
void setProjectName(const std::string& projectName);
std::string getDomainName()const;
void setDomainName(const std::string& domainName);
std::string getSamplingRate()const;
void setSamplingRate(const std::string& samplingRate);
std::string getDataCenter()const;
void setDataCenter(const std::string& dataCenter);
long getOwnerId()const;
void setOwnerId(long ownerId);
private:
std::string sLSLogStore_;
std::string sLSProject_;
std::string businessType_;
std::string sLSRegion_;
std::string projectName_;
std::string domainName_;
std::string samplingRate_;
std::string dataCenter_;
long ownerId_;
};
}
}
}
#endif // !ALIBABACLOUD_DCDN_MODEL_CREATEDCDNSLSREALTIMELOGDELIVERYREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
bc25b1feab159053602951a307014097b402ffc2 | 81fe7f2faea91785ee13cb0297ef9228d832be93 | /HackerRank/Contests/101Hack51/train_trip.cpp | b3874841ea673dd48a33c90d0c74638b9961a150 | [] | no_license | blegloannec/CodeProblems | 92349c36e1a35cfc1c48206943d9c2686ea526f8 | 77fd0fa1f1a519d4d55265b9a7abf12f1bd7d19e | refs/heads/master | 2022-05-16T20:20:40.578760 | 2021-12-30T11:10:25 | 2022-04-22T08:11:07 | 54,330,243 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,677 | cpp | #include <iostream>
#include <vector>
using namespace std;
typedef long long ent;
int n,v1,v2,v3;
ent a,b,c;
vector< vector<int> > G;
vector<int> D,A(8); // depth, mask to ancestor
int dfs(int u=0, int u0=-1) {
int mask = 0;
for (int i=1; i<=4; i<<=1)
if (u==A[i]) mask |= i;
for (auto iv=G[u].begin(); iv!=G[u].end(); ++iv)
if (*iv!=u0) {
D[*iv] = D[u]+1;
mask |= dfs(*iv,u);
}
if (mask>0 && A[mask]<0) A[mask] = u;
return mask;
}
/*
the DFS identifies the reduced tree:
0
|
(7)
---------
| |
(m1|m2) |
----- |
| | |
m1 m2 m3
then the optimal path falls down into one of
the 3 cases below (with the associated formulas)
(NB: the editorial suggests either Dijkstra in the
configurations graph of size 6^3, or a brute-force
enumeration of all the possible paths in the
reduced tree of size 6, instead of the formulas)
*/
ent path0(int m1, int m2, int m3) {
// m1,m2 ~~ a ~~> m1|m2 ~~ b ~~> 7
// either m3 ~~ a ~~> 7
// or m1&m2 ~~ b ~~> m3 ~~ c ~~> 7
// m1&m2&m3 ~~ c ~~> 0
return
a * (D[A[m1]]-D[A[m1|m2]] + D[A[m2]]-D[A[m1|m2]]) +
b * (D[A[m1|m2]]-D[A[7]]) +
min(a,b+c) * (D[A[m3]]-D[A[7]]) +
c * D[A[7]];
}
ent path1(int m1, int m2, int m3) {
// m1,m3 ~~ a ~~> m1|m2
// m1&m3 ~~ b ~~> m2
// m1&m2&m3 ~~ c ~~> 0
return
a * (D[A[m1]]-D[A[m1|m2]] + D[A[m3]]-D[A[7]] + D[A[m1|m2]]-D[A[7]]) +
b * (D[A[m2]]-D[A[m1|m2]]) +
c * D[A[m2]];
}
ent path2(int m1, int m2, int m3) {
// m1,m2,m3 ~~ a ~~> m1|m2
// m1&m2&m3 ~~ c ~~> 0
return
a * (D[A[m1]]-D[A[m1|m2]] + D[A[m2]]-D[A[m1|m2]] + D[A[m3]]-D[A[7]] + D[A[m1|m2]]-D[A[7]]) +
c * D[A[m1|m2]];
}
int main() {
int T;
cin >> T;
for (int t=0; t<T; ++t) {
cin >> n;
cin >> a >> b >> c;
cin >> v1 >> v2 >> v3;
--v1; --v2; --v3;
G.resize(n);
for (int i=0; i<n-1; ++i) {
int u,v;
cin >> u >> v; --u; --v;
G[u].push_back(v);
G[v].push_back(u);
}
// value modifications to simplify the formulas
b = min(b,2*a);
c = min(c,b+a);
fill(A.begin(),A.end(),-1);
int m1 = 1, m2 = 2, m3 = 4;
A[m1] = v1; A[m2] = v2; A[m3] = v3;
D.resize(n,0);
dfs();
for (int i=1; i<7; ++i)
if (A[i]<0) A[i] = A[7];
// swap if needed so that A[m1] and A[m2] have the deepest LCA
if (A[m1|m3]!=A[7]) swap(m2,m3);
else if (A[m2|m3]!=A[7]) swap(m1,m3);
// formulas
ent res = min(min(path0(m1,m2,m3),path2(m1,m2,m3)),min(path1(m1,m2,m3),path1(m2,m1,m3)));
cout << res << endl;
// cleaning
G.clear();
D.clear();
}
return 0;
}
| [
"blg@gmx.com"
] | blg@gmx.com |
2505b4efd5339ce36936e68e8649b651632397d7 | 6de02f09f9b0c8431683a6f65d164c897300c4ce | /Include/Aspen/Throw.hpp | 7bf66a622281348141c8295eb5be8f4d7d393340 | [
"Apache-2.0"
] | permissive | andrei-sa/aspen | 1bee42d69e7e7c18f337e6c4fdcfd87d07647149 | 6644663fc19a83fba0603dc4bbd6dbe71cfd55aa | refs/heads/master | 2022-04-23T01:49:58.596882 | 2020-04-24T17:59:32 | 2020-04-24T17:59:32 | 258,588,166 | 0 | 0 | Apache-2.0 | 2020-04-24T18:12:29 | 2020-04-24T18:12:28 | null | UTF-8 | C++ | false | false | 1,901 | hpp | #ifndef ASPEN_THROW_HPP
#define ASPEN_THROW_HPP
#include <exception>
#include <type_traits>
#include <utility>
#include "Aspen/State.hpp"
#include "Aspen/Traits.hpp"
namespace Aspen {
/**
* Implements a reactor that unconditionally throws.
* @param <T> The type of reactor to evaluate to.
*/
template<typename T>
class Throw {
public:
using Type = T;
/**
* Constructs a Throw.
* @param exception The exception to throw.
*/
explicit Throw(std::exception_ptr exception);
/**
* Constructs a Throw.
* @param exception The exception to throw.
*/
template<typename E>
Throw(E exception);
State commit(int sequence) noexcept;
eval_result_t<Type> eval() const;
private:
std::exception_ptr m_exception;
};
/**
* Returns a reactor that always throws an exception.
* @param exception The exception to throw.
*/
template<typename T>
auto throws(std::exception_ptr exception) {
return Throw<T>(std::move(exception));
}
/**
* Returns a reactor that always throws an exception.
* @param exception The exception to throw.
*/
template<typename T, typename E>
auto throws(E exception) {
return Throw<T>(std::move(exception));
}
template<typename T>
Throw<T>::Throw(std::exception_ptr exception)
: m_exception(std::move(exception)) {}
template<typename T>
template<typename E>
Throw<T>::Throw(E exception)
: Throw(std::make_exception_ptr(std::move(exception))) {}
template<typename T>
State Throw<T>::commit(int sequence) noexcept {
return State::COMPLETE_EVALUATED;
}
template<typename T>
eval_result_t<typename Throw<T>::Type> Throw<T>::eval() const {
std::rethrow_exception(m_exception);
if constexpr(!std::is_same_v<Type, void>) {
return *static_cast<const Type*>(nullptr);
}
}
}
#endif
| [
"kamal@eidolonsystems.com"
] | kamal@eidolonsystems.com |
da357c9d635b165bf539a8bfcc73111328ba34a3 | 5b706159ca28932d253358792cd3ea0888d143d4 | /cxx/tbb/vs_old_playground/utils.cpp | b4e0052190c3f108e7625e376f65b0783dcd7f13 | [] | no_license | pbertoni89/playground | f198eb778af29725a8a78b2041988737df82fd05 | ed68a1bf93b1ee397985a9092fb603ec14cf1afe | refs/heads/master | 2022-08-18T12:31:01.721809 | 2022-08-06T07:59:52 | 2022-08-06T07:59:52 | 165,248,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | #include "utils.hpp"
#include <iostream>
t_tp tic()
{
return std::chrono::high_resolution_clock::now();
}
double toc(t_tp _tic)
{
return tictoc(_tic, tic());
}
double tictoc(t_tp _tic, t_tp _toc)
{
return (1.e-9) * std::chrono::duration_cast<std::chrono::nanoseconds>(_toc - _tic).count();
}
void toclabel(t_tp tic1, std::string lbl)
{
std::cout << "[" << lbl << "]\t" << std::scientific << toc(tic1) << std::endl;
}
long fibonacci_serial(long n)
{
if (n<2)
{
return n;
}
else
{
return fibonacci_serial(n-1) + fibonacci_serial(n-2);
}
}
| [
"pbertoni@x-next.com"
] | pbertoni@x-next.com |
1fa00c42d5410e3922d3e02cc418855d31734808 | dccf5f6339baba548a83a7d390b63e285c9f0581 | /chrome/browser/resource_coordinator/tab_lifecycle_unit_source.h | 09c23058a7f4fca38c073b5ba3e9a65943b15b5a | [
"BSD-3-Clause"
] | permissive | Trailblazer01010111/chromium | 83843c9e45abb74a1a23df7302c1b274e460aee2 | 3fd9a73f1e93ce041a4580c20e30903ab090e95c | refs/heads/master | 2022-12-06T22:58:46.158304 | 2018-05-12T09:55:21 | 2018-05-12T09:55:21 | 133,138,333 | 1 | 0 | null | 2018-05-12T11:07:57 | 2018-05-12T11:07:56 | null | UTF-8 | C++ | false | false | 4,638 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_LIFECYCLE_UNIT_SOURCE_H_
#define CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_LIFECYCLE_UNIT_SOURCE_H_
#include <memory>
#include "base/macros.h"
#include "base/observer_list.h"
#include "chrome/browser/resource_coordinator/lifecycle_unit_source_base.h"
#include "chrome/browser/resource_coordinator/page_signal_receiver.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/browser/ui/browser_tab_strip_tracker.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
class TabStripModel;
namespace content {
class WebContents;
}
namespace resource_coordinator {
class TabLifecycleObserver;
class TabLifecycleUnitExternal;
// Creates and destroys LifecycleUnits as tabs are created and destroyed.
class TabLifecycleUnitSource : public BrowserListObserver,
public LifecycleUnitSourceBase,
public PageSignalObserver,
public TabStripModelObserver {
public:
TabLifecycleUnitSource();
~TabLifecycleUnitSource() override;
static TabLifecycleUnitSource* GetInstance();
// Returns the TabLifecycleUnitExternal instance associated with
// |web_contents|, or nullptr if |web_contents| isn't a tab.
TabLifecycleUnitExternal* GetTabLifecycleUnitExternal(
content::WebContents* web_contents) const;
// Adds / removes an observer that is notified when the discarded or auto-
// discardable state of a tab changes.
void AddTabLifecycleObserver(TabLifecycleObserver* observer);
void RemoveTabLifecycleObserver(TabLifecycleObserver* observer);
// Pretend that |tab_strip| is the TabStripModel of the focused window.
void SetFocusedTabStripModelForTesting(TabStripModel* tab_strip);
class TabLifecycleUnitHolder;
private:
friend class TabLifecycleUnitTest;
class TabLifecycleUnit;
// Returns the TabLifecycleUnit instance associated with |web_contents|, or
// nullptr if |web_contents| isn't a tab.
TabLifecycleUnit* GetTabLifecycleUnit(
content::WebContents* web_contents) const;
// Returns the TabStripModel of the focused browser window, if any.
TabStripModel* GetFocusedTabStripModel() const;
// Updates the focused TabLifecycleUnit.
void UpdateFocusedTab();
// Updates the focused TabLifecycleUnit to |new_focused_lifecycle_unit|.
// TabInsertedAt() calls this directly instead of UpdateFocusedTab() because
// the active WebContents of a TabStripModel isn't updated when
// TabInsertedAt() is called.
void UpdateFocusedTabTo(TabLifecycleUnit* new_focused_lifecycle_unit);
// TabStripModelObserver:
void TabInsertedAt(TabStripModel* tab_strip_model,
content::WebContents* contents,
int index,
bool foreground) override;
void TabDetachedAt(content::WebContents* contents, int index) override;
void ActiveTabChanged(content::WebContents* old_contents,
content::WebContents* new_contents,
int index,
int reason) override;
void TabReplacedAt(TabStripModel* tab_strip_model,
content::WebContents* old_contents,
content::WebContents* new_contents,
int index) override;
void TabChangedAt(content::WebContents* contents,
int index,
TabChangeType change_type) override;
// BrowserListObserver:
void OnBrowserSetLastActive(Browser* browser) override;
void OnBrowserNoLongerActive(Browser* browser) override;
// PageSignalObserver:
void OnLifecycleStateChanged(content::WebContents* web_contents,
mojom::LifecycleState state) override;
// Tracks the BrowserList and all TabStripModels.
BrowserTabStripTracker browser_tab_strip_tracker_;
// Pretend that this is the TabStripModel of the focused window, for testing.
TabStripModel* focused_tab_strip_model_for_testing_ = nullptr;
// The currently focused TabLifecycleUnit. Updated by UpdateFocusedTab().
TabLifecycleUnit* focused_lifecycle_unit_ = nullptr;
// Observers notified when the discarded or auto-discardable state of a tab
// changes.
base::ObserverList<TabLifecycleObserver> tab_lifecycle_observers_;
DISALLOW_COPY_AND_ASSIGN(TabLifecycleUnitSource);
};
} // namespace resource_coordinator
#endif // CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_LIFECYCLE_UNIT_SOURCE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e7c9adb656023bce4f234cba55c4f5c59b89ed76 | 1a77b5eac40055032b72e27e720ac5d43451bbd6 | /フォーム対応/VisualC++/MFC/Chap9/Dr64/Dr64/Dr64.h | 53012bcc2fcbbd40d33928e4dbd25eba71ab4e57 | [] | no_license | motonobu-t/algorithm | 8c8d360ebb982a0262069bb968022fe79f2c84c2 | ca7b29d53860eb06a357eb268f44f47ec9cb63f7 | refs/heads/master | 2021-01-22T21:38:34.195001 | 2017-05-15T12:00:51 | 2017-05-15T12:01:00 | 85,451,237 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 622 | h | // Dr64.h : Dr64 アプリケーションのメイン ヘッダー ファイル
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH に対してこのファイルをインクルードする前に 'stdafx.h' をインクルードしてください"
#endif
#include "resource.h" // メイン シンボル
// CDr64App:
// このクラスの実装については、Dr64.cpp を参照してください。
//
class CDr64App : public CWinApp
{
public:
CDr64App();
// オーバーライド
public:
virtual BOOL InitInstance();
// 実装
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CDr64App theApp; | [
"rx_78_bd@yahoo.co.jp"
] | rx_78_bd@yahoo.co.jp |
70afcbc2aa00d5cea3b4156ad646bfecc06d2b30 | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/geometry/algorithms/detail/interior_iterator.hpp | 81c0f41c3cdc4c4325b6370184590b73113d5cf8 | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | hpp | // Boost.Geometry
// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
#include <boost/range/iterator.hpp>
#include <boost/range/value_type.hpp>
#include <boost/geometry/core/interior_type.hpp>
namespace boost
{
namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail
{
/*!
\brief Structure defining the type of interior rings iterator
\note If the Geometry is const, const iterator is defined.
\tparam Geometry \tparam_geometry
*/
template <typename Geometry>
struct interior_iterator
{
typedef typename boost::range_iterator
<
typename geometry::interior_type<Geometry>::type
>::type type;
};
template <typename BaseT, typename T>
struct copy_const
{
typedef T type;
};
template <typename BaseT, typename T>
struct copy_const<BaseT const, T>
{
typedef T const type;
};
template <typename Geometry>
struct interior_ring_iterator
{
typedef typename boost::range_iterator
<
typename copy_const
<
typename geometry::interior_type<Geometry>::type,
typename boost::range_value
<
typename geometry::interior_type<Geometry>::type
>::type
>::type
>::type type;
};
} // namespace detail
#endif // DOXYGEN_NO_DETAIL
}
} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
| [
"k.melekhin@gmail.com"
] | k.melekhin@gmail.com |
fb675e05547c9ab5d1ccf3265bc51faa87c030a2 | 726ee28589b3173163a2a7a02354eedadd2ef14d | /prime generation, sieve of Eratosthenes, linear sieve.cpp | 4bf7c6c6c93816a037eef8e432a7fbb071cfb72a | [] | no_license | yenting-chen/Algorithms-and-Data-Structures | e048e3e96746ef597ddc90e9cf76d0895ee3c373 | 3f075b58c49ea0e4b1a5a0dedb16d0f9dc92a426 | refs/heads/main | 2023-01-14T07:15:09.373727 | 2020-11-28T13:35:32 | 2020-11-28T13:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | cpp | /*
prime generation, sieve of Eratosthenes, linear sieve
*/
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<algorithm>
#include<vector>
#include<string>
#include<string.h>
#include<ctype.h>
using namespace std;
typedef long long lld;
#include<ctime>
vector<int> normal(const int N)
{
int cnt = 0;
vector<bool> isp(N, true);
vector<int> p;
for (int i = 2; i<N; i++)
{
if (isp[i])
{
p.push_back(i);
for (lld j = (lld)i*i; j < N; j += i)
{
cnt++;
isp[j] = false;
}
}
}
printf("cnt=%d\n", cnt);
return p;
}
vector<int> linear(const int N)
{
int cnt = 0;
vector<bool> isp(N, true);
vector<int> p;
for (int i = 2; i<N; i++)
{
if (isp[i])
p.push_back(i);
for (int j = 0; j < p.size() && (lld)p[j]*i<N; j++)
{
cnt++;
isp[p[j]*i] = false;
if (i%p[j] == 0)
break;
}
}
printf("cnt=%d\n",cnt);
return p;
}
int main(int argc, const char* argv[])
{
const int N = argc>1 ? atoi(argv[1]) : 1000000;
time_t t = clock();
vector<int> prime_n = normal(N);
printf("%lu\n", clock() - t);
t = clock();
vector<int> prime_l = linear(N);
printf("%lu\n", clock() - t);
if (prime_n != prime_l)
printf("Error!\n");
printf("%d %d\n", prime_n.size(), prime_l.size());
}
| [
"ian96969696@gmail.com"
] | ian96969696@gmail.com |
be1f77b7e2c5db77621b51a2ea87470137abe139 | e51e82ee1846ac922fcf7da7b0980b538eb7a0ff | /server.cpp | 6d1037f3f3acf44bb731362084ace0a0541da365 | [
"MIT"
] | permissive | bwackwat/app-daemon | a01daeb319b8259ff507cc6b0b613bce9dbaaee9 | c5979aa6df11687797d3e98ff42aa2292ebb7ee0 | refs/heads/master | 2021-01-10T12:58:21.939115 | 2016-10-17T18:11:54 | 2016-10-17T18:11:54 | 49,697,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,910 | cpp | #include <memory>
#include <iostream>
#include <fstream>
#include <atomic>
#include <thread>
#include <set>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "adhost.cpp"
#include "server.hpp"
#include "bcast.hpp"
#include "conn.hpp"
using namespace boost;
void Server::do_accept(){
acceptor_.async_accept(socket_, [this](system::error_code ec){
if (ec){
std::cout << "async_accept error (" << ec.value() << "): " << ec.message() << std::endl;
return;
}
std::make_shared<Connection>(this, std::move(socket_))->start();
do_accept();
});
//std::cout << "Accepting..." << std::endl;
}
void Server::master_heartbeat_broadcast(){
std::cout << "Master Heartbeat broadcasting..." << std::endl;
asio::io_service broadcast_service;
std::string request = "";
request.append(Connection::packet_types[3]);
request.append("\n");
for (auto& host : appd_hosts){
if (host.port != server_port){
broadcasters.emplace_back(this, &host, broadcast_service, &request);
}
}
try{
broadcast_service.run();
}catch (std::exception& e){
std::cerr << "broadcast_service.run() exception: " << e.what() << "\n";
}
std::cout << "Master Heartbeat broadcast complete!" << std::endl;
broadcasters.clear();
master_heartbeat_timer.expires_from_now(posix_time::seconds(2));
master_heartbeat_timer.async_wait(bind(&Server::master_heartbeat_broadcast, this));
}
void Server::master_request_broadcast(){
std::cout << "Master Heartbeat timed out, broadcasting Master Request..." << std::endl;
asio::io_service broadcast_service;
yes_votes = 0;
no_votes = 0;
std::string request = "";
request.append(Connection::packet_types[0]);
request.append("\n");
master_request_time = chrono::time_point_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now()).time_since_epoch().count();
request.append(std::to_string(master_request_time));
request.append("\n");
for (auto& host : appd_hosts){
if (host.port != server_port){
broadcasters.emplace_back(this, &host, broadcast_service, &request);
}
}
try{
broadcast_service.run();
}catch (std::exception& e){
std::cerr << "broadcast_service.run() exception: " << e.what() << "\n";
}
std::cout << "Master Request broadcast complete! Votes: " << yes_votes.load() << " YES " << no_votes.load() << " NO." << std::endl;
broadcasters.clear();
if (yes_votes.load() > no_votes.load()){
std::cout << "-------->>>>>>> this IS the master" << std::endl;
is_master = true;
master_heartbeat_broadcast();
}else{
std::cout << "-------->>>>>>> this IS NOT the master" << std::endl;
master_request_time = 0;
}
master_heartbeat_timeout_timer.expires_from_now(posix_time::seconds(4));
master_heartbeat_timeout_timer.async_wait(bind(&Server::master_heartbeat_timeout, this, asio::placeholders::error));
}
void Server::master_heartbeat_timeout(const system::error_code& ec){
if (ec){
if (ec == asio::error::operation_aborted){
//Trashed this timerwith cancel();
}else{
std::cout << "async_accept error (" << ec.value() << "): " << ec.message() << std::endl;
}
}else if (!is_master){
if (broadcast_thread.joinable()){
broadcast_thread.join();
}
broadcast_thread = std::thread(&Server::master_request_broadcast, this);
}
}
Server::Server(int port)
: server_port(port),
acceptor_(io_service_, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), server_port)),
socket_(io_service_),
master_heartbeat_timer(io_service_),
master_heartbeat_timeout_timer(io_service_){
std::ifstream infile("daemons.list", std::ifstream::in);
if(!infile.good()){
std::cerr << "No daemons.list! Bye." << std::endl;
return;
}
std::string line;
while (std::getline(infile, line)){
AppDaemonHost next;
if (strcmp(line.c_str(), "tcp") == 0){
next.type = TCP;
}else{
next.type = IDK;
}
if (!std::getline(infile, line)){
std::cout << "invalid daemon address in list" << std::endl;
//throw std::exception("Invalid daemon list.");
}
next.hostname = line;
if (!std::getline(infile, line)){
std::cout << "invalid daemon port in list" << std::endl;
//throw std::exception("Invalid daemon list.");
}
next.port = atoi(line.c_str());
std::cout << "Host App Daemon @ " << next.to_string() << std::endl;
appd_hosts.push_back(next);
}
infile.close();
master_heartbeat_timeout_timer.expires_from_now(posix_time::seconds(4));
master_heartbeat_timeout_timer.async_wait(bind(&Server::master_heartbeat_timeout, this, asio::placeholders::error));
try{
do_accept();
}catch (std::exception& e){
std::cerr << "do_accept() exception: " << e.what() << "\n";
}
try{
io_service_.run();
}catch (std::exception& e){
std::cerr << "io_service_.run() exception: " << e.what() << "\n";
}
}
| [
"root@bwackwat-deb-dev.localhost"
] | root@bwackwat-deb-dev.localhost |
e2110233ae3b4eb4519806a574bfc8cbb21a6a74 | 5f140905236871bd1d575eeaad5b6aa0a34d7b9e | /UnrealCPPProjectile.h | 45cebaffeb0a1d1d54ca8af6bcee4b5cba222b90 | [
"MIT"
] | permissive | aurodev/unrealcpp | cf09841d9b83a99e0083c4e31e01f486794fe5b1 | f22bf95dc50bbf1f0b00c17c6f01ae821a92c363 | refs/heads/master | 2023-03-16T21:42:13.772264 | 2022-12-28T10:09:50 | 2022-12-28T10:09:50 | 272,730,819 | 0 | 0 | MIT | 2020-06-16T14:31:44 | 2020-06-16T14:31:43 | null | UTF-8 | C++ | false | false | 1,091 | h | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/Actor.h"
#include "UnrealCPPProjectile.generated.h"
UCLASS(config=Game)
class AUnrealCPPProjectile : public AActor
{
GENERATED_BODY()
/** Sphere collision component */
UPROPERTY(VisibleDefaultsOnly, Category=Projectile)
class USphereComponent* CollisionComp;
/** Projectile movement component */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true"))
class UProjectileMovementComponent* ProjectileMovement;
public:
AUnrealCPPProjectile();
/** called when projectile hits something */
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
/** Returns CollisionComp subobject **/
FORCEINLINE class USphereComponent* GetCollisionComp() const { return CollisionComp; }
/** Returns ProjectileMovement subobject **/
FORCEINLINE class UProjectileMovementComponent* GetProjectileMovement() const { return ProjectileMovement; }
};
| [
"hmcguire13@gmail.com"
] | hmcguire13@gmail.com |
53bfd2fe62eec7e4f7ddabee9b2c2aeb08a0756b | c21b082283fbac55516061e3aa42470a673a5490 | /models/sqlobjects/gradeobject.h | 77bc7354f1a79a47c46455d0d0a20e144e6ad835 | [] | no_license | ohahlev/topautocamcpp | e7f102fe9401a66689df6bb26f12fa7a8d41c710 | 29444958853d642b8ef2e48deff6ded86053e681 | refs/heads/master | 2022-12-03T22:57:45.064834 | 2020-08-19T14:40:05 | 2020-08-19T14:40:05 | 278,991,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | h | #ifndef GRADEOBJECT_H
#define GRADEOBJECT_H
#include <TSqlObject>
#include <QSharedData>
class T_MODEL_EXPORT GradeObject : public TSqlObject, public QSharedData
{
public:
int id {0};
QString name;
QDateTime created_at;
QDateTime updated_at;
enum PropertyIndex {
Id = 0,
Name,
CreatedAt,
UpdatedAt,
};
int primaryKeyIndex() const override { return Id; }
int autoValueIndex() const override { return Id; }
QString tableName() const override { return QStringLiteral("grade"); }
private: /*** Don't modify below this line ***/
Q_OBJECT
Q_PROPERTY(int id READ getid WRITE setid)
T_DEFINE_PROPERTY(int, id)
Q_PROPERTY(QString name READ getname WRITE setname)
T_DEFINE_PROPERTY(QString, name)
Q_PROPERTY(QDateTime created_at READ getcreated_at WRITE setcreated_at)
T_DEFINE_PROPERTY(QDateTime, created_at)
Q_PROPERTY(QDateTime updated_at READ getupdated_at WRITE setupdated_at)
T_DEFINE_PROPERTY(QDateTime, updated_at)
};
#endif // GRADEOBJECT_H
| [
"ohahlev@gmail.com"
] | ohahlev@gmail.com |
16a8a21bfdd7b3dff5f780a2439714633425e2de | 621a26b549b625b1dc53f07aeb35e12b91ee9886 | /Templates/kruskalCluster.cpp | a0b44e82e06a6b1347485c0f1b31f3b344f8bcad | [] | no_license | rishirv/competitive-programming | c6524754a4c6142997956022b47f6863ca9d241f | 272911ed86c60d19574e1366ae09d4f1f5429fe1 | refs/heads/master | 2021-08-10T22:17:59.110903 | 2020-05-10T01:33:43 | 2020-05-10T01:33:43 | 177,334,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,227 | cpp | //K-clustering based on Kruskal's algorithm
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
bool comp(const tuple<int, int, int>& a, const tuple<int, int, int>& b){
return get<2>(a) < get<2>(b);
}
ifstream fin ("cluster.in");
vector<tuple<int, int, int>> g;
int n, clusters, space, it=0;
//Union - Find implementation
int parent[501], size[501];
int Find(int i){
if(i == parent[i]) return i;
parent[i] = Find(parent[i]);
return parent[i];
}
bool Union(int x, int y){
int a = Find(x), b = Find(y);
if(a == b) return false;
if(size[a] == size[b]){
size[b]++;
parent[a] = b;
} else if(size[a] < size[b]){
parent[a] = b;
} else{
parent[b] = a;
}
return true;
}
//End Union - Find
void add_edge(){
while(!Union(get<0>(g[it]), get<1>(g[it]))) ++it;
space=get<2>(g[it]);
++it;
clusters--;
}
int main(){
int i, j, k, target;
fin>>n;
cin>>target;
while(fin>>i>>j>>k){
g.push_back(make_tuple(i, j, k));
}
sort(g.begin(), g.end(), comp);
for(int i=1; i<=500; i++){
parent[i] = i;
}
clusters = n;
while(clusters != target){
add_edge();
}
add_edge();
cout<<space<<endl;
} | [
"verma.rishiraj@gmail.com"
] | verma.rishiraj@gmail.com |
4b1c279d4569cc7468c5bd6781e9698a8ef48a10 | bc5e1438ba7171bda36074e6390dbc22ded32b73 | /03.18/.cpp | 569647bb7f4e107facd7617fb65abf424556c878 | [
"MIT"
] | permissive | peiyuefei/study | e8e15dbafccc69e4921dce1cdcb10d936396945d | 27c2e84bb23eecdf05e11b389091572e59cc2aa5 | refs/heads/main | 2023-04-05T05:48:05.344670 | 2021-03-22T08:57:00 | 2021-03-22T08:57:00 | 338,889,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | #include<iostream>
using namespace std;
inline int max(int, int, int);
int main()
{
int i = 10, j = 20, k = 30, m;
m = max(i, j, k);
cout << "max=" << m << endl;
return 0;
}
inline int max(int a, int b, int c)
{
if (b > a)a = b;
if (c > a)a = c;
return a;
} | [
"1662531390@qq.com"
] | 1662531390@qq.com |
687b15ae0fa5e572d49f74cffc09014115732cfa | dbcd2006f283fcb469524d92d884024fa11345ac | /interfaces/kits/js/src/mod_fileio/common_func.h | 614128b75bcee12898b31b430be6463178146785 | [
"Apache-2.0"
] | permissive | openharmony-gitee-mirror/distributeddatamgr_file | 380e4841a943d548f810081d86b661d6b099a9b6 | 1e624bbc3850815fa1b2642c67123b7785bec6a1 | refs/heads/master | 2023-08-20T11:39:22.117760 | 2021-10-25T01:53:50 | 2021-10-25T01:53:50 | 400,051,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | h | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "../common/napi/uni_header.h"
#include <limits>
#include <memory>
#include <tuple>
namespace OHOS {
namespace DistributedFS {
namespace ModuleFileIO {
constexpr int64_t INVALID_POSITION = std::numeric_limits<decltype(INVALID_POSITION)>::max();
struct CommonFunc {
static std::tuple<bool, void *, int64_t, bool, int64_t> GetReadArg(napi_env env,
napi_value readBuf,
napi_value option);
static std::tuple<bool, std::unique_ptr<char[]>, void *, int64_t, bool, int64_t> GetWriteArg(napi_env env,
napi_value argWBuf,
napi_value argOption);
};
} // namespace ModuleFileIO
} // namespace DistributedFS
} // namespace OHOS | [
"mamingshuai1@huawei.com"
] | mamingshuai1@huawei.com |
a13acd1ff69806e8c9825b096cd741962eee15c0 | 108c8178de966c04c7ca7ccbfe00e8cafa8822d3 | /detectNet.cpp | 7e0a03383d3632baad70bfcc8118334ac9bce9a3 | [] | no_license | zn845639326/jetson-inference | cfc05359704ebb2d746a68a48cfba2959760678d | 46771ee283f9c30ab7a6122d69252e21d9acd3ff | refs/heads/master | 2021-01-19T04:54:59.942149 | 2017-04-03T12:32:16 | 2017-04-03T12:32:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,611 | cpp | /*
* http://github.com/dusty-nv/jetson-inference
*/
#include "detectNet.h"
#include "cudaMappedMemory.h"
#include "cudaOverlay.h"
#include "cudaResize.h"
#define OUTPUT_CVG 0
#define OUTPUT_BBOX 1
//#define DEBUG_CLUSTERING
detectNet* detectNet::Create( NetworkType networkType, float threshold )
{
if( networkType == PEDNET_MULTI )
return Create("networks/multiped-500/deploy.prototxt", "networks/multiped-500/snapshot_iter_178000.caffemodel", "networks/multiped-500/mean.binaryproto", threshold );
else if( networkType == FACENET )
return Create("networks/facenet-120/deploy.prototxt", "networks/facenet-120/snapshot_iter_24000.caffemodel", NULL, threshold );
else /*if( networkTYpe == PEDNET )*/
return Create("networks/ped-100/deploy.prototxt", "networks/ped-100/snapshot_iter_70800.caffemodel", "networks/ped-100/mean.binaryproto", threshold );
}
void detectNet::SetClassColor( uint32_t classIndex, float r, float g, float b, float a )
{
if( classIndex >= GetNumClasses() || !mClassColors[0] )
return;
const uint32_t i = classIndex * 4;
mClassColors[0][i+0] = r;
mClassColors[0][i+1] = g;
mClassColors[0][i+2] = b;
mClassColors[0][i+3] = a;
}
// constructor
detectNet::detectNet() : tensorNet()
{
mCoverageThreshold = 0.5f;
mClassColors[0] = NULL; // cpu ptr
mClassColors[1] = NULL; // gpu ptr
}
// destructor
detectNet::~detectNet()
{
}
// Create
detectNet* detectNet::Create( const char* prototxt, const char* model, const char* mean_binary, float threshold, const char* input_blob, const char* coverage_blob, const char* bbox_blob )
{
detectNet* net = new detectNet();
if( !net )
return NULL;
//net->EnableDebug();
std::vector<std::string> output_blobs;
output_blobs.push_back(coverage_blob);
output_blobs.push_back(bbox_blob);
if( !net->LoadNetwork(prototxt, model, mean_binary, input_blob, output_blobs) )
{
printf("detectNet -- failed to initialize.\n");
return NULL;
}
const uint32_t numClasses = net->GetNumClasses();
if( !cudaAllocMapped((void**)&net->mClassColors[0], (void**)&net->mClassColors[1], numClasses * sizeof(float4)) )
return NULL;
for( uint32_t n=0; n < numClasses; n++ )
{
if( n != 1 )
{
net->mClassColors[0][n*4+0] = 0.0f; // r
net->mClassColors[0][n*4+1] = 200.0f; // g
net->mClassColors[0][n*4+2] = 255.0f; // b
net->mClassColors[0][n*4+3] = 100.0f; // a
}
else
{
net->mClassColors[0][n*4+0] = 0.0f; // r
net->mClassColors[0][n*4+1] = 255.0f; // g
net->mClassColors[0][n*4+2] = 175.0f; // b
net->mClassColors[0][n*4+3] = 100.0f; // a
}
}
net->SetThreshold(threshold);
return net;
}
cudaError_t cudaPreImageNetMean( float4* input, size_t inputWidth, size_t inputHeight, float* output, size_t outputWidth, size_t outputHeight, const float3& mean_value );
struct float6 { float x; float y; float z; float w; float v; float u; };
static inline float6 make_float6( float x, float y, float z, float w, float v, float u ) { float6 f; f.x = x; f.y = y; f.z = z; f.w = w; f.v = v; f.u = u; return f; }
inline static bool rectOverlap(const float6& r1, const float6& r2)
{
return ! ( r2.x > r1.z
|| r2.z < r1.x
|| r2.y > r1.w
|| r2.w < r1.y
);
}
static void mergeRect( std::vector<float6>& rects, const float6& rect )
{
const uint32_t num_rects = rects.size();
bool intersects = false;
for( uint32_t r=0; r < num_rects; r++ )
{
if( rectOverlap(rects[r], rect) )
{
intersects = true;
#ifdef DEBUG_CLUSTERING
printf("found overlap\n");
#endif
if( rect.x < rects[r].x ) rects[r].x = rect.x;
if( rect.y < rects[r].y ) rects[r].y = rect.y;
if( rect.z > rects[r].z ) rects[r].z = rect.z;
if( rect.w > rects[r].w ) rects[r].w = rect.w;
break;
}
}
if( !intersects )
rects.push_back(rect);
}
// Detect
bool detectNet::Detect( float* rgba, uint32_t width, uint32_t height, float* boundingBoxes, int* numBoxes, float* confidence )
{
if( !rgba || width == 0 || height == 0 || !boundingBoxes || !numBoxes || *numBoxes < 1 )
{
printf("detectNet::Detect( 0x%p, %u, %u ) -> invalid parameters\n", rgba, width, height);
return false;
}
// downsample and convert to band-sequential BGR
if( CUDA_FAILED(cudaPreImageNetMean((float4*)rgba, width, height, mInputCUDA, mWidth, mHeight,
make_float3(104.0069879317889f, 116.66876761696767f, 122.6789143406786f))) )
{
printf("detectNet::Classify() -- cudaPreImageNetMean failed\n");
return false;
}
// process with GIE
void* inferenceBuffers[] = { mInputCUDA, mOutputs[OUTPUT_CVG].CUDA, mOutputs[OUTPUT_BBOX].CUDA };
if( !mContext->execute(1, inferenceBuffers) )
{
printf(LOG_GIE "detectNet::Classify() -- failed to execute tensorRT context\n");
*numBoxes = 0;
return false;
}
PROFILER_REPORT();
// cluster detection bboxes
float* net_cvg = mOutputs[OUTPUT_CVG].CPU;
float* net_rects = mOutputs[OUTPUT_BBOX].CPU;
const int ow = mOutputs[OUTPUT_BBOX].dims.w; // number of columns in bbox grid in X dimension
const int oh = mOutputs[OUTPUT_BBOX].dims.h; // number of rows in bbox grid in Y dimension
const int owh = ow * oh; // total number of bbox in grid
const int cls = GetNumClasses(); // number of object classes in coverage map
const float cell_width = /*width*/ mInputDims.w / ow;
const float cell_height = /*height*/ mInputDims.h / oh;
const float scale_x = float(width) / float(mInputDims.w);
const float scale_y = float(height) / float(mInputDims.h);
#ifdef DEBUG_CLUSTERING
printf("input width %i height %i\n", (int)mInputDims.w, (int)mInputDims.h);
printf("cells x %i y %i\n", ow, oh);
printf("cell width %f height %f\n", cell_width, cell_height);
printf("scale x %f y %f\n", scale_x, scale_y);
#endif
#if 1
std::vector< std::vector<float6> > rects;
rects.resize(cls);
// extract and cluster the raw bounding boxes that meet the coverage threshold
for( uint32_t z=0; z < cls; z++ )
{
rects[z].reserve(owh);
for( uint32_t y=0; y < oh; y++ )
{
for( uint32_t x=0; x < ow; x++)
{
const float coverage = net_cvg[z * owh + y * ow + x];
if( coverage > mCoverageThreshold )
{
const float mx = x * cell_width;
const float my = y * cell_height;
const float x1 = (net_rects[0 * owh + y * ow + x] + mx) * scale_x; // left
const float y1 = (net_rects[1 * owh + y * ow + x] + my) * scale_y; // top
const float x2 = (net_rects[2 * owh + y * ow + x] + mx) * scale_x; // right
const float y2 = (net_rects[3 * owh + y * ow + x] + my) * scale_y; // bottom
#ifdef DEBUG_CLUSTERING
printf("rect x=%u y=%u cvg=%f %f %f %f %f \n", x, y, coverage, x1, x2, y1, y2);
#endif
mergeRect( rects[z], make_float6(x1, y1, x2, y2, coverage, z) );
}
}
}
}
//printf("done clustering rects\n");
// condense the multiple class lists down to 1 list of detections
const uint32_t numMax = *numBoxes;
int n = 0;
for( uint32_t z = 0; z < cls; z++ )
{
const uint32_t numBox = rects[z].size();
for( uint32_t b = 0; b < numBox && n < numMax; b++ )
{
const float6 r = rects[z][b];
boundingBoxes[n * 4 + 0] = r.x;
boundingBoxes[n * 4 + 1] = r.y;
boundingBoxes[n * 4 + 2] = r.z;
boundingBoxes[n * 4 + 3] = r.w;
if( confidence != NULL )
{
confidence[n * 2 + 0] = r.v; // coverage
confidence[n * 2 + 1] = r.u; // class ID
}
n++;
}
}
*numBoxes = n;
#else
*numBoxes = 0;
#endif
return true;
}
// DrawBoxes
bool detectNet::DrawBoxes( float* input, float* output, uint32_t width, uint32_t height, const float* boundingBoxes, int numBoxes, int classIndex )
{
if( !input || !output || width == 0 || height == 0 || !boundingBoxes || numBoxes < 1 || classIndex < 0 || classIndex >= GetNumClasses() )
return false;
const float4 color = make_float4( mClassColors[0][classIndex*4+0],
mClassColors[0][classIndex*4+1],
mClassColors[0][classIndex*4+2],
mClassColors[0][classIndex*4+3] );
printf("draw boxes %i %i %f %f %f %f\n", numBoxes, classIndex, color.x, color.y, color.z, color.w);
if( CUDA_FAILED(cudaRectOutlineOverlay((float4*)input, (float4*)output, width, height, (float4*)boundingBoxes, numBoxes, color)) )
return false;
return true;
}
| [
"dustinf@nvidia.com"
] | dustinf@nvidia.com |
f6a87634b4d176765a44fa6e29c94fc0c3f30775 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Control/AthContainers/test/DataVector_e_test.cxx | df6526bd36aac073465246a6d00cfa7914b3704e | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// $Id$
/**
* @file AthContainers/test/DataVector_e_test.cxx
* @author scott snyder <snyder@bnl.gov>
* @date Sep, 2013
* @brief Regression tests for DataVector
*
* The @c DataVector regression tests are split into several pieces,
* in order to reduce the memory required for compilation.
*/
#undef NDEBUG
#include "DataVector_test.icc"
void test2_e()
{
std::cout << "test2_e\n";
do_test2<AAux, BAux> ();
}
int main()
{
test2_e();
return 0;
}
| [
"graemes.cern@gmail.com"
] | graemes.cern@gmail.com |
eb9f979ba5f6a6961aa6a4f6264e29d3a73fc791 | 531504b3f4fda98acc84a3885a7c346aa1a371ee | /KSYNVSDK/include/framework/NvJpegReader.h | 193c96dbd5c873351dc4b180e71bc2154e593cc3 | [] | no_license | noodle147/KSYDiversityLive_iOS | bbdac64166b458cdf5981bd8b66e2715c390bb51 | 95921f36095d3435a6ad709472492b1f3b8d25ec | refs/heads/master | 2021-04-08T00:05:06.054617 | 2018-03-07T02:47:30 | 2018-03-07T02:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,498 | h | //================================================================================
//
// (c) Copyright China Digital Video (Beijing) Limited, 2017. All rights reserved.
//
// This code and information is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the implied
// warranties of merchantability and/or fitness for a particular purpose.
//
//--------------------------------------------------------------------------------
// Birth Date: May 13. 2017
// Author: NewAuto video team
//================================================================================
#pragma once
#include "NvJpegTurboReader.h"
#include <INvVideoFrameAllocator.h>
#include <INvVideoFrame.h>
#include <NvSmartPtr.h>
#ifdef Q_OS_IOS
#define NV_HAS_LIBJPEG
#endif
class CNvJpegReader
{
public:
CNvJpegReader();
~CNvJpegReader();
public:
void ReadFrame(const QString &jpegFilePath, INvVideoFrame **ppIVideoFrame);
void ReadFrame(const QByteArray &imageData, INvVideoFrame **ppIVideoFrame);
private:
TNvSmartPtr<INvVideoFrameAllocator> m_pJHostVideoFrameAllocator;
#if defined(NV_HAS_LIBJPEG_TURBO)
CNvJpegTurboReader m_jpegTurboReader;
#endif
private:
#ifdef NV_HAS_LIBJPEG
void ReadFrameByLibJpeg(const QString &jpegFilePath, INvVideoFrame **ppIVideoFrame);
void ReadFrameByLibJpeg(const QByteArray &jpegImageData, INvVideoFrame **ppIVideoFrame);
#endif
};
| [
"jiangdong@kingsoft.com"
] | jiangdong@kingsoft.com |
0196a6435615e72ed6305d303778d0ca25edeace | aea895b4f3caac17e3b3743723db2dbaaf69aeed | /C++/JZ18.cpp | bee85620249311426189e8d8028b39a9a7767b9b | [] | no_license | xxxsssyyy/offer-Goal | c8f28fe09dd86ed10d6fcb52e6b7881c46bb9998 | 6d509b83856fff744ca6e06c946cf55041a3311a | refs/heads/master | 2021-08-02T15:28:06.820412 | 2021-07-29T02:09:46 | 2021-07-29T02:09:46 | 192,471,289 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | cpp | // Created by xingsiyuan on 2021/1/27 10:38.
// Copyright (c) xingsiyuan2019@ia.ac.cn
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
/*
题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解题思路:
*/
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (!pRoot) {
return;
}
else if (!pRoot->left && !pRoot->right) {
return;
}
else if (!pRoot->left) {
pRoot->left = pRoot->right;
pRoot->right = NULL;
}
else if (!pRoot->right) {
pRoot->right = pRoot->left;
pRoot->left = NULL;
}
else {
TreeNode* temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
}
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
| [
"xsy961127@buaa.edu.cn"
] | xsy961127@buaa.edu.cn |
4bd56d6c94b41345ce167ac35c4153fa0c408b91 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/iis/svcs/smtp/aqueue/advqueue/smtpconn.cpp | 22271d626b52f6a1002806058b5c93698402af75 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,502 | cpp | //-----------------------------------------------------------------------------
//
//
// File:
// smtpconn.cpp
// Description:
// Implementation of CSMTPConn
// Author: Mike Swafford (MikeSwa)
//
// History:
//
// Copyright (C) 1998 Microsoft Corporation
//
//-----------------------------------------------------------------------------
#include "aqprecmp.h"
#include "SMTPConn.h"
#include "connmgr.h"
#include "domcfg.h"
CPool CSMTPConn::s_SMTPConnPool;
//---[ CSMTPConn::CSMTPConn() ]------------------------------------------------
//
//
// Description:
// CSMTPConn constructor
// Parameters:
// IN pConnMgr Ptr to instance connection manager
// IN plmq Ptr to link for this connection
// IN cMaxMessagesPerConnection Max messages to send per connection
// 0 implies unlimited
// Returns:
// -
//
//-----------------------------------------------------------------------------
CSMTPConn::CSMTPConn(CConnMgr *pConnMgr, CLinkMsgQueue *plmq,
DWORD cMaxMessagesPerConnection)
{
_ASSERT(pConnMgr);
_ASSERT(plmq);
m_dwSignature = SMTP_CONNECTION_SIG;
m_pConnMgr = pConnMgr;
m_pIntDomainInfo = NULL;
m_plmq = plmq;
m_cFailedMsgs = 0;
m_cTriedMsgs = 0;
m_cMaxMessagesPerConnection = cMaxMessagesPerConnection;
m_dwConnectionStatus = CONNECTION_STATUS_OK;
m_szDomainName = NULL;
m_cbDomainName = 0;
m_liConnections.Flink = NULL;
m_liConnections.Blink = NULL;
m_cAcks = 0;
m_dwTickCountOfLastAck = 0;
if (plmq)
{
plmq->AddRef();
}
}
//---[ CSMTPConn::~CSMTPConn() ]-----------------------------------------------
//
//
// Description:
// CSMTPConn default destructor
// Parameters:
// -
// Returns:
// -
//
//-----------------------------------------------------------------------------
CSMTPConn::~CSMTPConn()
{
HRESULT hrConnectionStatus = S_OK;
BOOL fHardErrorForceNDR = FALSE;
_ASSERT(m_cAcks == m_cTriedMsgs);
if (m_plmq != NULL)
{
_ASSERT(m_pConnMgr);
m_pConnMgr->ReleaseConnection(this, &fHardErrorForceNDR);
switch(m_dwConnectionStatus)
{
case CONNECTION_STATUS_OK:
hrConnectionStatus = S_OK;
break;
case CONNECTION_STATUS_FAILED:
hrConnectionStatus = AQUEUE_E_HOST_NOT_RESPONDING;
break;
case CONNECTION_STATUS_DROPPED:
hrConnectionStatus = AQUEUE_E_CONNECTION_DROPPED;
break;
case CONNECTION_STATUS_FAILED_LOOPBACK:
hrConnectionStatus = AQUEUE_E_LOOPBACK_DETECTED;
break;
case CONNECTION_STATUS_FAILED_NDR_UNDELIVERED:
hrConnectionStatus = AQUEUE_E_NDR_ALL;
break;
default:
_ASSERT(0 && "Undefined Connection Status");
hrConnectionStatus = S_OK;
}
m_plmq->SetLastConnectionFailure(hrConnectionStatus);
m_plmq->RemoveConnection(this, fHardErrorForceNDR);
m_plmq->Release();
//We should kick the connection manager, because if we were generating
//DSNs, no connection could be made
m_pConnMgr->KickConnections();
}
if (m_pIntDomainInfo)
m_pIntDomainInfo->Release();
}
//---[ CSMTPConn::GetNextMessage ]---------------------------------------------
//
//
// Description:
// Implementation of ISMTPConnection::GetNextMsg.
// Gets the next message queued for this connection and determines which
// recipients should be delivered for this connection.
// Parameters:
// OUT ppimsg New IMsg top be delivered
// OUT pdwMsgContext A 32-bit Context that needs to be provided in the
// message ack.
// OUT pcIndexes The number of index in prgdwRecipIndex
// OUT prgdwRecipIndex Recipient indexes that the caller is responsible
// for attempting delivery to.
// Returns:
//
//
//-----------------------------------------------------------------------------
STDMETHODIMP CSMTPConn::GetNextMessage(
OUT IMailMsgProperties **ppIMailMsgProperties,
OUT DWORD ** ppvMsgContext,
OUT DWORD * pcIndexes,
OUT DWORD ** prgdwRecipIndex)
{
TraceFunctEnterEx((LPARAM) this, "CSMTPConn::GetNextMessage");
HRESULT hr = S_OK;
//We get the next message only if we are under the batch limit
if(m_cMaxMessagesPerConnection &&
(m_cTriedMsgs >= m_cMaxMessagesPerConnection) &&
(!m_pIntDomainInfo ||
!((DOMAIN_INFO_TURN_ONLY | DOMAIN_INFO_ETRN_ONLY) &
m_pIntDomainInfo->m_DomainInfo.dwDomainInfoFlags)))
{
//SMTP does not check - but we may need a specific error for this case
hr = AQUEUE_E_QUEUE_EMPTY;
goto Exit;
}
if (m_pConnMgr && m_pConnMgr->fConnectionsStoppedByAdmin())
{
//Admin has requested that all outbound connections stop
hr = AQUEUE_E_QUEUE_EMPTY;
goto Exit;
}
hr = m_plmq->HrGetNextMsg(&m_dcntxtCurrentDeliveryContext, ppIMailMsgProperties,
pcIndexes, prgdwRecipIndex);
if (FAILED(hr))
goto Exit;
//this will automagically catch the queue empty case...
//If the Link has no more messages it will return AQUEUE_E_QUEUE_EMPTY, which
//should cause the caller to Release() and query GetNextConnection again.
*ppvMsgContext = (DWORD *) &m_dcntxtCurrentDeliveryContext;
//increment the messages served
InterlockedIncrement((PLONG)&m_cTriedMsgs);
Exit:
if (!m_cTriedMsgs)
DebugTrace((LPARAM) this, "GetNextMessage called, but no messages tried for this connection");
//rewrite error for SMTPSVC
if (AQUEUE_E_QUEUE_EMPTY == hr)
hr = HRESULT_FROM_WIN32(ERROR_EMPTY);
TraceFunctLeave();
return hr;
}
//---[ CSMTPConn::AckMessage ]-------------------------------------------------
//
//
// Description:
// Acknowledges the delivery of a message (success/error codes are put in
// the envelope by the transport).
//
// Implements ISMTPConnection::AckMessage();
// Parameters:
// IN pIMsg IMsg to acknowledge
// IN dwMsgContext Context that was returned by GetNextMessage
// IN eMsgStatus Status of message
// Returns:
// S_OK on success
// E_INVALIDARG if dwMsgContext is invalid
//
//-----------------------------------------------------------------------------
STDMETHODIMP CSMTPConn::AckMessage(/*[in]*/ MessageAck *pMsgAck)
{
HRESULT hr = S_OK;
DWORD dwTickCount = GetTickCount();
_ASSERT(m_plmq);
_ASSERT(pMsgAck);
if (!(pMsgAck->dwMsgStatus & MESSAGE_STATUS_ALL_DELIVERED))
{
m_cFailedMsgs++;
}
InterlockedIncrement((PLONG)&m_cAcks);
_ASSERT(m_cAcks == m_cTriedMsgs);
hr = m_plmq->HrAckMsg(pMsgAck);
m_dwTickCountOfLastAck = dwTickCount; //Set after assert so we can compare
return hr;
}
//---[ CSMTPConn::GetSMTPDomain ]----------------------------------------------
//
//
// Description:
// Returns the SMTPDomain of the link associated with this connections.
//
// $$REVIEW:
// This method does not allocate new memory for this string, but instead
// relies on the good intentions of the SMTP stack (or test driver) to
// not overwrite this memory. If we ever expose this interface externally,
// then we should revert to allocating memory and doing a buffer copy
//
// Implements ISMTPConnection::GetSMTPDomain
// Parameters:
// IN OUT pDomainInfo Ptr to DomainInfo struct supplied by caller
// and filled in here
// Returns:
// S_OK on success
//
//-----------------------------------------------------------------------------
STDMETHODIMP CSMTPConn::GetDomainInfo(IN OUT DomainInfo *pDomainInfo)
{
HRESULT hr = S_OK;
_ASSERT(pDomainInfo->cbVersion >= sizeof(DomainInfo));
_ASSERT(pDomainInfo);
if (NULL == m_plmq)
{
hr = AQUEUE_E_LINK_INVALID;
goto Exit;
}
if (!m_pIntDomainInfo)
{
//Try to get domain info
hr = m_plmq->HrGetDomainInfo(&m_cbDomainName, &m_szDomainName,
&m_pIntDomainInfo);
if (FAILED(hr))
{
m_pIntDomainInfo = NULL;
_ASSERT(AQUEUE_E_INVALID_DOMAIN != hr);
goto Exit;
}
}
_ASSERT(m_pIntDomainInfo);
_ASSERT(m_cbDomainName);
_ASSERT(m_szDomainName);
// Is it OK to send client side commands on this connection
// If not, we reset those domain info flags so SMTp cannot see them
if(!m_plmq->fCanSendCmd())
{
m_pIntDomainInfo->m_DomainInfo.dwDomainInfoFlags &= ~(DOMAIN_INFO_SEND_TURN | DOMAIN_INFO_SEND_ETRN);
}
// If SMTP doesn't have the DOMAIN_INFO_TURN_ON_EMPTY then it is the older,
// broken SMTP and we shouldn't allow TURN on empty to work.
if ((m_plmq->cGetTotalMsgCount() == 0) &&
!(m_pIntDomainInfo->m_DomainInfo.dwDomainInfoFlags &
DOMAIN_INFO_TURN_ON_EMPTY))
{
m_pIntDomainInfo->m_DomainInfo.dwDomainInfoFlags &= ~DOMAIN_INFO_SEND_TURN;
}
//copy everything but size
memcpy(&(pDomainInfo->dwDomainInfoFlags),
&(m_pIntDomainInfo->m_DomainInfo.dwDomainInfoFlags),
sizeof(DomainInfo) - sizeof(DWORD));
//make sure our assumptions about the struct of DomainInfo are valid
_ASSERT(1 == ((DWORD *) &(pDomainInfo->dwDomainInfoFlags)) - ((DWORD *) pDomainInfo));
//we've filled pDomainInfo with the info for our Domain
if (pDomainInfo->szDomainName[0] == '*')
{
//we matched a wildcard domain... substitute our domain name
pDomainInfo->cbDomainNameLength = m_cbDomainName;
pDomainInfo->szDomainName = m_szDomainName;
}
else
{
//if it wasn't a wildcard match... strings should match!
_ASSERT(0 == _stricmp(m_szDomainName, pDomainInfo->szDomainName));
}
Exit:
return hr;
}
//---[ CSMTPConn::SetDiagnosticInfo ]------------------------------------------
//
//
// Description:
// Sets the extra diagnostic information for this connection.
// Parameters:
// IN hrDiagnosticError Error code... if SUCCESS we thow away
// the rest of the information
// IN szDiagnosticVerb String pointing to the protocol
// verb that caused the failure.
// IN szDiagnosticResponse String that contains the remote
// servers response.
// Returns:
// S_OK always
// History:
// 2/18/99 - MikeSwa Created
//
//-----------------------------------------------------------------------------
STDMETHODIMP CSMTPConn::SetDiagnosticInfo(
IN HRESULT hrDiagnosticError,
IN LPCSTR szDiagnosticVerb,
IN LPCSTR szDiagnosticResponse)
{
TraceFunctEnterEx((LPARAM) this, "CSMTPConn::SetDiagnosticInfo");
if (m_plmq && FAILED(hrDiagnosticError))
{
m_plmq->SetDiagnosticInfo(hrDiagnosticError, szDiagnosticVerb,
szDiagnosticResponse);
}
TraceFunctLeave();
return S_OK; //always return S_OK
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
683cf84e19e835ba3862ad572e5d073c2b839b7b | 9c3a823dcbea34a52178243c14d9d69a19a6129f | /include/ros_lib/tf2_msgs/LookupTransformActionResult.h | a6458c2f52ddf9df46f105abcbdc1244f6f57b7f | [] | no_license | team914/muphry | 9dc6f45304204d3853a5d3877dd512cfa2a796e4 | a2b85f7f0d857da57347e129b33e65af211b88e0 | refs/heads/develop | 2020-10-02T01:10:30.559742 | 2020-05-03T23:43:41 | 2020-05-03T23:43:41 | 227,664,967 | 2 | 1 | null | 2020-04-21T18:23:03 | 2019-12-12T17:52:06 | C++ | UTF-8 | C++ | false | false | 1,512 | h | #ifndef _ROS_tf2_msgs_LookupTransformActionResult_h
#define _ROS_tf2_msgs_LookupTransformActionResult_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros_lib/ros/msg.h"
#include "ros_lib/std_msgs/Header.h"
#include "ros_lib/actionlib_msgs/GoalStatus.h"
#include "ros_lib/tf2_msgs/LookupTransformResult.h"
namespace tf2_msgs
{
class LookupTransformActionResult : public ros::Msg
{
public:
typedef std_msgs::Header _header_type;
_header_type header;
typedef actionlib_msgs::GoalStatus _status_type;
_status_type status;
typedef tf2_msgs::LookupTransformResult _result_type;
_result_type result;
LookupTransformActionResult():
header(),
status(),
result()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->header.serialize(outbuffer + offset);
offset += this->status.serialize(outbuffer + offset);
offset += this->result.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->header.deserialize(inbuffer + offset);
offset += this->status.deserialize(inbuffer + offset);
offset += this->result.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return "tf2_msgs/LookupTransformActionResult"; };
const char * getMD5(){ return "ac26ce75a41384fa8bb4dc10f491ab90"; };
};
}
#endif
| [
"acetousk@gmail.com"
] | acetousk@gmail.com |
1e0dfa754486ab451bfdf4bea6a7d88aecb7cfae | 2df9392e8e7be3c66736b8e67cb71929f12a5f2b | /source/Shaders/Shader.cpp | 7f5221de477419a661e0ccd15b2d5bbd74104449 | [] | no_license | k-j0/graphics-demo | 34fc57b1cfc5a4bf92bade181479330e3d217403 | 522de6b3a67ad461fd5a92182d0716990167a955 | refs/heads/master | 2020-04-15T05:15:06.776476 | 2019-01-07T10:25:27 | 2019-01-07T10:25:27 | 164,414,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,970 | cpp | #include "Shader.h"
#include "AppGlobals.h"
Shader::Shader() : BaseShader(GLOBALS.Device, GLOBALS.Hwnd) {
}
Shader::~Shader(){
if (sampleState)
sampleState->Release();
if (matrixBuffer)
matrixBuffer->Release();
if (layout)
layout->Release();
}
///Reference: https://docs.microsoft.com/en-us/windows/uwp/gaming/load-a-game-asset
void Shader::loadSkinVertexShader(WCHAR * filename) {
if (vertexShader) {
printf("Error: vertex shader has already been loaded prior!\n");
return;
}
/// Load shader -----------------------------------------------------------------------------------------------------------------------
std::ifstream input(filename, std::ios::binary);
std::vector<char> bytes((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>()));
if (bytes.size() <= 0) {
std::wstring wfilename(filename);
printf("Error: vertex shader file %s does not exist...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
return;
}
HRESULT result = GLOBALS.Device->CreateVertexShader(bytes.data(), bytes.size(), nullptr, &vertexShader);
if (result != S_OK) {
std::wstring wfilename(filename);
printf("Error: could not load compiled skinning vertex shader %s...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
printError(result);
return;
}
/// Create input layout -----------------------------------------------------------------------------------------------------------------------
const D3D11_INPUT_ELEMENT_DESC layoutDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float3 Position
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float2 Texcoord0
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float3 Normal
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float3 Tangent
{ "BLENDINDICES", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Uint4 BlendIndices0
{ "BLENDINDICES", 1, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Uint4 BlendIndices1
{ "BLENDWEIGHT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float4 BlendWeight0
{ "BLENDWEIGHT", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float4 BlendWeight1
};
result = GLOBALS.Device->CreateInputLayout(layoutDesc, ARRAYSIZE(layoutDesc), bytes.data(), bytes.size(), &layout);
if (result != S_OK) {
std::wstring wfilename(filename);
printf("Error: could not create input layout for skinning vertex shader %s...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
printError(result);
return;
}
//Success! :D
}
void Shader::loadTangentVertexShader(WCHAR * filename) {
if (vertexShader) {
printf("Error: vertex shader has already been loaded prior!\n");
return;
}
/// Load shader -----------------------------------------------------------------------------------------------------------------------
std::ifstream input(filename, std::ios::binary);
std::vector<char> bytes((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>()));
if (bytes.size() <= 0) {
std::wstring wfilename(filename);
printf("Error: vertex shader file %s does not exist...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
return;
}
HRESULT result = GLOBALS.Device->CreateVertexShader(bytes.data(), bytes.size(), nullptr, &vertexShader);
if (result != S_OK) {
std::wstring wfilename(filename);
printf("Error: could not load compiled tangent vertex shader %s...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
printError(result);
return;
}
/// Create input layout -----------------------------------------------------------------------------------------------------------------------
const D3D11_INPUT_ELEMENT_DESC layoutDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float3 Position
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float2 Texcoord0
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, // Float3 Normal
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } // Float3 Tangent
};
result = GLOBALS.Device->CreateInputLayout(layoutDesc, ARRAYSIZE(layoutDesc), bytes.data(), bytes.size(), &layout);
if (result != S_OK) {
std::wstring wfilename(filename);
printf("Error: could not create input layout for tangent vertex shader %s...\n", std::string(wfilename.begin(), wfilename.end()).c_str());
printError(result);
return;
}
//Success! :D
}
void Shader::printError(HRESULT errorCode){
#define ERR(err) case err: printf(#err "\n"); return;
switch (errorCode) {
ERR(D3D11_ERROR_FILE_NOT_FOUND)
ERR(D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS)
ERR(D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS)
ERR(D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD)
ERR(DXGI_ERROR_INVALID_CALL)
ERR(DXGI_ERROR_WAS_STILL_DRAWING)
ERR(E_FAIL)
ERR(E_INVALIDARG)
ERR(E_OUTOFMEMORY)
ERR(E_NOTIMPL)
ERR(S_FALSE)
default:
printf("Unknown error\n");
}
#undef ERR
}
void Shader::initShader(WCHAR* vsFilename, WCHAR* psFilename, bool skin, bool colour, bool tangent) {
// Load (+ compile) shader files
if (skin)
loadSkinVertexShader(vsFilename);
else if (tangent)
loadTangentVertexShader(vsFilename);
else if (colour)
loadColourVertexShader(vsFilename);
else
loadVertexShader(vsFilename);
loadPixelShader(psFilename);
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
D3D11_BUFFER_DESC matrixBufferDesc;
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
renderer->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
//If this is derived from Shader, will setup additional specific buffers
initBuffers();
}
/// Loads hull and domain for this shader
void Shader::initHullDomain(WCHAR* hsFilename, WCHAR* dsFilename) {
loadHullShader(hsFilename);
loadDomainShader(dsFilename);
//setup dynamic tessellation buffer
SETUP_SHADER_BUFFER(DynamicTessellationBufferType, dynamicTessellationBuffer);
}
/// Loads geometry for this shader
void Shader::initGeometry(WCHAR* gsFilename) {
loadGeometryShader(gsFilename);
}
void Shader::setShaderParameters(ID3D11DeviceContext* deviceContext, const XMMATRIX &worldMatrix, const XMMATRIX &viewMatrix, const XMMATRIX &projectionMatrix, XMFLOAT3 cameraPosition) {
D3D11_MAPPED_SUBRESOURCE mappedResource;
// Transpose the matrices to prepare them for the shader.
XMMATRIX tworld, tview, tproj;
tworld = XMMatrixTranspose(worldMatrix);
tview = XMMatrixTranspose(viewMatrix);
tproj = XMMatrixTranspose(projectionMatrix);
MatrixBufferType* dataPtr;
deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
dataPtr = (MatrixBufferType*)mappedResource.pData;
dataPtr->world = tworld;
dataPtr->view = tview;
dataPtr->projection = tproj;
deviceContext->Unmap(matrixBuffer, 0);
if (domainShader) {//if there is a domain shader, the matrices will be applied there.
deviceContext->DSSetConstantBuffers(0, 1, &matrixBuffer);
}
else if (geometryShader) {//instead if there is a geometry shader, the matrices will be applied there.
deviceContext->GSSetConstantBuffers(0, 1, &matrixBuffer);
}
else {//otherwise, vertex shader it is
deviceContext->VSSetConstantBuffers(0, 1, &matrixBuffer);
}
//Send dynamic tessellation buffer if needed
if (hullShader) {
DynamicTessellationBufferType* dynPtr;
deviceContext->Map(dynamicTessellationBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
dynPtr = (DynamicTessellationBufferType*)mappedResource.pData;
dynPtr->worldMatrix = tworld;
dynPtr->cameraPosition = cameraPosition;
dynPtr->oneOverFarPlane = 1 / FAR_PLANE;
dynPtr->tessellationMax = GLOBALS.TessellationMax;
dynPtr->tessellationMin = GLOBALS.TessellationMin;
dynPtr->tessellationRange = GLOBALS.TessellationRange <= 0 ? FLT_MAX : 1.0f/GLOBALS.TessellationRange;
deviceContext->Unmap(dynamicTessellationBuffer, 0);
deviceContext->HSSetConstantBuffers(0, 1, &dynamicTessellationBuffer);
}
// Set sampler resource in the pixel shader
deviceContext->PSSetSamplers(0, 1, &sampleState);
}
| [
"jkings@hotmail.fr"
] | jkings@hotmail.fr |
91294aac99d16d0cce74af8cf9967fb5fd5a0118 | 6075db6342cd100c31ba19bdee8f7f446229843a | /expressions/GtExpr.hpp | dc272de4e0b041e488204978ce379ff5216563e0 | [] | no_license | 14sjohnson/Compiler | 5b98899108354ab14088a46cbcf25ba9a1dbd4c4 | 98dafeb1a991255bbbc77fae96fb781adfea8a85 | refs/heads/master | 2022-11-28T17:43:40.791658 | 2020-08-09T23:32:47 | 2020-08-09T23:32:47 | 264,842,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | hpp | #ifndef GTEXPR_HPP
#define GTEXPR_HPP
#include "Expression.hpp"
class GtExpr : public Expression {
private:
Expression* a;
Expression* b;
public:
GtExpr(Expression* e1, Expression* e2, Type* type) : Expression(type), a(e1), b(e2) {}
Register* emit() {
auto regA = a->emit();
auto regB = b->emit();
auto result = new Register();
std::cout << "sgt " << result->getRegister() << ", "
<< regA->getRegister() << ", "
<< regB->getRegister()
<< std::endl;
return result;
}
};
#endif
| [
"johnson.scott.14@gmail.com"
] | johnson.scott.14@gmail.com |
72b94fe67143b136f0483e1aaccea7bb1854cb75 | 67ce8ff142f87980dba3e1338dabe11af50c5366 | /opencv/src/opencv/modules/gapi/test/render/ftp_render_test.cpp | 95e7f5aabb348102100b0942be585e745f377134 | [
"Apache-2.0"
] | permissive | checksummaster/depthmovie | 794ff1c5a99715df4ea81abd4198e8e4e68cc484 | b0f1c233afdaeaaa5546e793a3e4d34c4977ca10 | refs/heads/master | 2023-04-19T01:45:06.237313 | 2021-04-30T20:34:16 | 2021-04-30T20:34:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | cpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018 Intel Corporation
#include "../test_precomp.hpp"
#ifdef HAVE_FREETYPE
#include <random>
#include <opencv2/core/utils/configuration.private.hpp>
#include "backends/render/ft_render.hpp"
namespace opencv_test
{
static std::string getFontPath()
{
static std::string path = cv::utils::getConfigurationParameterString("OPENCV_TEST_FREETYPE_FONT_PATH",
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc");
return path;
}
inline void RunTest(const std::string& font,
size_t num_iters,
size_t lower_char_code,
size_t upper_char_code)
{
cv::gapi::wip::draw::FTTextRender ftpr(font);
std::mt19937 gen{std::random_device()()};
std::uniform_int_distribution<int> dist(lower_char_code, upper_char_code);
std::uniform_int_distribution<int> dist_size(2, 200);
for (size_t i = 0; i < num_iters; ++i)
{
size_t text_size = dist_size(gen);
std::wstring text;
for (size_t j = 0; j < text_size; ++j)
{
wchar_t c = dist(gen);
text += c;
}
int fh = dist_size(gen);
int baseline = 0;
cv::Size size;
ASSERT_NO_THROW(size = ftpr.getTextSize(text, fh, &baseline));
cv::Mat bmp(size, CV_8UC1, cv::Scalar::all(0));
cv::Point org(0, bmp.rows - baseline);
ASSERT_NO_THROW(ftpr.putText(bmp, text, org, fh));
}
}
TEST(FTTextRenderTest, Smoke_Test_Ascii)
{
RunTest(getFontPath(), 2000, 32, 126);
}
TEST(FTTextRenderTest, Smoke_Test_Unicode)
{
RunTest(getFontPath(), 2000, 20320, 30000);
}
} // namespace opencv_test
#endif // HAVE_FREETYPE
| [
"alex@shimadzu.ca"
] | alex@shimadzu.ca |
2e3138e2dd967045b07a2d44a2ce803a6ed50032 | 186a05fcb725481c0c51c31b2b948819205c789d | /src/parser/StringManip.cpp | ab13123a307b704bd83d914d7b34512ec9b84442 | [] | no_license | benhj/jasl | e497c5e17bff05aa5bbd2cfb1528b54674835b72 | 6e2d6cdb74692e4eaa950e25ed661d615cc32f11 | refs/heads/master | 2020-12-25T16:49:00.699346 | 2019-12-09T18:57:47 | 2019-12-09T18:57:47 | 28,279,592 | 27 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | cpp | #include "StringManip.hpp"
#include "Strings.hpp"
#include "BasicTypes.hpp"
#include "Expressions.hpp"
#include "Parameters.hpp"
namespace qi = ::boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
qi::rule<jasl::StringManip::Iterator, jasl::Function(), ascii::space_type> jasl::StringManip::appendRule;
qi::rule<jasl::StringManip::Iterator, jasl::Function(), ascii::space_type> jasl::StringManip::reverseRule;
qi::rule<jasl::StringManip::Iterator, jasl::Function(), ascii::space_type> jasl::StringManip::concatRule;
namespace jasl {
void StringManip::init()
{
using qi::lit;
using ascii::string;
// appends to end of a string, s
// append (s, "hello") -> result;
appendRule %= string("append")
>> ('(')
>> (Strings::doubleQuotedString | Strings::genericString)
>> ','
>> (Strings::doubleQuotedString | Strings::genericString | BasicTypes::doubleRule | BasicTypes::intRule | BasicTypes::boolRule |
Expressions::mathExpression | Expressions::bracketedMathExpression |
Expressions::comparisonExpression | Expressions::bracketedComparisonExpression)
>> ')'
>> lit("->")
>> Strings::genericString
>> ';';
// string_reverse name;
reverseRule %= string("string_reverse")
>> (Strings::doubleQuotedString | Strings::genericString)
>> ';';
// concatenate strings.
concatRule %= string("concat")
>> (Parameters::parameterList) >> lit("->")
>> Strings::genericString
>> ';';
}
} | [
"bhj.research@gmail.com"
] | bhj.research@gmail.com |
48444f07879c3d62edcc22511cc6a490739d0657 | 71a7b0c4e7b483f8be9723717ef976af14a1d106 | /fold2/3_test_training.cpp | 5ddfdfcbdb6e9de24b35d9663880bf577612dc83 | [] | no_license | GibreelAbdullah/nlp_project | 874533a6387f56d8017f4dbb439edc7cd66c0a65 | 68319d2ffd55435bf973fddb944450e132bc1938 | refs/heads/master | 2021-01-10T18:21:23.262542 | 2016-04-17T20:37:08 | 2016-04-17T20:37:08 | 52,622,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | #include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
ifstream f1;
ofstream f2,f3;
string s;
char s1[12]="0/test0.txt",s2[13]="0/train0.txt";
f1.open("stop_removed.txt");
int i=-1;
int countpos=0,countneg=0;
while(++i<10)
{
int start=i*30;
int end=(i+1)*30;
countpos=0;
countneg=0;
system ("i=0; while [ $i -lt 10 ]; do mkdir -p $i; i=`expr $i + 1`; done;");
s1[6]=i+'0';
s2[7]=i+'0';
s1[0]=i+'0';
s2[0]=i+'0';
f2.open(s1);
f3.open(s2);
while(getline(f1,s))
{
s.insert(1," *");
if(s[0]=='+')
{
countpos++;
if(countpos>start && countpos<=end)
f2<<s<<" </stop>"<<endl;
else
f3<<s<<" </stop>"<<endl;
}
else
{
countneg++;
if(countneg>start && countneg<=end)
f2<<s<<" </stop>"<<endl;
else
f3<<s<<" </stop>"<<endl;
}
}
f1.clear();
f1.seekg(0);
f2.close();
f3.close();
}
} | [
"gibreel.khan@gmail.com"
] | gibreel.khan@gmail.com |
e11fdec0dfb4ea1fc0ce7cc380650d889f1b1673 | 1151d4f8b636a36db18829f0fb03166a3c40b735 | /tests/posit/logic/logic.cpp | fa9cbe884666173d1bb39fc8f8ffc0dabe1d6a19 | [
"LicenseRef-scancode-public-domain",
"LGPL-3.0-only",
"MIT"
] | permissive | Afonso-2403/universal | 9f695344649f363d4faeaf8df4d1d033c258a952 | bddd1489de6476ee60bd45e473b918b6c7a4bce6 | refs/heads/main | 2023-08-05T06:54:48.006615 | 2021-09-16T11:42:42 | 2021-09-16T11:42:42 | 382,342,543 | 0 | 0 | MIT | 2021-07-02T12:40:39 | 2021-07-02T12:40:38 | null | UTF-8 | C++ | false | false | 20,202 | cpp | // logic.cpp :test suite runner for logic operators between posits
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
// minimum set of include files to reflect source code dependencies
// enable literals to simplify the testing codes
#define POSIT_ENABLE_LITERALS 1
#include <universal/number/posit/posit_impl.hpp>
#include <universal/number/posit/manipulators.hpp>
#include <universal/number/posit/math/classify.hpp>
#include <universal/number/quire/exceptions.hpp> // as we are catching quire exceptions
#include <universal/verification/posit_test_suite.hpp>
#define MANUAL_TESTING 0
#define STRESS_TESTING 0
int main()
try {
using namespace std;
using namespace sw::universal;
int nrOfFailedTestCases = 0;
#if MANUAL_TESTING
{
constexpr size_t nbits = 8;
constexpr size_t es = 0;
double nan = NAN;
double inf = INFINITY;
double normal = 0;
posit<nbits, es> pa(nan), pb(inf), pc(normal);
std::cout << pa << " " << pb << " " << pc << std::endl;
// showcasing the differences between posit and IEEE float
std::cout << "NaN == NaN: IEEE=" << (nan == nan ? "true" : "false") << " Posit=" << (pa == pa ? "true" : "false") << std::endl;
std::cout << "NaN == real: IEEE=" << (nan == normal ? "true" : "false") << " Posit=" << (pa == pc ? "true" : "false") << std::endl;
std::cout << "INF == INF: IEEE=" << (inf == inf ? "true" : "false") << " Posit=" << (pb == pb ? "true" : "false") << std::endl;
std::cout << "NaN != NaN: IEEE=" << (nan != nan ? "true" : "false") << " Posit=" << (pa != pb ? "true" : "false") << std::endl;
std::cout << "INF != INF: IEEE=" << (inf != inf ? "true" : "false") << " Posit=" << (pb != pb ? "true" : "false") << std::endl;
std::cout << "NaN <= real: IEEE=" << (nan <= normal ? "true" : "false") << " Posit=" << (pa <= pc ? "true" : "false") << std::endl;
std::cout << "NaN >= real: IEEE=" << (nan >= normal ? "true" : "false") << " Posit=" << (pa >= pc ? "true" : "false") << std::endl;
std::cout << "INF < real: IEEE=" << (inf < normal ? "true" : "false") << " Posit=" << (pa < pc ? "true" : "false") << std::endl;
std::cout << "INF > real: IEEE=" << (inf > normal ? "true" : "false") << " Posit=" << (pa > pc ? "true" : "false") << std::endl;
}
{
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<3, 0>(), "posit<3,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<3, 0>(), "posit<3,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<3, 0>(), "posit<3,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<3, 0>(), "posit<3,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<3, 0>(), "posit<3,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<3, 0>(), "posit<3,0>", ">=");
}
#else
posit<16, 1> p;
cout << "Logic: operator==()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<3, 0>(), "posit<3,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<4, 0>(), "posit<4,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<4, 1>(), "posit<4,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<5, 0>(), "posit<5,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<5, 1>(), "posit<5,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<5, 2>(), "posit<5,2>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<6, 0>(), "posit<6,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<6, 1>(), "posit<6,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<6, 2>(), "posit<6,2>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<6, 3>(), "posit<6,3>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<7, 0>(), "posit<7,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<7, 1>(), "posit<7,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<7, 2>(), "posit<7,2>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<7, 3>(), "posit<7,3>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<7, 4>(), "posit<7,4>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 0>(), "posit<8,0>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 1>(), "posit<8,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 2>(), "posit<8,2>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 3>(), "posit<8,3>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 4>(), "posit<8,4>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<8, 5>(), "posit<8,5>", "==");
if (!(p == 0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> == 0", "== int literal");
}
else {
ReportTestResult(0, "posit<16,1> == 0", "== int literal");
}
if (!(p == 0.0f)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> == 0.0", "== float literal");
}
else {
ReportTestResult(0, "posit<16,1> == 0.0", "== float literal");
}
if (!(p == 0.0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> == 0.0", "== double literal");
}
else {
ReportTestResult(0, "posit<16,1> == 0.0", "== double literal");
}
if (!(p == 0.0l)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> == 0.0", "== long double literal");
}
else {
ReportTestResult(0, "posit<16,1> == 0.0", "== long double literal");
}
cout << "Logic: operator!=()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<3, 0>(), "posit<3,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<4, 0>(), "posit<4,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<4, 1>(), "posit<4,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<5, 0>(), "posit<5,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<5, 1>(), "posit<5,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<5, 2>(), "posit<5,2>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<6, 0>(), "posit<6,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<6, 1>(), "posit<6,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<6, 2>(), "posit<6,2>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<6, 3>(), "posit<6,3>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<7, 0>(), "posit<7,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<7, 1>(), "posit<7,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<7, 2>(), "posit<7,2>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<7, 3>(), "posit<7,3>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<8, 0>(), "posit<8,0>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<8, 1>(), "posit<8,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<8, 2>(), "posit<8,2>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<8, 3>(), "posit<8,3>", "!=");
if (p != 0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> != 0", "!= int literal");
}
else {
ReportTestResult(0, "posit<16,1> != 0", "!= int literal");
}
if (p != 0.0f) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> != 0.0", "!= float literal");
}
else {
ReportTestResult(0, "posit<16,1> != 0.0", "!= float literal");
}
if (p != 0.0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> != 0.0", "!= double literal");
}
else {
ReportTestResult(0, "posit<16,1> != 0.0", "!= double literal");
}
if (p != 0.0l) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> != 0.0", "!= long double literal");
}
else {
ReportTestResult(0, "posit<16,1> != 0.0", "!= long double literal");
}
std::cout << "Logic: operator<()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<3, 0>(), "posit<3,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<4, 0>(), "posit<4,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<4, 1>(), "posit<4,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<5, 0>(), "posit<5,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<5, 1>(), "posit<5,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<5, 2>(), "posit<5,2>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<6, 0>(), "posit<6,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<6, 1>(), "posit<6,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<6, 2>(), "posit<6,2>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<6, 3>(), "posit<6,3>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<7, 0>(), "posit<7,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<7, 1>(), "posit<7,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<7, 2>(), "posit<7,2>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<7, 3>(), "posit<7,3>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<8, 0>(), "posit<8,0>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<8, 1>(), "posit<8,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<8, 2>(), "posit<8,2>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<8, 3>(), "posit<8,3>", "<");
if (p < 0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> < 0", "< int literal");
}
else {
ReportTestResult(0, "posit<16,1> < 0", "< int literal");
}
if (p < 0.0f) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> < 0.0", "< float literal");
}
else {
ReportTestResult(0, "posit<16,1> < 0.0", "< float literal");
}
if (p < 0.0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> < 0.0", "< double literal");
}
else {
ReportTestResult(0, "posit<16,1> < 0.0", "< double literal");
}
if (p < 0.0l) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> < 0.0", "< long double literal");
}
else {
ReportTestResult(0, "posit<16,1> < 0.0", "< long double literal");
}
std::cout << "Logic: operator<=()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<3, 0>(), "posit<3,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<4, 0>(), "posit<4,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<4, 1>(), "posit<4,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<5, 0>(), "posit<5,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<5, 1>(), "posit<5,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<5, 2>(), "posit<5,2>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<6, 0>(), "posit<6,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<6, 1>(), "posit<6,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<6, 2>(), "posit<6,2>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<6, 3>(), "posit<6,3>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<7, 0>(), "posit<7,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<7, 1>(), "posit<7,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<7, 2>(), "posit<7,2>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<7, 3>(), "posit<7,3>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<8, 0>(), "posit<8,0>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<8, 1>(), "posit<8,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<8, 2>(), "posit<8,2>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<8, 3>(), "posit<8,3>", "<=");
if (!(p <= 0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> <= 0", "<= int literal");
}
else {
ReportTestResult(0, "posit<16,1> <= 0", "<= int literal");
}
if (!(p <= 0.0f)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> <= 0.0", "<= float literal");
}
else {
ReportTestResult(0, "posit<16,1> <= 0.0", "<= float literal");
}
if (!(p <= 0.0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> <= 0.0", "<= double literal");
}
else {
ReportTestResult(0, "posit<16,1> <= 0.0", "<= double literal");
}
if (!(p <= 0.0l)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> <= 0.0", "<= long double literal");
}
else {
ReportTestResult(0, "posit<16,1> <= 0.0", "<= long double literal");
}
std::cout << "Logic: operator>()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<3, 0>(), "posit<3,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<4, 0>(), "posit<4,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<4, 1>(), "posit<4,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<5, 0>(), "posit<5,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<5, 1>(), "posit<5,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<5, 2>(), "posit<5,2>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<6, 0>(), "posit<6,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<6, 1>(), "posit<6,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<6, 2>(), "posit<6,2>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<6, 3>(), "posit<6,3>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<7, 0>(), "posit<7,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<7, 1>(), "posit<7,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<7, 2>(), "posit<7,2>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<7, 3>(), "posit<7,3>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<8, 0>(), "posit<8,0>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<8, 1>(), "posit<8,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<8, 2>(), "posit<8,2>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<8, 3>(), "posit<8,3>", ">");
if (p > 0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> > 0", "> int literal");
}
else {
ReportTestResult(0, "posit<16,1> > 0", "> int literal");
}
if (p > 0.0f) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> > 0.0", "> float literal");
}
else {
ReportTestResult(0, "posit<16,1> > 0.0", "> float literal");
}
if (p > 0.0) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> > 0.0", "> double literal");
}
else {
ReportTestResult(0, "posit<16,1> > 0.0", "> double literal");
}
if (p > 0.0l) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> > 0.0", "> long double literal");
}
else {
ReportTestResult(0, "posit<16,1> > 0.0", "> long double literal");
}
std::cout << "Logic: operator>=()" << endl;
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<3, 0>(), "posit<3,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<4, 0>(), "posit<4,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<4, 1>(), "posit<4,1>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<5, 0>(), "posit<5,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<5, 1>(), "posit<5,1>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<5, 2>(), "posit<5,2>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<6, 0>(), "posit<6,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<6, 1>(), "posit<6,1>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<6, 2>(), "posit<6,2>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<6, 3>(), "posit<6,3>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<7, 0>(), "posit<7,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<7, 1>(), "posit<7,1>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<7, 2>(), "posit<7,2>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<7, 3>(), "posit<7,3>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<8, 0>(), "posit<8,0>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<8, 1>(), "posit<8,1>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<8, 2>(), "posit<8,2>", ">=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<8, 3>(), "posit<8,3>", ">=");
if (!(p >= 0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> >= 0", ">= int literal");
}
else {
ReportTestResult(0, "posit<16,1> >= 0", ">= int literal");
}
if (!(p >= 0.0f)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> >= 0.0", ">= float literal");
}
else {
ReportTestResult(0, "posit<16,1> >= 0.0", ">= float literal");
}
if (!(p >= 0.0)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> >= 0.0", ">= double literal");
}
else {
ReportTestResult(0, "posit<16,1> >= 0.0", ">= double literal");
}
if (!(p >= 0.0l)) {
nrOfFailedTestCases += ReportTestResult(1, "posit<16,1> >= 0.0", ">= long double literal");
}
else {
ReportTestResult(0, "posit<16,1> >= 0.0", ">= long double literal");
}
#if STRESS_TESTING
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicEqual<16, 1>(), "posit<16,1>", "==");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicNotEqual<16, 1>(), "posit<16,1>", "!=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessThan<16, 1>(), "posit<16,1>", "<");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicLessOrEqualThan<16, 1>(), "posit<16,1>", "<=");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterThan<16, 1>(), "posit<16,1>", ">");
nrOfFailedTestCases += ReportTestResult(VerifyPositLogicGreaterOrEqualThan<16, 1>(), "posit<16,1>", ">=");
#endif // STRESS_TESTING
#endif // MANUAL_TESTING
return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
| [
"theo@stillwater-sc.com"
] | theo@stillwater-sc.com |
d5c41c43a62abde1c2d24b2f714a9991b15fdec7 | d15c9735399e609b5ef15fb342100cf5d3045b38 | /Day 18/main.cpp | 18f85db57b4f6eb3715d41437d6563bb9fa42c67 | [] | no_license | Wunkolo/AOC2020 | 60a927166fe5a2b201eec310a70b13eb9c934fda | f950dca77b7b7e603eed1d565566c07ea6725e2b | refs/heads/master | 2023-02-07T11:55:30.223057 | 2020-12-29T17:27:13 | 2020-12-29T17:27:13 | 317,777,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,867 | cpp | #include <iostream>
#include <cstdio>
#include <vector>
#include <numeric>
#include <algorithm>
#include <cctype>
#include <stack>
#include <queue>
template< bool Part2 = false >
std::uintmax_t Evaluate(const std::string& Expression)
{
std::stack<char> OperatorStack;
std::stack<std::uintmax_t> OperandStack;
const auto EvalTerm = [&OperatorStack, &OperandStack]()
{
const auto OperandA = OperandStack.top(); OperandStack.pop();
const auto OperandB = OperandStack.top(); OperandStack.pop();
switch(OperatorStack.top())
{
case '+': OperandStack.push(OperandA + OperandB); break;
case '*': OperandStack.push(OperandA * OperandB); break;
}
OperatorStack.pop();
};
for(const auto& Token : Expression)
{
switch(Token)
{
case '(': OperatorStack.push(Token); break;
case ')':
{
while(OperatorStack.size() && OperatorStack.top() != '(') EvalTerm();
if(OperatorStack.top() == '(') OperatorStack.pop();
break;
}
case '+':
case '*':
{
while(
OperatorStack.size() && OperatorStack.top() != '('
&& (!Part2 || (Part2 && Token == '*' && OperatorStack.top() == '+'))
) EvalTerm();
OperatorStack.push(Token);
break;
}
default:
if( std::isdigit(Token) ) OperandStack.push(Token - '0'); break;
}
}
while(OperatorStack.size()) EvalTerm();
return OperandStack.top();
}
int main()
{
std::string CurLine;
std::vector<std::string> Expressions;
while( std::getline(std::cin, CurLine) )
{
CurLine.erase(std::remove(CurLine.begin(), CurLine.end(), ' '), CurLine.end());
Expressions.push_back(CurLine);
}
std::cout << std::transform_reduce(
Expressions.cbegin(), Expressions.cend(),
0ull, std::plus<>(), Evaluate<false>
) << std::endl;
std::cout << std::transform_reduce(
Expressions.cbegin(), Expressions.cend(),
0ull, std::plus<>(), Evaluate<true>
) << std::endl;
} | [
"Wunkolo@gmail.com"
] | Wunkolo@gmail.com |
c67368e3146bb1c3c3fa62a8881fca72f0304f76 | ccd739c2ee26f7b31ff87eb6cd63d294f408fe07 | /src/otus_homework/include/otus_homework/adapters/generated/movable_adapter.hpp | eab0bb1cb060aa7325a76cec83380441171f223c | [
"MIT"
] | permissive | winmord/otus_homework | da61c7141010c436042e61140ff9a903dc0767c0 | 161cb5b63679c249eb5a94c0d2f66aa2ad6af634 | refs/heads/main | 2023-07-14T21:26:41.984178 | 2021-09-08T19:07:28 | 2021-09-08T19:07:28 | 367,152,883 | 0 | 0 | MIT | 2021-09-08T19:07:30 | 2021-05-13T19:24:34 | C++ | UTF-8 | C++ | false | false | 875 | hpp | #pragma once
#include <memory>
#include "otus_homework/globals.hpp"
#include "otus_homework/interfaces/i_uobject.hpp"
#include "otus_homework/interfaces/i_movable.hpp"
namespace tank_battle_server
{
class movable_adapter : public i_movable
{
public:
explicit movable_adapter(std::shared_ptr<i_uobject> obj)
: obj_(std::move(obj))
{}
movement_vector get_position() const override
{
return *ioc_provider::IoC.resolve<movement_vector>("tank.operations.i_movable:get_position", obj_);
}
void set_position(movement_vector const& position) override
{
ioc_provider::IoC.resolve("tank.operations.i_movable:set_position", obj_, position);
}
movement_vector get_velocity() const override
{
return *ioc_provider::IoC.resolve<movement_vector>("tank.operations.i_movable:get_velocity", obj_);
}
private:
std::shared_ptr<i_uobject> obj_;
};
} | [
"winmord@yandex.ru"
] | winmord@yandex.ru |
0885db61fd0baad3d61da2747ec118e96803f1cb | 873c2595f0207779ad09ea75bc391c590d71265f | /ui/cpp/mainwindow.h | e9c00ae82b57ae0a95eddd29710cb102554832cd | [] | no_license | mtboswell/mystuff | 113009d2c80f2097791e13e9ee861d246e751e57 | 184c05c6cc2a24a6260bb24e6e84e31638e535f8 | refs/heads/master | 2020-04-19T02:57:48.203005 | 2017-02-17T23:44:19 | 2017-02-17T23:44:19 | 67,952,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_addBackendButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"micah@boswellautomation.com"
] | micah@boswellautomation.com |
28abe6781841afbbbc25261f6c737154ebba34ed | c56b86c0c098948a1aa7ca3b4a25c7be47af2f45 | /Qt/my_programm/show_films/src/version.hpp | 354deba3cc50f2ca8999a8d15808aae32639b008 | [] | no_license | jianglin2045/mega_GIT | 764e460282f1242be5530c8e20e498119f20f827 | 7224c3cf50bf029ff127a3e3db0bb3698af28aa4 | refs/heads/master | 2023-02-13T19:41:30.407632 | 2021-01-11T21:09:31 | 2021-01-11T21:09:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | hpp | #ifndef VERSION_HPP
#define VERSION_HPP
//-----
#define VER_MAJOR 1
#define VER_MINOR 7
#define VER_PATCH 0
#define VER_BUILD 898
#define VER_STR "1.7.0.898"
//-----
#endif // VERSION_HPP
| [
"tux4096@gmail.com"
] | tux4096@gmail.com |
6d3742b6e8d54ff3ac1b7e10049326681bc1a2e0 | 006f035d65012b7c5af15d54716407a276a096a8 | /dependencies/include/cgal/CGAL/GMP_arithmetic_kernel.h | af363e7b16a1b3c6bea23313577cb739d7ad956c | [] | no_license | rosecodym/space-boundary-tool | 4ce5b67fd96ec9b66f45aca60e0e69f4f8936e93 | 300db4084cd19b092bdf2e8432da065daeaa7c55 | refs/heads/master | 2020-12-24T06:51:32.828579 | 2016-08-12T16:13:51 | 2016-08-12T16:13:51 | 65,566,229 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,458 | h | // Copyright (c) 2008 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/releases/CGAL-4.1-branch/Arithmetic_kernel/include/CGAL/GMP_arithmetic_kernel.h $
// $Id: GMP_arithmetic_kernel.h 67093 2012-01-13 11:22:39Z lrineau $
//
// Author(s) : Michael Hemmer <mhemmer@uni-mainz.de>
//
// ============================================================================
//
// \brief provide class Arithmetic_kernel, a collection of number types.
//
#ifndef CGAL_GMP_ARITHMETIC_KERNEL_H
#define CGAL_GMP_ARITHMETIC_KERNEL_H
#ifdef CGAL_USE_GMP
#include <CGAL/basic.h>
#include <CGAL/Arithmetic_kernel/Arithmetic_kernel_base.h>
#include <CGAL/Get_arithmetic_kernel.h>
#include <CGAL/Gmpz.h>
#include <CGAL/Gmpq.h>
#ifdef CGAL_USE_MPFI
#define CGAL_HAS_GMP_ARITHMETIC_KERNEL
#include <CGAL/Gmpfr.h>
#include <CGAL/Gmpfi.h>
#endif //CGAL_USE_MPFI
namespace CGAL {
/*! \ingroup CGAL_Arithmetic_kernel
* \brief The GMP set of exact number types
*/
class GMP_arithmetic_kernel : public internal::Arithmetic_kernel_base {
public:
typedef CGAL::Gmpz Integer;
typedef CGAL::Gmpq Rational;
#ifdef CGAL_USE_MPFI
typedef CGAL::Gmpfr Bigfloat;
typedef CGAL::Gmpfi Bigfloat_interval;
#endif //CGAL_USE_MPFI
};
template <>
struct Get_arithmetic_kernel<Gmpz> {
typedef GMP_arithmetic_kernel Arithmetic_kernel;
};
template <>
struct Get_arithmetic_kernel<Gmpq>{
typedef GMP_arithmetic_kernel Arithmetic_kernel;
};
#ifdef CGAL_USE_MPFI
template <>
struct Get_arithmetic_kernel<Gmpfr>{
typedef GMP_arithmetic_kernel Arithmetic_kernel;
};
template <>
struct Get_arithmetic_kernel<Gmpfi>{
typedef GMP_arithmetic_kernel Arithmetic_kernel;
};
#endif //CGAL_USE_MPFI
} //namespace CGAL
#endif //CGAL_USE_GMP
#endif // CGAL_ARITHMETIC_KERNEL_H
// EOF
| [
"cmrose@lbl.gov"
] | cmrose@lbl.gov |
eea022acaab5404bd7f7758553de57aae5d09845 | 2098c74a59133c985e10f57a901bc5839a6d1333 | /Source/XrGameCS/alife_group_abstract.cpp | d4642a76a917be430ebb04fd1f8152a4dc677a9f | [] | no_license | ChuniMuni/XRayEngine | 28672b4c5939e95c6dfb24c9514041dd25cfa306 | cdb13c23552fd86409b6e4e2925ac78064ee8739 | refs/heads/master | 2023-04-02T01:04:01.134317 | 2021-04-10T07:44:41 | 2021-04-10T07:44:41 | 266,738,168 | 1 | 0 | null | 2021-04-10T07:44:41 | 2020-05-25T09:27:11 | C++ | UTF-8 | C++ | false | false | 6,912 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : alife_group_abstract.cpp
// Created : 27.10.2005
// Modified : 27.10.2005
// Author : Dmitriy Iassenev
// Description : ALife group abstract class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "xrServer_Objects_ALife.h"
#include "ai_space.h"
#include "alife_simulator.h"
#include "alife_object_registry.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "alife_schedule_registry.h"
#include "alife_graph_registry.h"
#include "game_level_cross_table.h"
#include "level_graph.h"
void CSE_ALifeGroupAbstract::switch_online ()
{
CSE_ALifeDynamicObject *object = smart_cast<CSE_ALifeDynamicObject*>(this);
VERIFY (object);
R_ASSERT (!object->m_bOnline);
object->m_bOnline = true;
ALife::OBJECT_IT I = m_tpMembers.begin(), B = I;
ALife::OBJECT_IT E = m_tpMembers.end();
u32 N = (u32)(E - I);
for ( ; I != E; ++I) {
CSE_ALifeDynamicObject *J = ai().alife().objects().object(*I);
if (m_bCreateSpawnPositions) {
J->o_Position = object->o_Position;
J->m_tNodeID = object->m_tNodeID;
CSE_ALifeMonsterAbstract *l_tpALifeMonsterAbstract = smart_cast<CSE_ALifeMonsterAbstract*>(J);
if (l_tpALifeMonsterAbstract)
l_tpALifeMonsterAbstract->o_torso.yaw = angle_normalize_signed((I - B)/N*PI_MUL_2);
}
object->alife().add_online (J, false);
}
m_bCreateSpawnPositions = false;
object->alife().scheduled().remove (object);
object->alife().graph().remove (object,object->m_tGraphID,false);
}
void CSE_ALifeGroupAbstract::switch_offline ()
{
CSE_ALifeDynamicObject *object = smart_cast<CSE_ALifeDynamicObject*>(base());
VERIFY (object);
R_ASSERT (object->m_bOnline);
object->m_bOnline = false;
ALife::OBJECT_IT I = m_tpMembers.begin();
ALife::OBJECT_IT E = m_tpMembers.end();
if (I != E) {
CSE_ALifeMonsterAbstract *tpGroupMember = smart_cast<CSE_ALifeMonsterAbstract*>(ai().alife().objects().object(*I));
CSE_ALifeMonsterAbstract *tpGroup = smart_cast<CSE_ALifeMonsterAbstract*>(this);
if (tpGroupMember && tpGroup) {
tpGroup->m_fCurSpeed = tpGroup->m_fCurrentLevelGoingSpeed;
tpGroup->o_Position = tpGroupMember->o_Position;
u32 dwNodeID = tpGroup->m_tNodeID;
tpGroup->m_tGraphID = ai().cross_table().vertex(dwNodeID).game_vertex_id();
tpGroup->m_fDistanceToPoint = ai().cross_table().vertex(dwNodeID).distance();
tpGroup->m_tNextGraphID = tpGroup->m_tGraphID;
u16 wNeighbourCount = ai().game_graph().vertex(tpGroup->m_tGraphID)->edge_count();
CGameGraph::const_iterator i,e;
ai().game_graph().begin (tpGroup->m_tGraphID,i,e);
tpGroup->m_tPrevGraphID = (*(i + object->randI(0,wNeighbourCount))).vertex_id();
}
object->alife().remove_online (tpGroupMember,false);
++I;
}
for ( ; I != E; ++I)
object->alife().remove_online (ai().alife().objects().object(*I),false);
object->alife().scheduled().add (object);
object->alife().graph().add (object,object->m_tGraphID,false);
}
bool CSE_ALifeGroupAbstract::synchronize_location ()
{
if (m_tpMembers.empty())
return (true);
CSE_ALifeDynamicObject *object = smart_cast<CSE_ALifeDynamicObject*>(base());
VERIFY (object);
ALife::OBJECT_VECTOR::iterator I = m_tpMembers.begin();
ALife::OBJECT_VECTOR::iterator E = m_tpMembers.end();
for ( ; I != E; ++I)
ai().alife().objects().object(*I)->synchronize_location ();
CSE_ALifeDynamicObject &member = *ai().alife().objects().object(*I);
object->o_Position = member.o_Position;
object->m_tNodeID = member.m_tNodeID;
if (object->m_tGraphID != member.m_tGraphID) {
if (!object->m_bOnline)
object->alife().graph().change (object,object->m_tGraphID,member.m_tGraphID);
else
object->m_tGraphID = member.m_tGraphID;
}
object->m_fDistance = member.m_fDistance;
return (true);
}
void CSE_ALifeGroupAbstract::try_switch_online ()
{
CSE_ALifeDynamicObject *I = smart_cast<CSE_ALifeDynamicObject*>(base());
VERIFY (I);
// checking if the object is not an empty group of objects
if (m_tpMembers.empty())
return;
I->try_switch_online ();
}
void CSE_ALifeGroupAbstract::try_switch_offline ()
{
// checking if group is not empty
if (m_tpMembers.empty())
return;
// so, we have a group of objects
// therefore check all the group members if they are ready to switch offline
CSE_ALifeDynamicObject *I = smart_cast<CSE_ALifeDynamicObject*>(base());
VERIFY (I);
// iterating on group members
u32 i = 0, N = (u32)m_tpMembers.size();
for (; i < N; ++i) {
// casting group member to the abstract monster to get access to the Health property
CSE_ALifeMonsterAbstract *tpGroupMember = smart_cast<CSE_ALifeMonsterAbstract*>(ai().alife().objects().object(m_tpMembers[i]));
if (!tpGroupMember)
continue;
// check if monster is not dead
if (tpGroupMember->g_Alive()) {
// so, monster is not dead
// checking if the object is _not_ ready to switch offline
if (!tpGroupMember->can_switch_offline())
continue;
if (!tpGroupMember->can_switch_online())
// so, it is not ready, breaking a cycle, because we can't
// switch group offline since not all the group members are ready
// to switch offline
break;
if (I->alife().graph().actor()->o_Position.distance_to(tpGroupMember->o_Position) <= I->alife().offline_distance())
// so, it is not ready, breaking a cycle, because we can't
// switch group offline since not all the group members are ready
// to switch offline
break;
continue;
}
// detach object from the group
tpGroupMember->set_health ( 0.f );
tpGroupMember->m_bDirectControl = true;
m_tpMembers.erase (m_tpMembers.begin() + i);
tpGroupMember->m_bOnline = false;
CSE_ALifeInventoryItem *item = smart_cast<CSE_ALifeInventoryItem*>(tpGroupMember);
if (item && item->attached()) {
CSE_ALifeDynamicObject *object = ai().alife().objects().object(tpGroupMember->ID_Parent,true);
if (object)
object->detach (item);
}
// store the __new separate object into the registries
I->alife().register_object (tpGroupMember);
// and remove it from the graph point but do not remove it from the current level map
CSE_ALifeInventoryItem *l_tpALifeInventoryItem = smart_cast<CSE_ALifeInventoryItem*>(tpGroupMember);
if (!l_tpALifeInventoryItem || !l_tpALifeInventoryItem->attached())
I->alife().graph().remove (tpGroupMember,tpGroupMember->m_tGraphID,false);
tpGroupMember->m_bOnline = true;
--m_wCount;
--i;
--N;
}
// checking if group is not empty
if (m_tpMembers.empty())
return;
if (!I->can_switch_offline())
return;
if (I->can_switch_online() || (i == N))
I->alife().switch_offline (I);
}
bool CSE_ALifeGroupAbstract::redundant () const
{
return (m_tpMembers.empty());
}
| [
"i-sobolevskiy@mail.ru"
] | i-sobolevskiy@mail.ru |
9ab4bac6830ad6205e1c56f6d4b389ddb49b138d | 9c35568f878d76820dd9e38b2d407311314fde8d | /telegram-bot-api/td/td/telegram/Photo.cpp | 4c498bae030ad68428a158f32dfde5ed86f7ab17 | [
"BSL-1.0",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | rifaiirfan41/lisensi | 3cefea88cb504b6cdfecf9df8c971d3e3296041e | 1f82769982d015de0e52a3d80b282307a121be8e | refs/heads/master | 2023-07-10T00:39:06.698567 | 2021-08-23T23:55:02 | 2021-08-23T23:55:02 | 382,179,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,199 | cpp | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/Photo.h"
#include "td/telegram/secret_api.h"
#include "td/telegram/telegram_api.h"
#include "td/telegram/files/FileEncryptionKey.h"
#include "td/telegram/files/FileLocation.h"
#include "td/telegram/files/FileManager.h"
#include "td/telegram/net/DcId.h"
#include "td/utils/algorithm.h"
#include "td/utils/base64.h"
#include "td/utils/common.h"
#include "td/utils/format.h"
#include "td/utils/HttpUrl.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/Random.h"
#include <algorithm>
#include <cmath>
#include <limits>
namespace td {
static uint16 get_dimension(int32 size, const char *source) {
if (size < 0 || size > 65535) {
LOG(ERROR) << "Wrong image dimension = " << size << " from " << source;
return 0;
}
return narrow_cast<uint16>(size);
}
Dimensions get_dimensions(int32 width, int32 height, const char *source) {
Dimensions result;
result.width = get_dimension(width, source);
result.height = get_dimension(height, source);
if (result.width == 0 || result.height == 0) {
result.width = 0;
result.height = 0;
}
return result;
}
static uint32 get_pixel_count(const Dimensions &dimensions) {
return static_cast<uint32>(dimensions.width) * static_cast<uint32>(dimensions.height);
}
bool operator==(const Dimensions &lhs, const Dimensions &rhs) {
return lhs.width == rhs.width && lhs.height == rhs.height;
}
bool operator!=(const Dimensions &lhs, const Dimensions &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const Dimensions &dimensions) {
return string_builder << "(" << dimensions.width << ", " << dimensions.height << ")";
}
td_api::object_ptr<td_api::minithumbnail> get_minithumbnail_object(const string &packed) {
if (packed.size() < 3) {
return nullptr;
}
if (packed[0] == '\x01') {
static const string header =
base64_decode(
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACgcHiMeGSgjISMtKygwPGRBPDc3PHtYXUlkkYCZlo+AjIqgtObDoKrarYqMyP/L2u71////"
"m8H///"
"/6/+b9//j/2wBDASstLTw1PHZBQXb4pYyl+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj/"
"wAARCAAAAAADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/"
"8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0R"
"FRkd"
"ISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2"
"uHi4"
"+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/"
"8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkN"
"ERUZ"
"HSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2"
"Nna4"
"uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwA=")
.move_as_ok();
static const string footer = base64_decode("/9k=").move_as_ok();
auto result = td_api::make_object<td_api::minithumbnail>();
result->height_ = static_cast<unsigned char>(packed[1]);
result->width_ = static_cast<unsigned char>(packed[2]);
result->data_ = PSTRING() << header.substr(0, 164) << packed[1] << header[165] << packed[2] << header.substr(167)
<< packed.substr(3) << footer;
return result;
}
return nullptr;
}
static td_api::object_ptr<td_api::ThumbnailFormat> get_thumbnail_format_object(PhotoFormat format) {
switch (format) {
case PhotoFormat::Jpeg:
return td_api::make_object<td_api::thumbnailFormatJpeg>();
case PhotoFormat::Png:
return td_api::make_object<td_api::thumbnailFormatPng>();
case PhotoFormat::Webp:
return td_api::make_object<td_api::thumbnailFormatWebp>();
case PhotoFormat::Gif:
return td_api::make_object<td_api::thumbnailFormatGif>();
case PhotoFormat::Tgs:
return td_api::make_object<td_api::thumbnailFormatTgs>();
case PhotoFormat::Mpeg4:
return td_api::make_object<td_api::thumbnailFormatMpeg4>();
default:
UNREACHABLE();
return nullptr;
}
}
static StringBuilder &operator<<(StringBuilder &string_builder, PhotoFormat format) {
switch (format) {
case PhotoFormat::Jpeg:
return string_builder << "jpg";
case PhotoFormat::Png:
return string_builder << "png";
case PhotoFormat::Webp:
return string_builder << "webp";
case PhotoFormat::Gif:
return string_builder << "gif";
case PhotoFormat::Tgs:
return string_builder << "tgs";
case PhotoFormat::Mpeg4:
return string_builder << "mp4";
default:
UNREACHABLE();
return string_builder;
}
}
static FileId register_photo(FileManager *file_manager, const PhotoSizeSource &source, int64 id, int64 access_hash,
std::string file_reference,
tl_object_ptr<telegram_api::fileLocationToBeDeprecated> &&location,
DialogId owner_dialog_id, int32 file_size, DcId dc_id, PhotoFormat format) {
int32 local_id = location->local_id_;
int64 volume_id = location->volume_id_;
LOG(DEBUG) << "Receive " << format << " photo of type " << source.get_file_type() << " in [" << dc_id << ","
<< volume_id << "," << local_id << "]. Id: (" << id << ", " << access_hash << ")";
auto suggested_name = PSTRING() << static_cast<uint64>(volume_id) << "_" << static_cast<uint64>(local_id) << '.'
<< format;
auto file_location_source = owner_dialog_id.get_type() == DialogType::SecretChat ? FileLocationSource::FromUser
: FileLocationSource::FromServer;
return file_manager->register_remote(
FullRemoteFileLocation(source, id, access_hash, local_id, volume_id, dc_id, std::move(file_reference)),
file_location_source, owner_dialog_id, file_size, 0, std::move(suggested_name));
}
ProfilePhoto get_profile_photo(FileManager *file_manager, UserId user_id, int64 user_access_hash,
tl_object_ptr<telegram_api::UserProfilePhoto> &&profile_photo_ptr) {
ProfilePhoto result;
int32 profile_photo_id =
profile_photo_ptr == nullptr ? telegram_api::userProfilePhotoEmpty::ID : profile_photo_ptr->get_id();
switch (profile_photo_id) {
case telegram_api::userProfilePhotoEmpty::ID:
break;
case telegram_api::userProfilePhoto::ID: {
auto profile_photo = move_tl_object_as<telegram_api::userProfilePhoto>(profile_photo_ptr);
auto dc_id = DcId::create(profile_photo->dc_id_);
result.has_animation = (profile_photo->flags_ & telegram_api::userProfilePhoto::HAS_VIDEO_MASK) != 0;
result.id = profile_photo->photo_id_;
result.minithumbnail = profile_photo->stripped_thumb_.as_slice().str();
result.small_file_id =
register_photo(file_manager, {DialogId(user_id), user_access_hash, false}, result.id, 0, "",
std::move(profile_photo->photo_small_), DialogId(), 0, dc_id, PhotoFormat::Jpeg);
result.big_file_id =
register_photo(file_manager, {DialogId(user_id), user_access_hash, true}, result.id, 0, "",
std::move(profile_photo->photo_big_), DialogId(), 0, dc_id, PhotoFormat::Jpeg);
break;
}
default:
UNREACHABLE();
break;
}
return result;
}
tl_object_ptr<td_api::profilePhoto> get_profile_photo_object(FileManager *file_manager,
const ProfilePhoto &profile_photo) {
if (!profile_photo.small_file_id.is_valid()) {
return nullptr;
}
return td_api::make_object<td_api::profilePhoto>(
profile_photo.id, file_manager->get_file_object(profile_photo.small_file_id),
file_manager->get_file_object(profile_photo.big_file_id), get_minithumbnail_object(profile_photo.minithumbnail),
profile_photo.has_animation);
}
bool operator==(const ProfilePhoto &lhs, const ProfilePhoto &rhs) {
bool location_differs = lhs.small_file_id != rhs.small_file_id || lhs.big_file_id != rhs.big_file_id;
bool id_differs;
if (lhs.id == -1 && rhs.id == -1) {
// group chat photo
id_differs = location_differs;
} else {
id_differs = lhs.id != rhs.id;
}
if (location_differs) {
LOG_IF(ERROR, !id_differs) << "Photo " << lhs.id << " location has changed. First profilePhoto: " << lhs
<< ", second profilePhoto: " << rhs;
return false;
}
return lhs.has_animation == rhs.has_animation && lhs.minithumbnail == rhs.minithumbnail && !id_differs;
}
bool operator!=(const ProfilePhoto &lhs, const ProfilePhoto &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const ProfilePhoto &profile_photo) {
return string_builder << "<ID = " << profile_photo.id << ", small_file_id = " << profile_photo.small_file_id
<< ", big_file_id = " << profile_photo.big_file_id
<< ", has_animation = " << profile_photo.has_animation << ">";
}
DialogPhoto get_dialog_photo(FileManager *file_manager, DialogId dialog_id, int64 dialog_access_hash,
tl_object_ptr<telegram_api::ChatPhoto> &&chat_photo_ptr) {
int32 chat_photo_id = chat_photo_ptr == nullptr ? telegram_api::chatPhotoEmpty::ID : chat_photo_ptr->get_id();
DialogPhoto result;
switch (chat_photo_id) {
case telegram_api::chatPhotoEmpty::ID:
break;
case telegram_api::chatPhoto::ID: {
auto chat_photo = move_tl_object_as<telegram_api::chatPhoto>(chat_photo_ptr);
auto dc_id = DcId::create(chat_photo->dc_id_);
result.has_animation = (chat_photo->flags_ & telegram_api::chatPhoto::HAS_VIDEO_MASK) != 0;
result.minithumbnail = chat_photo->stripped_thumb_.as_slice().str();
result.small_file_id =
register_photo(file_manager, {dialog_id, dialog_access_hash, false}, 0, 0, "",
std::move(chat_photo->photo_small_), DialogId(), 0, dc_id, PhotoFormat::Jpeg);
result.big_file_id = register_photo(file_manager, {dialog_id, dialog_access_hash, true}, 0, 0, "",
std::move(chat_photo->photo_big_), DialogId(), 0, dc_id, PhotoFormat::Jpeg);
break;
}
default:
UNREACHABLE();
break;
}
return result;
}
tl_object_ptr<td_api::chatPhotoInfo> get_chat_photo_info_object(FileManager *file_manager,
const DialogPhoto *dialog_photo) {
if (dialog_photo == nullptr || !dialog_photo->small_file_id.is_valid()) {
return nullptr;
}
return td_api::make_object<td_api::chatPhotoInfo>(file_manager->get_file_object(dialog_photo->small_file_id),
file_manager->get_file_object(dialog_photo->big_file_id),
get_minithumbnail_object(dialog_photo->minithumbnail),
dialog_photo->has_animation);
}
vector<FileId> dialog_photo_get_file_ids(const DialogPhoto &dialog_photo) {
vector<FileId> result;
if (dialog_photo.small_file_id.is_valid()) {
result.push_back(dialog_photo.small_file_id);
}
if (dialog_photo.big_file_id.is_valid()) {
result.push_back(dialog_photo.big_file_id);
}
return result;
}
DialogPhoto as_fake_dialog_photo(const Photo &photo) {
DialogPhoto result;
if (!photo.is_empty()) {
for (auto &size : photo.photos) {
if (size.type == 'a') {
result.small_file_id = size.file_id;
} else if (size.type == 'c') {
result.big_file_id = size.file_id;
}
}
result.has_animation = !photo.animations.empty();
if (!result.small_file_id.is_valid() || !result.big_file_id.is_valid()) {
LOG(ERROR) << "Failed to convert " << photo << " to chat photo";
return DialogPhoto();
}
}
return result;
}
ProfilePhoto as_profile_photo(FileManager *file_manager, UserId user_id, int64 user_access_hash, const Photo &photo) {
ProfilePhoto result;
static_cast<DialogPhoto &>(result) = as_fake_dialog_photo(photo);
if (!result.small_file_id.is_valid()) {
return result;
}
auto reregister_photo = [&](bool is_big, FileId file_id) {
auto file_view = file_manager->get_file_view(file_id);
CHECK(file_view.has_remote_location());
auto remote = file_view.remote_location();
CHECK(remote.is_photo());
CHECK(!remote.is_web());
remote.set_source({DialogId(user_id), user_access_hash, is_big});
return file_manager->register_remote(std::move(remote), FileLocationSource::FromServer, DialogId(),
file_view.size(), file_view.expected_size(), file_view.remote_name());
};
result.id = photo.id.get();
result.small_file_id = reregister_photo(false, result.small_file_id);
result.big_file_id = reregister_photo(true, result.big_file_id);
return result;
}
bool operator==(const DialogPhoto &lhs, const DialogPhoto &rhs) {
return lhs.small_file_id == rhs.small_file_id && lhs.big_file_id == rhs.big_file_id &&
lhs.minithumbnail == rhs.minithumbnail && lhs.has_animation == rhs.has_animation;
}
bool operator!=(const DialogPhoto &lhs, const DialogPhoto &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const DialogPhoto &dialog_photo) {
return string_builder << "<small_file_id = " << dialog_photo.small_file_id
<< ", big_file_id = " << dialog_photo.big_file_id
<< ", has_animation = " << dialog_photo.has_animation << ">";
}
PhotoSize get_secret_thumbnail_photo_size(FileManager *file_manager, BufferSlice bytes, DialogId owner_dialog_id,
int32 width, int32 height) {
if (bytes.empty()) {
return PhotoSize();
}
PhotoSize res;
res.type = 't';
res.dimensions = get_dimensions(width, height, "get_secret_thumbnail_photo_size");
res.size = narrow_cast<int32>(bytes.size());
// generate some random remote location to save
auto dc_id = DcId::invalid();
auto local_id = -(Random::secure_int32() & 0x7FFFFFFF);
auto volume_id = Random::secure_int64();
res.file_id = file_manager->register_remote(
FullRemoteFileLocation(PhotoSizeSource(FileType::EncryptedThumbnail, 't'), 0, 0, local_id, volume_id, dc_id,
string()),
FileLocationSource::FromServer, owner_dialog_id, res.size, 0,
PSTRING() << static_cast<uint64>(volume_id) << "_" << static_cast<uint64>(local_id) << ".jpg");
file_manager->set_content(res.file_id, std::move(bytes));
return res;
}
Variant<PhotoSize, string> get_photo_size(FileManager *file_manager, PhotoSizeSource source, int64 id,
int64 access_hash, std::string file_reference, DcId dc_id,
DialogId owner_dialog_id, tl_object_ptr<telegram_api::PhotoSize> &&size_ptr,
PhotoFormat format) {
CHECK(size_ptr != nullptr);
tl_object_ptr<telegram_api::fileLocationToBeDeprecated> location;
string type;
PhotoSize res;
BufferSlice content;
switch (size_ptr->get_id()) {
case telegram_api::photoSizeEmpty::ID:
return std::move(res);
case telegram_api::photoSize::ID: {
auto size = move_tl_object_as<telegram_api::photoSize>(size_ptr);
type = std::move(size->type_);
location = std::move(size->location_);
res.dimensions = get_dimensions(size->w_, size->h_, "photoSize");
res.size = size->size_;
break;
}
case telegram_api::photoCachedSize::ID: {
auto size = move_tl_object_as<telegram_api::photoCachedSize>(size_ptr);
type = std::move(size->type_);
location = std::move(size->location_);
CHECK(size->bytes_.size() <= static_cast<size_t>(std::numeric_limits<int32>::max()));
res.dimensions = get_dimensions(size->w_, size->h_, "photoCachedSize");
res.size = static_cast<int32>(size->bytes_.size());
content = std::move(size->bytes_);
break;
}
case telegram_api::photoStrippedSize::ID: {
auto size = move_tl_object_as<telegram_api::photoStrippedSize>(size_ptr);
if (format != PhotoFormat::Jpeg) {
LOG(ERROR) << "Receive unexpected JPEG minithumbnail in photo of format " << format;
return std::move(res);
}
return size->bytes_.as_slice().str();
}
case telegram_api::photoSizeProgressive::ID: {
auto size = move_tl_object_as<telegram_api::photoSizeProgressive>(size_ptr);
if (size->sizes_.empty()) {
LOG(ERROR) << "Receive " << to_string(size);
return std::move(res);
}
std::sort(size->sizes_.begin(), size->sizes_.end());
type = std::move(size->type_);
location = std::move(size->location_);
res.dimensions = get_dimensions(size->w_, size->h_, "photoSizeProgressive");
res.size = size->sizes_.back();
size->sizes_.pop_back();
res.progressive_sizes = std::move(size->sizes_);
break;
}
case telegram_api::photoPathSize::ID: {
auto size = move_tl_object_as<telegram_api::photoPathSize>(size_ptr);
if (format != PhotoFormat::Tgs && format != PhotoFormat::Webp) {
LOG(ERROR) << "Receive unexpected SVG minithumbnail in photo of format " << format;
return std::move(res);
}
return size->bytes_.as_slice().str();
}
default:
UNREACHABLE();
break;
}
if (type.size() != 1) {
res.type = 0;
LOG(ERROR) << "Wrong photoSize \"" << type << "\" " << res;
} else {
res.type = static_cast<uint8>(type[0]);
}
if (source.get_type() == PhotoSizeSource::Type::Thumbnail) {
source.thumbnail().thumbnail_type = res.type;
}
res.file_id = register_photo(file_manager, source, id, access_hash, file_reference, std::move(location),
owner_dialog_id, res.size, dc_id, format);
if (!content.empty()) {
file_manager->set_content(res.file_id, std::move(content));
}
return std::move(res);
}
AnimationSize get_animation_size(FileManager *file_manager, PhotoSizeSource source, int64 id, int64 access_hash,
std::string file_reference, DcId dc_id, DialogId owner_dialog_id,
tl_object_ptr<telegram_api::videoSize> &&size) {
CHECK(size != nullptr);
AnimationSize res;
if (size->type_ != "v" && size->type_ != "u") {
LOG(ERROR) << "Wrong videoSize \"" << size->type_ << "\" in " << to_string(size);
}
res.type = static_cast<uint8>(size->type_[0]);
res.dimensions = get_dimensions(size->w_, size->h_, "get_animation_size");
res.size = size->size_;
if ((size->flags_ & telegram_api::videoSize::VIDEO_START_TS_MASK) != 0) {
res.main_frame_timestamp = size->video_start_ts_;
}
if (source.get_type() == PhotoSizeSource::Type::Thumbnail) {
source.thumbnail().thumbnail_type = res.type;
}
res.file_id = register_photo(file_manager, source, id, access_hash, file_reference, std::move(size->location_),
owner_dialog_id, res.size, dc_id, PhotoFormat::Mpeg4);
return res;
}
PhotoSize get_web_document_photo_size(FileManager *file_manager, FileType file_type, DialogId owner_dialog_id,
tl_object_ptr<telegram_api::WebDocument> web_document_ptr) {
if (web_document_ptr == nullptr) {
return {};
}
FileId file_id;
vector<tl_object_ptr<telegram_api::DocumentAttribute>> attributes;
int32 size = 0;
string mime_type;
switch (web_document_ptr->get_id()) {
case telegram_api::webDocument::ID: {
auto web_document = move_tl_object_as<telegram_api::webDocument>(web_document_ptr);
auto r_http_url = parse_url(web_document->url_);
if (r_http_url.is_error()) {
LOG(ERROR) << "Can't parse URL " << web_document->url_;
return {};
}
auto http_url = r_http_url.move_as_ok();
auto url = http_url.get_url();
file_id = file_manager->register_remote(FullRemoteFileLocation(file_type, url, web_document->access_hash_),
FileLocationSource::FromServer, owner_dialog_id, 0, web_document->size_,
get_url_query_file_name(http_url.query_));
size = web_document->size_;
mime_type = std::move(web_document->mime_type_);
attributes = std::move(web_document->attributes_);
break;
}
case telegram_api::webDocumentNoProxy::ID: {
auto web_document = move_tl_object_as<telegram_api::webDocumentNoProxy>(web_document_ptr);
if (web_document->url_.find('.') == string::npos) {
LOG(ERROR) << "Receive invalid URL " << web_document->url_;
return {};
}
auto r_file_id = file_manager->from_persistent_id(web_document->url_, file_type);
if (r_file_id.is_error()) {
LOG(ERROR) << "Can't register URL: " << r_file_id.error();
return {};
}
file_id = r_file_id.move_as_ok();
size = web_document->size_;
mime_type = std::move(web_document->mime_type_);
attributes = std::move(web_document->attributes_);
break;
}
default:
UNREACHABLE();
}
CHECK(file_id.is_valid());
bool is_animation = mime_type == "video/mp4";
bool is_gif = mime_type == "image/gif";
Dimensions dimensions;
for (auto &attribute : attributes) {
switch (attribute->get_id()) {
case telegram_api::documentAttributeImageSize::ID: {
auto image_size = move_tl_object_as<telegram_api::documentAttributeImageSize>(attribute);
dimensions = get_dimensions(image_size->w_, image_size->h_, "web documentAttributeImageSize");
break;
}
case telegram_api::documentAttributeAnimated::ID:
case telegram_api::documentAttributeHasStickers::ID:
case telegram_api::documentAttributeSticker::ID:
case telegram_api::documentAttributeVideo::ID:
case telegram_api::documentAttributeAudio::ID:
LOG(ERROR) << "Unexpected web document attribute " << to_string(attribute);
break;
case telegram_api::documentAttributeFilename::ID:
break;
default:
UNREACHABLE();
}
}
PhotoSize s;
s.type = is_animation ? 'v' : (is_gif ? 'g' : (file_type == FileType::Thumbnail ? 't' : 'n'));
s.dimensions = dimensions;
s.size = size;
s.file_id = file_id;
return s;
}
td_api::object_ptr<td_api::thumbnail> get_thumbnail_object(FileManager *file_manager, const PhotoSize &photo_size,
PhotoFormat format) {
if (!photo_size.file_id.is_valid()) {
return nullptr;
}
if (format == PhotoFormat::Jpeg && photo_size.type == 'g') {
format = PhotoFormat::Gif;
}
return td_api::make_object<td_api::thumbnail>(get_thumbnail_format_object(format), photo_size.dimensions.width,
photo_size.dimensions.height,
file_manager->get_file_object(photo_size.file_id));
}
static tl_object_ptr<td_api::photoSize> get_photo_size_object(FileManager *file_manager, const PhotoSize *photo_size) {
if (photo_size == nullptr || !photo_size->file_id.is_valid()) {
return nullptr;
}
return td_api::make_object<td_api::photoSize>(
photo_size->type ? std::string(1, static_cast<char>(photo_size->type))
: std::string(), // TODO replace string type with integer type
file_manager->get_file_object(photo_size->file_id), photo_size->dimensions.width, photo_size->dimensions.height,
vector<int32>(photo_size->progressive_sizes));
}
static vector<td_api::object_ptr<td_api::photoSize>> get_photo_sizes_object(FileManager *file_manager,
const vector<PhotoSize> &photo_sizes) {
auto sizes = transform(photo_sizes, [file_manager](const PhotoSize &photo_size) {
return get_photo_size_object(file_manager, &photo_size);
});
std::stable_sort(sizes.begin(), sizes.end(), [](const auto &lhs, const auto &rhs) {
if (lhs->photo_->expected_size_ != rhs->photo_->expected_size_) {
return lhs->photo_->expected_size_ < rhs->photo_->expected_size_;
}
return static_cast<uint32>(lhs->width_) * static_cast<uint32>(lhs->height_) <
static_cast<uint32>(rhs->width_) * static_cast<uint32>(rhs->height_);
});
td::remove_if(sizes, [](const auto &size) {
return !size->photo_->local_->can_be_downloaded_ && !size->photo_->local_->is_downloading_completed_;
});
return sizes;
}
bool operator==(const PhotoSize &lhs, const PhotoSize &rhs) {
return lhs.type == rhs.type && lhs.dimensions == rhs.dimensions && lhs.size == rhs.size &&
lhs.file_id == rhs.file_id && lhs.progressive_sizes == rhs.progressive_sizes;
}
bool operator!=(const PhotoSize &lhs, const PhotoSize &rhs) {
return !(lhs == rhs);
}
bool operator<(const PhotoSize &lhs, const PhotoSize &rhs) {
if (lhs.size != rhs.size) {
return lhs.size < rhs.size;
}
auto lhs_pixels = get_pixel_count(lhs.dimensions);
auto rhs_pixels = get_pixel_count(rhs.dimensions);
if (lhs_pixels != rhs_pixels) {
return lhs_pixels < rhs_pixels;
}
int32 lhs_type = lhs.type == 't' ? -1 : lhs.type;
int32 rhs_type = rhs.type == 't' ? -1 : rhs.type;
if (lhs_type != rhs_type) {
return lhs_type < rhs_type;
}
if (lhs.file_id != rhs.file_id) {
return lhs.file_id.get() < rhs.file_id.get();
}
return lhs.dimensions.width < rhs.dimensions.width;
}
StringBuilder &operator<<(StringBuilder &string_builder, const PhotoSize &photo_size) {
return string_builder << "{type = " << photo_size.type << ", dimensions = " << photo_size.dimensions
<< ", size = " << photo_size.size << ", file_id = " << photo_size.file_id
<< ", progressive_sizes = " << photo_size.progressive_sizes << "}";
}
static tl_object_ptr<td_api::animatedChatPhoto> get_animated_chat_photo_object(FileManager *file_manager,
const AnimationSize *animation_size) {
if (animation_size == nullptr || !animation_size->file_id.is_valid()) {
return nullptr;
}
return td_api::make_object<td_api::animatedChatPhoto>(animation_size->dimensions.width,
file_manager->get_file_object(animation_size->file_id),
animation_size->main_frame_timestamp);
}
bool operator==(const AnimationSize &lhs, const AnimationSize &rhs) {
return static_cast<const PhotoSize &>(lhs) == static_cast<const PhotoSize &>(rhs) &&
fabs(lhs.main_frame_timestamp - rhs.main_frame_timestamp) < 1e-3;
}
bool operator!=(const AnimationSize &lhs, const AnimationSize &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const AnimationSize &animation_size) {
return string_builder << static_cast<const PhotoSize &>(animation_size) << " from "
<< animation_size.main_frame_timestamp;
}
Photo get_encrypted_file_photo(FileManager *file_manager, tl_object_ptr<telegram_api::encryptedFile> &&file,
tl_object_ptr<secret_api::decryptedMessageMediaPhoto> &&photo,
DialogId owner_dialog_id) {
FileId file_id = file_manager->register_remote(
FullRemoteFileLocation(FileType::Encrypted, file->id_, file->access_hash_, DcId::create(file->dc_id_), string()),
FileLocationSource::FromServer, owner_dialog_id, photo->size_, 0,
PSTRING() << static_cast<uint64>(file->id_) << ".jpg");
file_manager->set_encryption_key(file_id, FileEncryptionKey{photo->key_.as_slice(), photo->iv_.as_slice()});
Photo res;
res.id = 0;
res.date = 0;
if (!photo->thumb_.empty()) {
res.photos.push_back(get_secret_thumbnail_photo_size(file_manager, std::move(photo->thumb_), owner_dialog_id,
photo->thumb_w_, photo->thumb_h_));
}
PhotoSize s;
s.type = 'i';
s.dimensions = get_dimensions(photo->w_, photo->h_, "get_encrypted_file_photo");
s.size = photo->size_;
s.file_id = file_id;
res.photos.push_back(s);
return res;
}
Photo get_photo(FileManager *file_manager, tl_object_ptr<telegram_api::Photo> &&photo, DialogId owner_dialog_id) {
if (photo == nullptr || photo->get_id() == telegram_api::photoEmpty::ID) {
return Photo();
}
CHECK(photo->get_id() == telegram_api::photo::ID);
return get_photo(file_manager, move_tl_object_as<telegram_api::photo>(photo), owner_dialog_id);
}
Photo get_photo(FileManager *file_manager, tl_object_ptr<telegram_api::photo> &&photo, DialogId owner_dialog_id) {
CHECK(photo != nullptr);
Photo res;
res.id = photo->id_;
res.date = photo->date_;
res.has_stickers = (photo->flags_ & telegram_api::photo::HAS_STICKERS_MASK) != 0;
if (res.is_empty()) {
LOG(ERROR) << "Receive photo with identifier " << res.id.get();
res.id = -3;
}
DcId dc_id = DcId::create(photo->dc_id_);
for (auto &size_ptr : photo->sizes_) {
auto photo_size = get_photo_size(file_manager, {FileType::Photo, 0}, photo->id_, photo->access_hash_,
photo->file_reference_.as_slice().str(), dc_id, owner_dialog_id,
std::move(size_ptr), PhotoFormat::Jpeg);
if (photo_size.get_offset() == 0) {
PhotoSize &size = photo_size.get<0>();
if (size.type == 0 || size.type == 't' || size.type == 'i' || size.type == 'u' || size.type == 'v') {
LOG(ERROR) << "Skip unallowed photo size " << size;
continue;
}
res.photos.push_back(std::move(size));
} else {
res.minithumbnail = std::move(photo_size.get<1>());
}
}
for (auto &size_ptr : photo->video_sizes_) {
auto animation =
get_animation_size(file_manager, {FileType::Photo, 0}, photo->id_, photo->access_hash_,
photo->file_reference_.as_slice().str(), dc_id, owner_dialog_id, std::move(size_ptr));
if (animation.type != 0 && animation.dimensions.width == animation.dimensions.height) {
res.animations.push_back(std::move(animation));
}
}
return res;
}
Photo get_web_document_photo(FileManager *file_manager, tl_object_ptr<telegram_api::WebDocument> web_document,
DialogId owner_dialog_id) {
PhotoSize s = get_web_document_photo_size(file_manager, FileType::Photo, owner_dialog_id, std::move(web_document));
Photo photo;
if (s.file_id.is_valid() && s.type != 'v' && s.type != 'g') {
photo.id = 0;
photo.photos.push_back(s);
}
return photo;
}
tl_object_ptr<td_api::photo> get_photo_object(FileManager *file_manager, const Photo &photo) {
if (photo.is_empty()) {
return nullptr;
}
return td_api::make_object<td_api::photo>(photo.has_stickers, get_minithumbnail_object(photo.minithumbnail),
get_photo_sizes_object(file_manager, photo.photos));
}
tl_object_ptr<td_api::chatPhoto> get_chat_photo_object(FileManager *file_manager, const Photo &photo) {
if (photo.is_empty()) {
return nullptr;
}
const AnimationSize *animation = photo.animations.empty() ? nullptr : &photo.animations.back();
return td_api::make_object<td_api::chatPhoto>(
photo.id.get(), photo.date, get_minithumbnail_object(photo.minithumbnail),
get_photo_sizes_object(file_manager, photo.photos), get_animated_chat_photo_object(file_manager, animation));
}
void photo_delete_thumbnail(Photo &photo) {
for (size_t i = 0; i < photo.photos.size(); i++) {
if (photo.photos[i].type == 't') {
photo.photos.erase(photo.photos.begin() + i);
return;
}
}
}
bool photo_has_input_media(FileManager *file_manager, const Photo &photo, bool is_secret, bool is_bot) {
if (photo.photos.empty() || photo.photos.back().type != 'i') {
LOG(ERROR) << "Wrong photo: " << photo;
return false;
}
auto file_id = photo.photos.back().file_id;
auto file_view = file_manager->get_file_view(file_id);
if (is_secret) {
if (!file_view.is_encrypted_secret() || !file_view.has_remote_location()) {
return false;
}
for (const auto &size : photo.photos) {
if (size.type == 't' && size.file_id.is_valid()) {
return false;
}
}
return true;
} else {
if (file_view.is_encrypted()) {
return false;
}
if (is_bot && file_view.has_remote_location()) {
return true;
}
return /* file_view.has_remote_location() || */ file_view.has_url();
}
}
tl_object_ptr<telegram_api::InputMedia> photo_get_input_media(FileManager *file_manager, const Photo &photo,
tl_object_ptr<telegram_api::InputFile> input_file,
int32 ttl) {
if (!photo.photos.empty()) {
auto file_id = photo.photos.back().file_id;
auto file_view = file_manager->get_file_view(file_id);
if (file_view.is_encrypted()) {
return nullptr;
}
if (file_view.has_remote_location() && !file_view.main_remote_location().is_web() && input_file == nullptr) {
int32 flags = 0;
if (ttl != 0) {
flags |= telegram_api::inputMediaPhoto::TTL_SECONDS_MASK;
}
return make_tl_object<telegram_api::inputMediaPhoto>(flags, file_view.main_remote_location().as_input_photo(),
ttl);
}
if (file_view.has_url()) {
int32 flags = 0;
if (ttl != 0) {
flags |= telegram_api::inputMediaPhotoExternal::TTL_SECONDS_MASK;
}
LOG(INFO) << "Create inputMediaPhotoExternal with a URL " << file_view.url() << " and TTL " << ttl;
return make_tl_object<telegram_api::inputMediaPhotoExternal>(flags, file_view.url(), ttl);
}
if (input_file == nullptr) {
CHECK(!file_view.has_remote_location());
}
}
if (input_file != nullptr) {
int32 flags = 0;
vector<tl_object_ptr<telegram_api::InputDocument>> added_stickers;
if (photo.has_stickers) {
flags |= telegram_api::inputMediaUploadedPhoto::STICKERS_MASK;
added_stickers = file_manager->get_input_documents(photo.sticker_file_ids);
}
if (ttl != 0) {
flags |= telegram_api::inputMediaUploadedPhoto::TTL_SECONDS_MASK;
}
return make_tl_object<telegram_api::inputMediaUploadedPhoto>(flags, std::move(input_file),
std::move(added_stickers), ttl);
}
return nullptr;
}
SecretInputMedia photo_get_secret_input_media(FileManager *file_manager, const Photo &photo,
tl_object_ptr<telegram_api::InputEncryptedFile> input_file,
const string &caption, BufferSlice thumbnail) {
FileId file_id;
int32 width = 0;
int32 height = 0;
FileId thumbnail_file_id;
int32 thumbnail_width = 0;
int32 thumbnail_height = 0;
for (const auto &size : photo.photos) {
if (size.type == 'i') {
file_id = size.file_id;
width = size.dimensions.width;
height = size.dimensions.height;
}
if (size.type == 't') {
thumbnail_file_id = size.file_id;
thumbnail_width = size.dimensions.width;
thumbnail_height = size.dimensions.height;
}
}
if (file_id.empty()) {
LOG(ERROR) << "NO SIZE";
return {};
}
auto file_view = file_manager->get_file_view(file_id);
auto &encryption_key = file_view.encryption_key();
if (!file_view.is_encrypted_secret() || encryption_key.empty()) {
return {};
}
if (file_view.has_remote_location()) {
LOG(INFO) << "Photo has remote location";
input_file = file_view.main_remote_location().as_input_encrypted_file();
}
if (input_file == nullptr) {
return {};
}
if (thumbnail_file_id.is_valid() && thumbnail.empty()) {
return {};
}
return SecretInputMedia{
std::move(input_file),
make_tl_object<secret_api::decryptedMessageMediaPhoto>(
std::move(thumbnail), thumbnail_width, thumbnail_height, width, height, narrow_cast<int32>(file_view.size()),
BufferSlice(encryption_key.key_slice()), BufferSlice(encryption_key.iv_slice()), caption)};
}
vector<FileId> photo_get_file_ids(const Photo &photo) {
auto result = transform(photo.photos, [](auto &size) { return size.file_id; });
if (!photo.animations.empty()) {
// photo file IDs must be first
append(result, transform(photo.animations, [](auto &size) { return size.file_id; }));
}
return result;
}
bool operator==(const Photo &lhs, const Photo &rhs) {
return lhs.id.get() == rhs.id.get() && lhs.photos == rhs.photos && lhs.animations == rhs.animations;
}
bool operator!=(const Photo &lhs, const Photo &rhs) {
return !(lhs == rhs);
}
StringBuilder &operator<<(StringBuilder &string_builder, const Photo &photo) {
string_builder << "[ID = " << photo.id.get() << ", photos = " << format::as_array(photo.photos);
if (!photo.animations.empty()) {
string_builder << ", animations = " << format::as_array(photo.animations);
}
return string_builder << ']';
}
static tl_object_ptr<telegram_api::fileLocationToBeDeprecated> copy_location(
const tl_object_ptr<telegram_api::fileLocationToBeDeprecated> &location) {
CHECK(location != nullptr);
return make_tl_object<telegram_api::fileLocationToBeDeprecated>(location->volume_id_, location->local_id_);
}
tl_object_ptr<telegram_api::userProfilePhoto> convert_photo_to_profile_photo(
const tl_object_ptr<telegram_api::photo> &photo) {
if (photo == nullptr) {
return nullptr;
}
tl_object_ptr<telegram_api::fileLocationToBeDeprecated> photo_small;
tl_object_ptr<telegram_api::fileLocationToBeDeprecated> photo_big;
for (auto &size_ptr : photo->sizes_) {
switch (size_ptr->get_id()) {
case telegram_api::photoSizeEmpty::ID:
break;
case telegram_api::photoSize::ID: {
auto size = static_cast<const telegram_api::photoSize *>(size_ptr.get());
if (size->type_ == "a") {
photo_small = copy_location(size->location_);
} else if (size->type_ == "c") {
photo_big = copy_location(size->location_);
}
break;
}
case telegram_api::photoCachedSize::ID: {
auto size = static_cast<const telegram_api::photoCachedSize *>(size_ptr.get());
if (size->type_ == "a") {
photo_small = copy_location(size->location_);
} else if (size->type_ == "c") {
photo_big = copy_location(size->location_);
}
break;
}
case telegram_api::photoStrippedSize::ID:
break;
case telegram_api::photoSizeProgressive::ID: {
auto size = static_cast<const telegram_api::photoSizeProgressive *>(size_ptr.get());
if (size->type_ == "a") {
photo_small = copy_location(size->location_);
} else if (size->type_ == "c") {
photo_big = copy_location(size->location_);
}
break;
}
default:
UNREACHABLE();
break;
}
}
if (photo_small == nullptr || photo_big == nullptr) {
return nullptr;
}
int32 flags = 0;
if (!photo->video_sizes_.empty()) {
flags |= telegram_api::userProfilePhoto::HAS_VIDEO_MASK;
}
return make_tl_object<telegram_api::userProfilePhoto>(flags, false /*ignored*/, photo->id_, std::move(photo_small),
std::move(photo_big), BufferSlice(), photo->dc_id_);
}
} // namespace td
| [
"rifaiirfan41@gmail.com"
] | rifaiirfan41@gmail.com |
3c8d34d64ac4f972b61232a6bc532b27acc60800 | 0ad356af02fb923747dc81036c9df4f7c9f6f2d5 | /e_encoder.cpp | 8a24edef14ce3ff22840aee3b9ebe3a08ac7c0b0 | [] | no_license | lvzhongze/steganography-1 | d9cff0d0194d5ac693d859d34c2e4647de108bc5 | 9c27761f5225dca61476f4e634623ec2f1eaefe2 | refs/heads/master | 2020-04-24T23:43:00.413691 | 2015-02-16T23:50:49 | 2015-02-16T23:50:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,458 | cpp | // General Information Hiding - encoder
// Usage: program_name carrier message encoded
// Description
// This program uses user password seeded random number generator to hide
// consequtive bits of user selected file within randomly chosen bytes of
// noised 3-channel carrier image.
// Author: Marcin Majkowski, m.p.majkowski@cranfield.ac.uk
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <memory>
#include <cv.h>
#include <highgui.h>
using namespace cv;
using namespace std;
unsigned long hash_djb2(const char* str);
template <typename T>
inline bool get_bit(T& var, unsigned n);
void add_gaussian_noise(Mat_<Vec3b>& src, Mat_<Vec3b>& dst, double sigma,
RNG& rng);
int main(int argc, char* argv[])
{
if (argc != 4) { // incorrect number of arguments
cout << "Usage: program_name carrier message encoded" << endl;
return -1;
}
// loading carrier image
cout << "Loading carrier image (" << argv[1] << ")... ";
auto carrier = Mat_<Vec3b>{};
if (!(carrier = imread(argv[1])).data) {
cout << "Could not open or find " << argv[1] << endl;
return -1;
}
cout << "done" << endl;
// loading message file to memory
cout << "Loading message file (" << argv[2] << ")... ";
auto file = ifstream(argv[2], ios::binary | ios::ate);
if (!file.is_open()) {
cout << "Could not open or find " << argv[2] << endl;
return -1;
}
auto file_size = int32_t(file.tellg());
auto memblock =
unique_ptr<char[]>(new char[file_size]); // thanks to this, allocated
// memory doesn't have to be
// deleted explicitly
file.seekg(0, ios::beg);
file.read(memblock.get(), file_size);
cout << "done (" << file_size * 8 << " bits)" << endl;
// prompting user for a character string password
cout << "Input password: ";
string password;
getline(cin, password);
// transforming password string to a 64-bit integer seed (with hash
// function)
auto seed = hash_djb2(password.c_str());
RNG rng(seed);
// adding Gaussian noise to the carrier image
cout << "Adding Gaussian noise to the carrier image... ";
double sigma = 5;
Mat_<Vec3b> noised;
add_gaussian_noise(carrier, noised, sigma, rng);
// noised = carrier.clone();
cout << "done" << endl;
// counting number of slots in noised carrier image
cout << "Counting number of free slots in noised carrier image... ";
auto slots =
vector<Vec3i>(noised.cols * noised.rows * 3); // all carrier image free
// slots indexes will be
// stored in this vector
auto slots_it = slots.begin();
for (int i = 0; i < noised.rows; ++i)
for (int j = 0; j < noised.cols; ++j)
for (int b = 0; b < 3; ++b)
if (noised.at<Vec3b>(i, j)[b] < 255)
*(slots_it++) = Vec3i({i, j, b});
slots.erase(slots_it,
slots.end()); // now slots.size() is a number of free slots
cout << "done (" << slots.size() << " slots)" << endl;
// determining if message, its size information and seed (for password
// checking) will fit in the carrier image
if ((file_size + 4 + sizeof(seed)) * 8 > slots.size()) {
cout << "Message file (" << argv[2] << ") is too big" << endl;
return -1;
}
// random shuffling vector of slots in carrier image
cout << "Shuffling a vector of free slots... ";
random_shuffle(slots.begin(), slots.end(), rng);
cout << "done" << endl;
// hiding seed variable (for password checking)
cout << "Hiding generated seed (for password cheking)... ";
Mat encoded = noised.clone();
int slot_index = 0;
for (int i = 0; i < sizeof(seed) * 8; ++i) {
Vec3i slot = slots[slot_index++];
int row = slot[0];
int col = slot[1];
int channel = slot[2];
encoded.at<Vec3b>(row, col)[channel] += get_bit(seed, i);
}
cout << "done" << endl;
// hiding message file size
cout << "Hiding message file size... ";
for (int i = 0; i < 32; ++i) {
Vec3i slot = slots[slot_index++];
int row = slot[0];
int col = slot[1];
int channel = slot[2];
encoded.at<Vec3b>(row, col)[channel] += get_bit(file_size, i);
}
cout << "done" << endl;
// distributing message bits over carrier image bytes
cout << "Distributing message bits over carrier image bytes... ";
for (int i = 0; i < file_size; ++i) {
for (int j = 0; j < 8; ++j) {
Vec3i slot = slots[slot_index++];
int row = slot[0];
int col = slot[1];
int channel = slot[2];
encoded.at<Vec3b>(row, col)[channel] +=
get_bit(char(memblock[i]), j);
}
}
cout << "done" << endl;
// saving generated image
cout << "Saving generated image (" << argv[3] << ")... ";
vector<int> compression_params = {CV_IMWRITE_PNG_COMPRESSION, 9};
imwrite(argv[3], encoded, compression_params);
cout << "done" << endl;
// success
return 0;
}
// from http://www.cse.yorku.ca/~oz/hash.html
unsigned long hash_djb2(const char* str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
template <typename T>
inline bool get_bit(T& var, unsigned n)
{
/*
unsigned which_byte = sizeof(T) - n / 8 - 1; // counting from right
char byte = ((char*)&var)[which_byte];
unsigned which_bit_in_byte = n % 8; // counting from right
return 1 & (byte >> (which_bit_in_byte));
*/
return 1 & (((char*)&var)[sizeof(T) - n / 8 - 1] >> (n % 8));
}
void add_gaussian_noise(Mat_<Vec3b>& src, Mat_<Vec3b>& dst, double sigma,
RNG& rng)
{
dst = src.clone();
int noised_value;
for (auto& pixel : dst)
for (auto i : {0, 1, 2}) {
noised_value = rng.gaussian(sigma) + pixel[i];
if (noised_value > 255) // preventing overflow
pixel[i] = 255;
else if (noised_value < 0)
pixel[i] = 0;
else
pixel[i] = noised_value;
}
}
| [
"pl.marcin.m@gmail.com"
] | pl.marcin.m@gmail.com |
86eb0ae9ec5d6c31c6de7b038401cbcb0c4b91f9 | 4985aad8ecfceca8027709cf488bc2c601443385 | /build/Android/Debug/app/src/main/include/Fuse.Elements.Element.h | 050e380e4f65c54c745f7f274b579ec80a17474e | [] | no_license | pacol85/Test1 | a9fd874711af67cb6b9559d9a4a0e10037944d89 | c7bb59a1b961bfb40fe320ee44ca67e068f0a827 | refs/heads/master | 2021-01-25T11:39:32.441939 | 2017-06-12T21:48:37 | 2017-06-12T21:48:37 | 93,937,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,377 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Elements/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Elements.Element-e8906a44.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.Actions-ea70af1f.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.Float2.h>
#include <Uno.UX.IPropertyListener.h>
#include <Uno.UX.Size.h>
namespace g{namespace Fuse{namespace Effects{struct Effect;}}}
namespace g{namespace Fuse{namespace Elements{struct BoxSizing;}}}
namespace g{namespace Fuse{namespace Elements{struct Cache;}}}
namespace g{namespace Fuse{namespace Elements{struct Element;}}}
namespace g{namespace Fuse{namespace Elements{struct ElementBatchEntry;}}}
namespace g{namespace Fuse{namespace Elements{struct ElementBatcher;}}}
namespace g{namespace Fuse{struct DrawContext;}}
namespace g{namespace Fuse{struct FastMatrix;}}
namespace g{namespace Fuse{struct HitTestContext;}}
namespace g{namespace Fuse{struct LayoutParams;}}
namespace g{namespace Fuse{struct VisualBounds;}}
namespace g{namespace Uno{namespace Collections{struct List;}}}
namespace g{namespace Uno{namespace Graphics{struct Framebuffer;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{namespace Uno{namespace UX{struct Size2;}}}
namespace g{namespace Uno{struct Float3;}}
namespace g{namespace Uno{struct Float4;}}
namespace g{namespace Uno{struct Rect;}}
namespace g{namespace Uno{struct Recti;}}
namespace g{
namespace Fuse{
namespace Elements{
// public interfacemodifiers class Element :104
// {
struct Element_type : ::g::Fuse::Visual_type
{
::g::Fuse::Triggers::Actions::IShow interface10;
::g::Fuse::Triggers::Actions::IHide interface11;
::g::Fuse::Triggers::Actions::ICollapse interface12;
::g::Fuse::IActualPlacement interface13;
::g::Fuse::Animations::IResize interface14;
void(*fp_ArrangePaddingBox)(::g::Fuse::Elements::Element*, ::g::Fuse::LayoutParams*);
void(*fp_CalcRenderBounds)(::g::Fuse::Elements::Element*, ::g::Fuse::VisualBounds**);
void(*fp_DrawWithChildren)(::g::Fuse::Elements::Element*, ::g::Fuse::DrawContext*);
void(*fp_FastTrackDrawWithOpacity)(::g::Fuse::Elements::Element*, ::g::Fuse::DrawContext*, bool*);
void(*fp_GetContentSize)(::g::Fuse::Elements::Element*, ::g::Fuse::LayoutParams*, ::g::Uno::Float2*);
void(*fp_get_HitTestLocalVisualBounds)(::g::Fuse::Elements::Element*, ::g::Fuse::VisualBounds**);
void(*fp_OnDraw)(::g::Fuse::Elements::Element*, ::g::Fuse::DrawContext*);
void(*fp_OnHitTestLocalVisual)(::g::Fuse::Elements::Element*, ::g::Fuse::HitTestContext*);
void(*fp_get_TreeRenderer)(::g::Fuse::Elements::Element*, uObject**);
};
Element_type* Element_typeof();
void Element__ctor_3_fn(Element* __this);
void Element__get_AbsoluteViewportOrigin_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__get_ActualAnchor_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__set_ActualAnchor_fn(Element* __this, ::g::Uno::Float2* value);
void Element__get_ActualPosition_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__get_ActualSize_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__get_Alignment_fn(Element* __this, int* __retval);
void Element__set_Alignment_fn(Element* __this, int* value);
void Element__get_AncestorElement_fn(Element* __this, Element** __retval);
void Element__get_Anchor_fn(Element* __this, ::g::Uno::UX::Size2* __retval);
void Element__set_Anchor_fn(Element* __this, ::g::Uno::UX::Size2* value);
void Element__ArrangePaddingBox_fn(Element* __this, ::g::Fuse::LayoutParams* lp);
void Element__get_Aspect_fn(Element* __this, float* __retval);
void Element__set_Aspect_fn(Element* __this, float* value);
void Element__get_AspectConstraint_fn(Element* __this, int* __retval);
void Element__set_AspectConstraint_fn(Element* __this, int* value);
void Element__get_BoxSizingObject_fn(Element* __this, ::g::Fuse::Elements::BoxSizing** __retval);
void Element__get_Cache_fn(Element* __this, ::g::Fuse::Elements::Cache** __retval);
void Element__get_CachingMode_fn(Element* __this, int* __retval);
void Element__set_CachingMode_fn(Element* __this, int* value);
void Element__CalcRenderBounds_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__CalcRenderBoundsWithEffects_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_CanAdjustMarginBox_fn(Element* __this, bool* __retval);
void Element__CaptureRegion_fn(Element* __this, ::g::Fuse::DrawContext* dc, ::g::Uno::Rect* region, ::g::Uno::Float2* padding, ::g::Uno::Graphics::Framebuffer** __retval);
void Element__CleanupBatching_fn(Element* __this);
void Element__get_ClipToBounds_fn(Element* __this, bool* __retval);
void Element__set_ClipToBounds_fn(Element* __this, bool* value);
void Element__Composit_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__CompositEffects_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__DispatchPlacement_fn(Element* __this);
void Element__Draw_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__DrawNonUnderlayChildren_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__DrawSelection_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__DrawUnderlayChildren_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__DrawWithChildren_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__get_Effects_fn(Element* __this, uObject** __retval);
void Element__get_ElementBatchEntry_fn(Element* __this, ::g::Fuse::Elements::ElementBatchEntry** __retval);
void Element__set_ElementBatchEntry_fn(Element* __this, ::g::Fuse::Elements::ElementBatchEntry* value);
void Element__FastTrackDrawWithOpacity_fn(Element* __this, ::g::Fuse::DrawContext* dc, bool* __retval);
void Element__FuseAnimationsIResizeSetSize_fn(Element* __this, ::g::Uno::Float2* size);
void Element__FuseIActualPlacementget_ActualSize_fn(Element* __this, ::g::Uno::Float3* __retval);
void Element__FuseTriggersActionsICollapseCollapse_fn(Element* __this);
void Element__FuseTriggersActionsIHideHide_fn(Element* __this);
void Element__FuseTriggersActionsIShowShow_fn(Element* __this);
void Element__GetArrangePaddingSize_fn(Element* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Element__GetContentSize_fn(Element* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Element__GetMarginSize_fn(Element* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Element__GetViewportInvertPixelRect_fn(Element* __this, ::g::Fuse::DrawContext* dc, ::g::Uno::Rect* localRegion, ::g::Uno::Recti* __retval);
void Element__GetVisibleViewportInvertPixelRect_fn(Element* __this, ::g::Fuse::DrawContext* dc, ::g::Fuse::VisualBounds* localRegion, ::g::Uno::Recti* __retval);
void Element__GMSReset_fn(Element* __this);
void Element__get_HasActiveEffects_fn(Element* __this, bool* __retval);
void Element__get_HasCompositionEffect_fn(Element* __this, bool* __retval);
void Element__get_HasEffects_fn(Element* __this, bool* __retval);
void Element__get_Height_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_Height_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_HitTestChildrenBounds_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_HitTestLocalBounds_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_HitTestLocalVisualBounds_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_HitTestMode_fn(Element* __this, int* __retval);
void Element__set_HitTestMode_fn(Element* __this, int* value);
void Element__get_IntendedPosition_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__get_IntendedSize_fn(Element* __this, ::g::Uno::Float2* __retval);
void Element__InternArrangePaddingBox_fn(Element* __this, ::g::Fuse::LayoutParams* lp);
void Element__InternGetContentSize_fn(Element* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Element__InvalidateLocalTransform_fn(Element* __this);
void Element__InvalidateRenderBoundsWithEffects_fn(Element* __this);
void Element__get_IsLocalVisible_fn(Element* __this, bool* __retval);
void Element__IsMarginBoxDependent_fn(Element* __this, ::g::Fuse::Visual* child, int* __retval);
void Element__IsPointInside_fn(Element* __this, ::g::Uno::Float2* localPoint, bool* __retval);
void Element__get_LimitHeight_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_LimitHeight_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_LimitWidth_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_LimitWidth_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_LocalRenderBounds_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_Margin_fn(Element* __this, ::g::Uno::Float4* __retval);
void Element__set_Margin_fn(Element* __this, ::g::Uno::Float4* value);
void Element__get_MaxHeight_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_MaxHeight_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_MaxWidth_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_MaxWidth_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_MinHeight_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_MinHeight_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_MinWidth_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_MinWidth_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_NeedsClipping_fn(Element* __this, bool* __retval);
void Element__NotifyTreeRedererOpacityChanged_fn(Element* __this);
void Element__NotifyTreeRendererHitTestModeChanged_fn(Element* __this);
void Element__NotifyTreeRendererPlaced_fn(Element* __this);
void Element__NotifyTreeRendererRooted_fn(Element* __this);
void Element__NotifyTreeRendererRootingStarted_fn(Element* __this);
void Element__NotifyTreeRendererTransformChanged_fn(Element* __this);
void Element__NotifyTreeRendererUnrooted_fn(Element* __this);
void Element__NotifyTreeRendererZOrderChanged_fn(Element* __this);
void Element__get_Offset_fn(Element* __this, ::g::Uno::UX::Size2* __retval);
void Element__set_Offset_fn(Element* __this, ::g::Uno::UX::Size2* value);
void Element__OnAdjustMarginBoxPosition_fn(Element* __this, ::g::Uno::Float2* position);
void Element__OnArrangeMarginBox_fn(Element* __this, ::g::Uno::Float2* position, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Element__OnChildAdded_fn(Element* __this, ::g::Fuse::Node* node);
void Element__OnChildRemoved_fn(Element* __this, ::g::Fuse::Node* node);
void Element__OnDraw_fn(Element* __this, ::g::Fuse::DrawContext* dc);
void Element__OnEffectAdded_fn(Element* __this, ::g::Fuse::Effects::Effect* e);
void Element__OnEffectRemoved_fn(Element* __this, ::g::Fuse::Effects::Effect* e);
void Element__OnEffectRenderBoundsChanged_fn(Element* __this, ::g::Fuse::Effects::Effect* e);
void Element__OnEffectRenderingChanged_fn(Element* __this, ::g::Fuse::Effects::Effect* e);
void Element__OnHitTest_fn(Element* __this, ::g::Fuse::HitTestContext* htc);
void Element__OnHitTestChildren_fn(Element* __this, ::g::Fuse::HitTestContext* htc);
void Element__OnHitTestLocalVisual_fn(Element* __this, ::g::Fuse::HitTestContext* htc);
void Element__OnInvalidateLayout_fn(Element* __this);
void Element__OnInvalidateRenderBounds_fn(Element* __this, bool* __retval);
void Element__OnInvalidateRenderBoundsWithEffects_fn(Element* __this);
void Element__OnInvalidateVisual_fn(Element* __this);
void Element__OnInvalidateVisualComposition_fn(Element* __this);
void Element__OnIsContextEnabledChanged_fn(Element* __this);
void Element__OnIsVisibleChanged_fn(Element* __this);
void Element__OnOpacityChanged_fn(Element* __this, uObject* origin);
void Element__OnPreplacement_fn(Element* __this);
void Element__OnRooted_fn(Element* __this);
void Element__OnRootedPreChildren_fn(Element* __this);
void Element__OnUnrooted_fn(Element* __this);
void Element__OnVisibilityChanged_fn(Element* __this, int* oldVisibility, uObject* origin);
void Element__OnZOrderChanged_fn(Element* __this);
void Element__OnZOrderInvalidated_fn(Element* __this);
void Element__get_Opacity_fn(Element* __this, float* __retval);
void Element__set_Opacity_fn(Element* __this, float* value);
void Element__get_Padding_fn(Element* __this, ::g::Uno::Float4* __retval);
void Element__set_Padding_fn(Element* __this, ::g::Uno::Float4* value);
void Element__PerformPlacement_fn(Element* __this, ::g::Uno::Float2* position, ::g::Uno::Float2* size, bool* temp);
void Element__add_Placed_fn(Element* __this, uDelegate* value);
void Element__remove_Placed_fn(Element* __this, uDelegate* value);
void Element__PrependImplicitTransform_fn(Element* __this, ::g::Fuse::FastMatrix* m);
void Element__PrependInverseTransformOrigin_fn(Element* __this, ::g::Fuse::FastMatrix* m);
void Element__PrependTransformOrigin_fn(Element* __this, ::g::Fuse::FastMatrix* m);
void Element__add_Preplacement_fn(Element* __this, uDelegate* value);
void Element__remove_Preplacement_fn(Element* __this, uDelegate* value);
void Element__RemoveChildElementFromBatching_fn(Element* __this, Element* elm);
void Element__get_RenderBoundsWithEffects_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__get_RenderBoundsWithoutEffects_fn(Element* __this, ::g::Fuse::VisualBounds** __retval);
void Element__RequestLayout_fn(Element* __this);
void Element__SetHitTestMode_fn(Element* __this, int* value, uObject* origin);
void Element__SetNewTransform_fn(Element* __this);
void Element__SetOpacity_fn(Element* __this, float* value, uObject* origin);
void Element__SetVisibility_fn(Element* __this, int* value, uObject* origin);
void Element__ShouldBatch_fn(Element* __this, bool* __retval);
void Element__get_TransformOrigin_fn(Element* __this, uObject** __retval);
void Element__set_TransformOrigin_fn(Element* __this, uObject* value);
void Element__get_TreeRenderer_fn(Element* __this, uObject** __retval);
void Element__get_Visibility_fn(Element* __this, int* __retval);
void Element__set_Visibility_fn(Element* __this, int* value);
void Element__get_Width_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_Width_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_X_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_X_fn(Element* __this, ::g::Uno::UX::Size* value);
void Element__get_Y_fn(Element* __this, ::g::Uno::UX::Size* __retval);
void Element__set_Y_fn(Element* __this, ::g::Uno::UX::Size* value);
struct Element : ::g::Fuse::Visual
{
::g::Uno::Float2 _actualAnchor;
::g::Uno::Float2 _actualPosition;
::g::Uno::Float2 _actualPositionCache;
::g::Uno::Float2 _actualSize;
int _alignment;
uStrong< ::g::Fuse::Elements::BoxSizing*> _boxSizing;
uStrong< ::g::Fuse::Elements::Cache*> _cache;
static ::g::Uno::UX::Selector _clipToBoundsName_;
static ::g::Uno::UX::Selector& _clipToBoundsName() { return Element_typeof()->Init(), _clipToBoundsName_; }
int _compositionEffects;
uStrong< ::g::Uno::Collections::List*> _effects;
uStrong< ::g::Fuse::Elements::ElementBatcher*> _elementBatcher;
bool _elementBatchValid;
int _gmsAt;
uStrong<uArray*> _gmsCache;
int _gmsCount;
bool _haveActualPositionCache;
::g::Uno::UX::Size _height;
static ::g::Uno::UX::Selector _hitTestModeName_;
static ::g::Uno::UX::Selector& _hitTestModeName() { return Element_typeof()->Init(), _hitTestModeName_; }
::g::Uno::Float2 _intendedSize;
static ::g::Uno::UX::Selector _opacityName_;
static ::g::Uno::UX::Selector& _opacityName() { return Element_typeof()->Init(), _opacityName_; }
bool _pendingDispatchPlacement;
uWeak< ::g::Fuse::Node*> _placedBefore;
::g::Uno::Float2 _ppPrevPosition;
::g::Uno::Float2 _ppPrevSize;
uStrong< ::g::Fuse::VisualBounds*> _renderBoundsWithEffects;
uStrong< ::g::Fuse::VisualBounds*> _renderBoundsWithoutEffects;
bool _transformChanged;
int _visibility;
static ::g::Uno::UX::Selector _visibilityName_;
static ::g::Uno::UX::Selector& _visibilityName() { return Element_typeof()->Init(), _visibilityName_; }
bool _warnNoCacheDraw;
bool _warnOpacityFlat;
::g::Uno::UX::Size _width;
static uSStrong<uObject*> DefaultTransformOrigin_;
static uSStrong<uObject*>& DefaultTransformOrigin() { return Element_typeof()->Init(), DefaultTransformOrigin_; }
static ::g::Uno::UX::Selector ExplicitTransformOriginName_;
static ::g::Uno::UX::Selector& ExplicitTransformOriginName() { return Element_typeof()->Init(), ExplicitTransformOriginName_; }
bool ignoreTempArrange;
uStrong< ::g::Fuse::Elements::ElementBatchEntry*> _ElementBatchEntry;
uStrong<uDelegate*> Placed1;
uStrong<uDelegate*> Preplacement1;
void ctor_3();
::g::Uno::Float2 ActualAnchor();
void ActualAnchor(::g::Uno::Float2 value);
::g::Uno::Float2 ActualPosition();
::g::Uno::Float2 ActualSize();
int Alignment();
void Alignment(int value);
Element* AncestorElement();
::g::Uno::UX::Size2 Anchor();
void Anchor(::g::Uno::UX::Size2 value);
void ArrangePaddingBox(::g::Fuse::LayoutParams lp);
float Aspect();
void Aspect(float value);
int AspectConstraint();
void AspectConstraint(int value);
::g::Fuse::Elements::BoxSizing* BoxSizingObject();
::g::Fuse::Elements::Cache* Cache();
int CachingMode();
void CachingMode(int value);
::g::Fuse::VisualBounds* CalcRenderBounds() { ::g::Fuse::VisualBounds* __retval; return (((Element_type*)__type)->fp_CalcRenderBounds)(this, &__retval), __retval; }
::g::Fuse::VisualBounds* CalcRenderBoundsWithEffects();
::g::Uno::Graphics::Framebuffer* CaptureRegion(::g::Fuse::DrawContext* dc, ::g::Uno::Rect region, ::g::Uno::Float2 padding);
void CleanupBatching();
bool ClipToBounds();
void ClipToBounds(bool value);
void Composit(::g::Fuse::DrawContext* dc);
void CompositEffects(::g::Fuse::DrawContext* dc);
void DispatchPlacement();
void DrawNonUnderlayChildren(::g::Fuse::DrawContext* dc);
void DrawUnderlayChildren(::g::Fuse::DrawContext* dc);
void DrawWithChildren(::g::Fuse::DrawContext* dc) { (((Element_type*)__type)->fp_DrawWithChildren)(this, dc); }
uObject* Effects();
::g::Fuse::Elements::ElementBatchEntry* ElementBatchEntry();
void ElementBatchEntry(::g::Fuse::Elements::ElementBatchEntry* value);
bool FastTrackDrawWithOpacity(::g::Fuse::DrawContext* dc) { bool __retval; return (((Element_type*)__type)->fp_FastTrackDrawWithOpacity)(this, dc, &__retval), __retval; }
::g::Uno::Float2 GetArrangePaddingSize(::g::Fuse::LayoutParams lp);
::g::Uno::Float2 GetContentSize(::g::Fuse::LayoutParams lp);
::g::Uno::Recti GetViewportInvertPixelRect(::g::Fuse::DrawContext* dc, ::g::Uno::Rect localRegion);
::g::Uno::Recti GetVisibleViewportInvertPixelRect(::g::Fuse::DrawContext* dc, ::g::Fuse::VisualBounds* localRegion);
void GMSReset();
bool HasActiveEffects();
bool HasCompositionEffect();
bool HasEffects();
::g::Uno::UX::Size Height();
void Height(::g::Uno::UX::Size value);
::g::Fuse::VisualBounds* HitTestLocalVisualBounds() { ::g::Fuse::VisualBounds* __retval; return (((Element_type*)__type)->fp_get_HitTestLocalVisualBounds)(this, &__retval), __retval; }
int HitTestMode();
void HitTestMode(int value);
::g::Uno::Float2 IntendedPosition();
::g::Uno::Float2 IntendedSize();
void InternArrangePaddingBox(::g::Fuse::LayoutParams lp);
::g::Uno::Float2 InternGetContentSize(::g::Fuse::LayoutParams lp);
void InvalidateRenderBoundsWithEffects();
bool IsPointInside(::g::Uno::Float2 localPoint);
::g::Uno::UX::Size LimitHeight();
void LimitHeight(::g::Uno::UX::Size value);
::g::Uno::UX::Size LimitWidth();
void LimitWidth(::g::Uno::UX::Size value);
::g::Uno::Float4 Margin();
void Margin(::g::Uno::Float4 value);
::g::Uno::UX::Size MaxHeight();
void MaxHeight(::g::Uno::UX::Size value);
::g::Uno::UX::Size MaxWidth();
void MaxWidth(::g::Uno::UX::Size value);
::g::Uno::UX::Size MinHeight();
void MinHeight(::g::Uno::UX::Size value);
::g::Uno::UX::Size MinWidth();
void MinWidth(::g::Uno::UX::Size value);
bool NeedsClipping();
void NotifyTreeRedererOpacityChanged();
void NotifyTreeRendererHitTestModeChanged();
void NotifyTreeRendererPlaced();
void NotifyTreeRendererRooted();
void NotifyTreeRendererRootingStarted();
void NotifyTreeRendererTransformChanged();
void NotifyTreeRendererUnrooted();
void NotifyTreeRendererZOrderChanged();
::g::Uno::UX::Size2 Offset();
void Offset(::g::Uno::UX::Size2 value);
void OnDraw(::g::Fuse::DrawContext* dc) { (((Element_type*)__type)->fp_OnDraw)(this, dc); }
void OnEffectAdded(::g::Fuse::Effects::Effect* e);
void OnEffectRemoved(::g::Fuse::Effects::Effect* e);
void OnEffectRenderBoundsChanged(::g::Fuse::Effects::Effect* e);
void OnEffectRenderingChanged(::g::Fuse::Effects::Effect* e);
void OnHitTestChildren(::g::Fuse::HitTestContext* htc);
void OnHitTestLocalVisual(::g::Fuse::HitTestContext* htc) { (((Element_type*)__type)->fp_OnHitTestLocalVisual)(this, htc); }
void OnInvalidateRenderBoundsWithEffects();
void OnOpacityChanged(uObject* origin);
void OnPreplacement();
void OnVisibilityChanged(int oldVisibility, uObject* origin);
void OnZOrderChanged();
float Opacity();
void Opacity(float value);
::g::Uno::Float4 Padding();
void Padding(::g::Uno::Float4 value);
void PerformPlacement(::g::Uno::Float2 position, ::g::Uno::Float2 size, bool temp);
void add_Placed(uDelegate* value);
void remove_Placed(uDelegate* value);
void add_Preplacement(uDelegate* value);
void remove_Preplacement(uDelegate* value);
void RemoveChildElementFromBatching(Element* elm);
::g::Fuse::VisualBounds* RenderBoundsWithEffects();
::g::Fuse::VisualBounds* RenderBoundsWithoutEffects();
void RequestLayout();
void SetHitTestMode(int value, uObject* origin);
void SetNewTransform();
void SetOpacity(float value, uObject* origin);
void SetVisibility(int value, uObject* origin);
bool ShouldBatch();
uObject* TransformOrigin();
void TransformOrigin(uObject* value);
uObject* TreeRenderer() { uObject* __retval; return (((Element_type*)__type)->fp_get_TreeRenderer)(this, &__retval), __retval; }
int Visibility();
void Visibility(int value);
::g::Uno::UX::Size Width();
void Width(::g::Uno::UX::Size value);
::g::Uno::UX::Size X();
void X(::g::Uno::UX::Size value);
::g::Uno::UX::Size Y();
void Y(::g::Uno::UX::Size value);
static void ArrangePaddingBox(Element* __this, ::g::Fuse::LayoutParams lp);
static ::g::Fuse::VisualBounds* CalcRenderBounds(Element* __this) { ::g::Fuse::VisualBounds* __retval; return Element__CalcRenderBounds_fn(__this, &__retval), __retval; }
static void DrawWithChildren(Element* __this, ::g::Fuse::DrawContext* dc) { Element__DrawWithChildren_fn(__this, dc); }
static bool FastTrackDrawWithOpacity(Element* __this, ::g::Fuse::DrawContext* dc) { bool __retval; return Element__FastTrackDrawWithOpacity_fn(__this, dc, &__retval), __retval; }
static ::g::Uno::Float2 GetContentSize(Element* __this, ::g::Fuse::LayoutParams lp);
static void OnDraw(Element* __this, ::g::Fuse::DrawContext* dc) { Element__OnDraw_fn(__this, dc); }
static void OnHitTestLocalVisual(Element* __this, ::g::Fuse::HitTestContext* htc) { Element__OnHitTestLocalVisual_fn(__this, htc); }
static ::g::Fuse::VisualBounds* HitTestLocalVisualBounds(Element* __this) { ::g::Fuse::VisualBounds* __retval; return Element__get_HitTestLocalVisualBounds_fn(__this, &__retval), __retval; }
static uObject* TreeRenderer(Element* __this) { uObject* __retval; return Element__get_TreeRenderer_fn(__this, &__retval), __retval; }
};
}}} // ::g::Fuse::Elements
#include <Fuse.LayoutParams.h>
#include <Uno.Float3.h>
#include <Uno.Float4.h>
#include <Uno.Rect.h>
#include <Uno.Recti.h>
#include <Uno.UX.Size2.h>
namespace g{
namespace Fuse{
namespace Elements{
inline void Element::ArrangePaddingBox(::g::Fuse::LayoutParams lp) { (((Element_type*)__type)->fp_ArrangePaddingBox)(this, &lp); }
inline ::g::Uno::Float2 Element::GetContentSize(::g::Fuse::LayoutParams lp) { ::g::Uno::Float2 __retval; return (((Element_type*)__type)->fp_GetContentSize)(this, &lp, &__retval), __retval; }
inline void Element::ArrangePaddingBox(Element* __this, ::g::Fuse::LayoutParams lp) { Element__ArrangePaddingBox_fn(__this, &lp); }
inline ::g::Uno::Float2 Element::GetContentSize(Element* __this, ::g::Fuse::LayoutParams lp) { ::g::Uno::Float2 __retval; return Element__GetContentSize_fn(__this, &lp, &__retval), __retval; }
// }
}}} // ::g::Fuse::Elements
| [
"newreality64@gmail.com"
] | newreality64@gmail.com |
9e161693ab97bf2b103d8142296ddfa14776f753 | 1809b5bda803fbbf51dcbc4e2d464c762f3563c1 | /sphere_grid/sphere_grid_prb.cpp | 602071f331f0d525880072e2456bd1026a83d607 | [] | no_license | tnakaicode/jburkardt | 42c5ef74ab88d17afbd188e4ff2b4ecb8a30bb25 | 74eebcbda61423178b96cfdec5d8bb30d6494a33 | refs/heads/master | 2020-12-24T02:23:01.855912 | 2020-02-05T02:10:32 | 2020-02-05T02:10:32 | 237,349,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,754 | cpp | # include <cstdlib>
# include <iostream>
# include <fstream>
# include <iomanip>
# include <cmath>
using namespace std;
# include "sphere_grid.hpp"
int main ( );
void test01 ( );
void test02 ( );
void test03 ( );
void test04 ( );
void test05 ( );
void test06 ( );
void test07 ( );
void test08 ( );
void test09 ( );
void test10 ( );
void test11 ( );
void test12 ( );
void test13 ( );
//****************************************************************************80
int main ( )
//****************************************************************************80
//
// Purpose:
//
// MAIN is the main program for SPHERE_GRID_PRB.
//
// Discussion:
//
// SPHERE_GRID_PRB tests the SPHERE_GRID library.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 October 2012
//
// Author:
//
// John Burkardt
//
{
timestamp ( );
cout << "\n";
cout << "SPHERE_GRID_PRB\n";
cout << " C++ version\n";
cout << " Test the SPHERE_GRID library.\n";
test01 ( );
test02 ( );
test03 ( );
test04 ( );
test05 ( );
test06 ( );
test07 ( );
test08 ( );
test09 ( );
test10 ( );
test11 ( );
test12 ( );
test13 ( );
//
// Terminate.
//
cout << "\n";
cout << "SPHERE_GRID_PRB\n";
cout << " Normal end of execution.\n";
cout << "\n";
timestamp ( );
return 0;
}
//****************************************************************************80
void test01 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST01 tests SPHERE_ICOS_POINT_NUM.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2010
//
// Author:
//
// John Burkardt
//
{
int edge_num;
int factor;
int factor_log;
int node_num;
int triangle_num;
cout << "\n";
cout << "TEST01\n";
cout << " SPHERE_ICOS_POINT_NUM determines the size\n";
cout << " (number of vertices, edges and faces) in a grid\n";
cout << " on a sphere, made by subdividing an initial\n";
cout << " projected icosahedron.\n";
cout << "\n";
cout << " N determines the number of subdivisions of each\n";
cout << " edge of the icosahedral faces.\n";
cout << "\n";
cout << " N V E F\n";
cout << " -------- -------- -------- --------\n";
cout << "\n";
for ( factor = 1; factor <= 20; factor++ )
{
node_num = sphere_icos_point_num ( factor );
edge_num = sphere_icos_edge_num ( factor );
triangle_num = sphere_icos_face_num ( factor );
cout << " " << setw(8) << factor
<< " " << setw(8) << node_num
<< " " << setw(8) << edge_num
<< " " << setw(8) << triangle_num << "\n";
}
cout << "\n";
cout << " Repeat, but using N constrained by doubling:\n";
cout << "\n";
cout << " N V E F\n";
cout << " -------- -------- -------- --------\n";
cout << "\n";
factor = 1;
for ( factor_log = 0; factor_log <= 10; factor_log++ )
{
node_num = sphere_icos_point_num ( factor );
edge_num = sphere_icos_edge_num ( factor );
triangle_num = sphere_icos_face_num ( factor );
cout << " " << setw(8) << factor
<< " " << setw(8) << node_num
<< " " << setw(8) << edge_num
<< " " << setw(8) << triangle_num << "\n";
factor = factor * 2;
}
return;
}
//****************************************************************************80
void test02 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST02 tests SPHERE_ICOS1_POINTS.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 August 2010
//
// Author:
//
// John Burkardt
//
{
int factor;
string filename;
int node;
int node_num;
double *node_xyz;
ofstream output;
cout << "\n";
cout << "TEST02\n";
cout << " SPHERE_ICOS_POINT_NUM \"sizes\" a grid generated\n";
cout << " on an icosahedron and projected to a sphere.\n";
cout << " SPHERE_ICOS1_POINTS creates the grid points.\n";
factor = 3;
cout << "\n";
cout << " Sizing factor = " << factor << "\n";
node_num = sphere_icos_point_num ( factor );
cout << "\n";
cout << " Number of vertices = " << node_num << "\n";
node_xyz = sphere_icos1_points ( factor, node_num );
r8mat_transpose_print_some ( 3, node_num, node_xyz, 1, 1, 3, 20,
" Initial part of NODE_XYZ array:" );
//
// Write the nodes to a file.
//
filename = "sphere_icos1_points_f" + i4_to_string ( factor, "%d" ) + ".xyz";
r8mat_write ( filename, 3, node_num, node_xyz );
cout << "\n";
cout << " Wrote data to \"" << filename << "\"\n";
delete [] node_xyz;
return;
}
//****************************************************************************80
void test03 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST03 tests SPHERE_ICOS2_POINTS.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2010
//
// Author:
//
// John Burkardt
//
{
int factor;
string filename;
int node;
int node_num;
double *node_xyz;
ofstream output;
cout << "\n";
cout << "TEST03\n";
cout << " SPHERE_ICOS_POINT_NUM \"sizes\" a grid generated\n";
cout << " on an icosahedron and projected to a sphere.\n";
cout << " SPHERE_ICOS2_POINTS creates the grid.\n";
factor = 3;
cout << "\n";
cout << " Sizing factor FACTOR = " << factor << "\n";
node_num = sphere_icos_point_num ( factor );
cout << "\n";
cout << " Number of nodes = " << node_num << "\n";
node_xyz = sphere_icos2_points ( factor, node_num );
r8mat_transpose_print_some ( 3, node_num, node_xyz, 1, 1, 3, 20,
" Initial part of NODE_XYZ array:" );
//
// Write the nodes to a file.
//
filename = "sphere_icos2_points_f" + i4_to_string ( factor, "%d" ) + ".xyz";
r8mat_write ( filename, 3, node_num, node_xyz );
cout << "\n";
cout << " Wrote data to \"" << filename << "\"\n";
delete [] node_xyz;
return;
}
//****************************************************************************80
void test04 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST04 tests SPHERE_LL_POINTS.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2012
//
// Author:
//
// John Burkardt
//
{
int lat_num = 3;
int lon_num = 4;
double pc[3] = { 0.0, 0.0, 0.0 };
int i;
int j;
int k;
int node_num;
double *node_xyz;
double r = 10.0;
cout << "\n";
cout << "TEST04\n";
cout << " SPHERE_LL_POINTS produces latitude/longitude\n";
cout << " points on a sphere in 3D.\n";
cout << "\n";
cout << " Radius = " << r << "\n";
r8vec_print ( 3, pc, " Center:" );
cout << "\n";
cout << " The number of latitudes = " << lat_num << "\n";
cout << " The number of longitudes = " << lon_num << "\n";
node_num = sphere_ll_point_num ( lat_num, lon_num );
cout << "\n";
cout << " The number of grid points is " << node_num << "\n";
node_xyz = sphere_ll_points ( r, pc, lat_num, lon_num, node_num );
cout << "\n";
k = 0;
cout << " " << setw(8) << k
<< " " << setw(12) << node_xyz[0+k*3]
<< " " << setw(12) << node_xyz[1+k*3]
<< " " << setw(12) << node_xyz[2+k*3] << "\n";
for ( i = 1; i <= lat_num; i++ )
{
cout << "\n";
for ( j = 0; j < lon_num; j++ )
{
k = k + 1;
cout << " " << setw(8) << k
<< " " << setw(12) << node_xyz[0+k*3]
<< " " << setw(12) << node_xyz[1+k*3]
<< " " << setw(12) << node_xyz[2+k*3] << "\n";
}
}
cout << "\n";
k = k + 1;
cout << " " << setw(8) << k
<< " " << setw(12) << node_xyz[0+k*3]
<< " " << setw(12) << node_xyz[1+k*3]
<< " " << setw(12) << node_xyz[2+k*3] << "\n";
delete [] node_xyz;
return;
}
//****************************************************************************80
void test05 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST05 tests SPHERE_SPIRALPOINTS.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2010
//
// Author:
//
// John Burkardt
//
{
string filename;
double center_xyz[3] = { 0.0, 0.0, 0.0 };
int node;
int node_num = 500;
double *node_xyz;
ofstream output;
double r = 1.0;
cout << "\n";
cout << "TEST05\n";
cout << " SPHERE_SPIRALPOINTS produces a spiral of\n";
cout << " points on an implicit sphere in 3D.\n";
cout << "\n";
cout << " Radius = " << r << "\n";
r8vec_print ( 3, center_xyz, " Center:" );
cout << "\n";
cout << " The number of spiral points is " << node_num << "\n";
node_xyz = sphere_spiralpoints ( r, center_xyz, node_num );
r8mat_transpose_print_some ( 3, node_num, node_xyz, 1, 1, 3, 10,
" The spiral points:" );
//
// Write the nodes to a file.
//
filename = "sphere_grid_spiral_n" + i4_to_string ( node_num, "%d" ) + ".xyz";
r8mat_write ( filename, 3, node_num, node_xyz );
cout << "\n";
cout << " Wrote data to \"" << filename << "\"\n";
delete [] node_xyz;
return;
}
//****************************************************************************80
void test06 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST06 tests SPHERE_LL_LINES.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2012
//
// Author:
//
// John Burkardt
//
{
int lat_num = 3;
int *line;
int line_num;
int long_num = 4;
cout << "\n";
cout << "TEST06\n";
cout << " SPHERE_LL_LINES computes latitude/longitude\n";
cout << " lines on a sphere in 3D.\n";
cout << "\n";
cout << " Number of latitudes is " << lat_num << "\n";
cout << " Number of longitudes is " << long_num << "\n";
line_num = sphere_ll_line_num ( lat_num, long_num );
cout << "\n";
cout << " Number of line segments is " << line_num << "\n";
line = sphere_ll_lines ( lat_num, long_num, line_num );
i4mat_transpose_print ( 2, line_num, line, " Grid line vertices:" );
free ( line );
return;
}
//****************************************************************************80
void test07 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST07 tests SPHERE_GRID_Q4.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2010
//
// Author:
//
// John Burkardt
//
{
int lat_num = 3;
int long_num = 4;
int rectangle_num = lat_num * long_num;
int *rectangle_node;
cout << "\n";
cout << "TEST07\n";
cout << " SPHERE_GRID_Q4 computes a grid\n";
cout << " of Q4 rectangular elements on a sphere in 3D.\n";
cout << "\n";
cout << " Number of latitudes is " << lat_num << "\n";
cout << " Number of longitudes is " << long_num << "\n";
cout << " The number of rectangles is " << rectangle_num << "\n";
rectangle_node = sphere_grid_q4 ( lat_num, long_num );
i4mat_transpose_print ( 4, rectangle_num, rectangle_node,
" Rectangle vertices:" );
delete [] rectangle_node;
return;
}
//****************************************************************************80
void test08 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST08 tests SPHERE_GRID_T3.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 August 2010
//
// Author:
//
// John Burkardt
//
{
int lat_num = 3;
int lon_num = 4;
int triangle_num;
int *triangle_node;
cout << "\n";
cout << "TEST08\n";
cout << " SPHERE_GRID_T3 computes a grid\n";
cout << " of T3 triangular elements on a sphere in 3D.\n";
cout << "\n";
cout << " Number of latitudes is " << lat_num << "\n";
cout << " Number of longitudes is " << lon_num << "\n";
triangle_node = sphere_grid_t3 ( lat_num, lon_num );
triangle_num = 2 * ( lat_num + 1 ) * lon_num;
cout << "\n";
cout << " The number of triangles is " << triangle_num << "\n";
i4mat_transpose_print ( 3, triangle_num, triangle_node,
" Triangle vertices:" );
delete [] triangle_node;
return;
}
//****************************************************************************80
void test09 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST09 tests SPHERE_UNIT_SAMPLE.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 August 2010
//
// Author:
//
// John Burkardt
//
{
string filename;
int node;
int node_num;
double *node_xyz;
ofstream output;
int seed = 123456789;
cout << "\n";
cout << "TEST09\n";
cout << " For the unit sphere in 3 dimensions:\n";
cout << " SPHERE_UNIT_SAMPLE does a random sampling.\n";
node_num = 1000;
node_xyz = sphere_unit_sample ( node_num, &seed );
r8mat_transpose_print_some ( 3, node_num, node_xyz, 1, 1, 3, 10,
" First 10 values:" );
//
// Write the nodes to a file.
//
filename = "sphere_sample_n" + i4_to_string ( node_num, "%d" ) + ".xyz";
r8mat_write ( filename, 3, node_num, node_xyz );
cout << "\n";
cout << " Wrote data to \"" << filename << "\"\n";
delete [] node_xyz;
return;
}
//****************************************************************************80
void test10 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST10 tests SPHERE_CUBED_POINTS.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 October 2012
//
// Author:
//
// John Burkardt
//
{
string filename;
int j;
int n;
int ns;
ofstream output;
double *xyz;
cout << "\n";
cout << "TEST10\n";
cout << " SPHERE_CUBED_POINTS computes points on a cubed sphere grid.\n";
n = 10;
cout << "\n";
cout << " Number of divisions on each face = " << n << "\n";
ns = sphere_cubed_point_num ( n );
cout << " Total number of points = " << ns << "\n";
xyz = sphere_cubed_points ( n, ns );
r8mat_transpose_print_some ( 3, ns, xyz, 1, 1, 3, 20, " Initial part of XYZ array:" );
//
// Write the nodes to a file.
//
filename = "sphere_cubed_f" + i4_to_string ( n, "%d" ) + ".xyz";
r8mat_write ( filename, 3, n, xyz );
cout << "\n";
cout << " Wrote data to \"" << filename << "\"\n";
delete [] xyz;
return;
}
//****************************************************************************80
void test11 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST11 is a dummy file. See the MATLAB source code for details.
//
{
return;
}
//****************************************************************************80
void test12 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST12 is a dummy file. See the MATLAB source code for details.
//
{
return;
}
//****************************************************************************80
void test13 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST13 is a dummy file. See the MATLAB source code for details.
//
{
return;
}
| [
"stesinigardi@hotmail.com"
] | stesinigardi@hotmail.com |
fd677f1c4f21ec28282bd458c3e00327ac35b45d | c7af0753636f8be5b4da74d22d6619ca5d96070b | /Allocator.h | 2bf48dd776e892e1bf915fbee2ab11e95367cc66 | [] | no_license | cescjiang/Mempool | 12712a3ec0e462f879268d808ca5cbafbbd4dfa6 | 16ec4adbe124b113eca6f652bd3f1300ba7b013b | refs/heads/master | 2021-01-16T18:40:29.365001 | 2013-04-23T17:54:10 | 2013-04-23T17:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,731 | h | #include <cstddef>
#include <new>
#include "Mempool.h"
template<typename T>
class Allocator
{
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template<typename _U>
struct rebind {
typedef Allocator<_U> other;
};
// 默认构造函数
Allocator() { }
// 析构函数
~Allocator() { }
// 拷贝构造函数
Allocator(const Allocator&) { }
// 泛化的拷贝构造函数
template<typename _U>
Allocator(const Allocator<_U>&) { }
// 返回对象地址
pointer address(reference x) const {
return (pointer) &x;
}
// 返回const对象地址
const_pointer address(const_reference x) const {
return (const_pointer) &x;
}
// 可成功配置的最大数
size_type max_size() {
return size_type(-1)/sizeof(T);
}
// 配置
pointer allocate(size_type n, const void* = 0) {
if ( n <= 0 || n > max_size() ) {
return NULL;
}
pointer p;
p = reinterpret_cast<pointer>(
Mempool::Allocate(sizeof(T) * n));
return p;
}
// 归还
void deallocate(pointer p, size_type) {
Mempool::Deallocate(p);
}
// 对元素进行拷贝构造
void construct(pointer p, const T& x) {
new (reinterpret_cast<void*>(p)) T(x);
}
// 对元素进行默认构造
void construct(pointer p) {
new (reinterpret_cast<void*>(p)) T();
}
// 元素的析构函数
void destroy(pointer p) {
p->~T();
}
};
| [
"gin.yjiang@gmail.com"
] | gin.yjiang@gmail.com |
dcfa231fcfa922806cf54b4dd9a8f21504f10c53 | 98b94eae33267a88fc0b743126f750af37c95e39 | /Data-Storage/ofstream-writing-data-to-a-file.cpp | e53a380cd5c09e3161108ec549567129bb3e4602 | [
"MIT"
] | permissive | ahuertaalberca/C-Plus-Plus | 003c75b7e70cc7eb326236706eaef2b04718497c | bbff921460ac4267af48558f040c7d82ccf42d5e | refs/heads/master | 2023-06-02T17:29:25.141650 | 2021-06-13T23:31:18 | 2021-06-13T23:31:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | //*********************************************
//This program writes data to a file.
//
// By: JESUS HILARIO HERNANDEZ
// Last modified: October 8, 2016
//*********************************************
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("demofile.txt");
cout << "Now writing data to the file.\n";
// Write for names to the file.
outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Chopin\n";
outputFile << "Mozart\n";
outputFile << "Brahms\n";
// Close the file
outputFile.close();
cout << "Done.\n";
return 0;
}
| [
"jesushilariohernandez@gmail.com"
] | jesushilariohernandez@gmail.com |
ccb9ec74e7154d601a0c04ad10093db02529921d | a20b2638065bc0e12f79a830035e3a6824cc01a3 | /src/options.hpp | 19e2766f35e7672f301f776617d06a6751233201 | [] | no_license | AdamLenda/tome2 | cc0b0af3a1c05896af8a8046fbebe1d3a573f61b | fd66550506705513d473967a5f72de21ca118eb7 | refs/heads/master | 2020-05-22T20:29:27.169251 | 2019-02-07T16:41:35 | 2019-02-13T09:18:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,541 | hpp | #pragma once
#include "h-basic.h"
#include "option_type.hpp"
#include <vector>
/**
* Game options accessible via the '=' menu.
*/
struct options {
//
// Option Set 1 -- User Interface
//
bool rogue_like_commands = false; /* Rogue-like commands */
bool quick_messages = true; /* Activate quick messages */
bool carry_query_flag = false; /* Prompt before picking things up */
bool use_old_target = false; /* Use old target by default */
bool always_pickup = false; /* Pick things up by default */
bool always_repeat = true; /* Repeat obvious commands */
bool ring_bell = false; /* Ring the bell (on errors, etc) */
//
// Option Set 2 -- Disturbance
//
bool find_ignore_stairs = false; /* Run past stairs */
bool find_ignore_doors = true; /* Run through open doors */
bool find_cut = false; /* Run past known corners */
bool find_examine = true; /* Run into potential corners */
bool disturb_move = false; /* Disturb whenever any monster moves */
bool disturb_near = true; /* Disturb whenever viewable monster moves */
bool disturb_panel = true; /* Disturb whenever map panel changes */
bool disturb_state = true; /* Disturn whenever player state changes */
bool disturb_minor = true; /* Disturb whenever boring things happen */
bool disturb_other = false; /* Disturb whenever various things happen */
bool last_words = true; /* Get last words upon dying */
bool wear_confirm = true; /* Confirm before putting on known cursed items */
bool confirm_stairs = false; /* Prompt before staircases... */
bool disturb_pets = false; /* Pets moving nearby disturb us */
//
// Option Set 3 -- Game-Play
//
bool auto_scum = true; /* Auto-scum for good levels */
bool view_perma_grids = true; /* Map remembers all perma-lit grids */
bool view_torch_grids = false; /* Map remembers all torch-lit grids */
bool dungeon_align = true; /* Generate dungeons with aligned rooms */
bool dungeon_stair = true; /* Generate dungeons with connected stairs */
bool flow_by_sound = false; /* Monsters track new player location */
bool smart_learn = false; /* Monsters learn from their mistakes */
bool small_levels = true; /* Allow unusually small dungeon levels */
bool empty_levels = true; /* Allow empty 'arena' levels */
//
// Option Set 4 -- Efficiency
//
bool view_reduce_lite = false; /* Reduce lite-radius when running */
bool avoid_abort = false; /* Avoid checking for user abort */
bool avoid_shimmer = false; /* Avoid processing extra shimmering */
bool avoid_other = false; /* Avoid processing special colors */
bool flush_failure = true; /* Flush input on any failure */
bool flush_disturb = false; /* Flush input on disturbance */
bool flush_command = false; /* Flush input before every command */
bool fresh_before = true; /* Flush output before normal commands */
bool fresh_after = false; /* Flush output after normal commands */
bool fresh_message = false; /* Flush output after all messages */
bool hilite_player = false; /* Hilite the player with the cursor */
bool view_yellow_lite = false; /* Use special colors for torch-lit grids */
bool view_bright_lite = false; /* Use special colors for 'viewable' grids */
bool view_granite_lite = false; /* Use special colors for wall grids (slow) */
bool view_special_lite = false; /* Use special colors for floor grids (slow) */
bool center_player = false; /* Center view on player */
//
// Option Set 5 - ToME options
//
bool ingame_help = true; /* In-game contextual help? */
bool auto_more = false; /* Auto more */
bool player_char_health = true; /* Display the player as a special symbol when in bad health ? */
bool linear_stats = true;
//
// Option Set 6 - Birth options
//
bool preserve = true; /* Preserve artifacts */
bool autoroll = true; /* Specify 'minimal' stats to roll */
bool point_based = false; /* Generate character using a point system */
bool ironman_rooms = false; /* Always generate very unusual rooms */
bool joke_monsters = false; /* Allow 'joke' monsters */
bool always_small_level = false; /* Force small levels */
bool fate_option = true; /* Player can receive fates */
bool no_selling = false; /* Player cannot sell items */
//
// Other options
//
bool cheat_peek = false; /* Peek into object creation */
bool cheat_hear = false; /* Peek into monster creation */
bool cheat_room = false; /* Peek into dungeon creation */
bool cheat_xtra = false; /* Peek into something else */
bool cheat_live = false; /* Allow player to avoid death */
byte hitpoint_warn = 0; /* Hitpoint warning (0 to 9) */
byte delay_factor = 0; /* Delay factor (0 to 9) */
s16b autosave_freq = 100; /* Autosave frequency */
bool autosave_t = false; /* Timed autosave */
bool autosave_l = false; /* Autosave before entering new levels */
/**
* Option groups
*/
std::vector<option_type> standard_options = {
// User-Interface
{ &rogue_like_commands, 1, 0, "rogue_like_commands", "Rogue-like commands" },
{ &quick_messages , 1, 1, "quick_messages" , "Activate quick messages" },
{ &carry_query_flag , 1, 3, "carry_query_flag" , "Prompt before picking things up" },
{ &use_old_target , 1, 4, "use_old_target" , "Use old target by default" },
{ &always_pickup , 1, 5, "always_pickup" , "Pick things up by default" },
{ &always_repeat , 1, 7, "always_repeat" , "Repeat obvious commands" },
{ &ring_bell , 1, 18, "ring_bell" , "Audible bell (on errors, etc)" },
// Disturbance
{ &find_ignore_stairs , 2, 0, "find_ignore_stairs" , "Run past stairs" },
{ &find_ignore_doors , 2, 1, "find_ignore_doors" , "Run through open doors" },
{ &find_cut , 2, 2, "find_cut" , "Run past known corners" },
{ &find_examine , 2, 3, "find_examine" , "Run into potential corners" },
{ &disturb_move , 2, 4, "disturb_move" , "Disturb whenever any monster moves" },
{ &disturb_near , 2, 5, "disturb_near" , "Disturb whenever viewable monster moves" },
{ &disturb_panel , 2, 6, "disturb_panel" , "Disturb whenever map panel changes" },
{ &disturb_state , 2, 7, "disturb_state" , "Disturb whenever player state changes" },
{ &disturb_minor , 2, 8, "disturb_minor" , "Disturb whenever boring things happen" },
{ &disturb_other , 2, 9, "disturb_other" , "Disturb whenever random things happen" },
{ &last_words , 2, 12, "last_words" , "Get last words when the character dies" },
{ &wear_confirm , 2, 15, "confirm_wear" , "Confirm to wear/wield known cursed items" },
{ &confirm_stairs , 2, 16, "confirm_stairs" , "Prompt before exiting a dungeon level" },
{ &disturb_pets , 2, 17, "disturb_pets" , "Disturb when visible pets move" },
// Game-Play
{ &auto_scum , 3, 1, "auto_scum" , "Auto-scum for good levels" },
{ &view_perma_grids , 3, 6, "view_perma_grids" , "Map remembers all perma-lit grids" },
{ &view_torch_grids , 3, 7, "view_torch_grids" , "Map remembers all torch-lit grids" },
{ &dungeon_align , 3, 8, "dungeon_align" , "Generate dungeons with aligned rooms" },
{ &dungeon_stair , 3, 9, "dungeon_stair" , "Generate dungeons with connected stairs" },
{ &flow_by_sound , 3, 10, "flow_by_sound" , "Monsters chase current location (v.slow)" },
{ &smart_learn , 3, 14, "smart_learn" , "Monsters learn from their mistakes" },
{ &small_levels , 3, 17, "small_levels" , "Allow unusually small dungeon levels" },
{ &empty_levels , 3, 18, "empty_levels" , "Allow empty 'arena' levels" },
// Efficiency
{ &view_reduce_lite , 4, 0, "view_reduce_lite" , "Reduce lite-radius when running" },
{ &avoid_abort , 4, 2, "avoid_abort" , "Avoid checking for user abort" },
{ &avoid_shimmer , 4, 17, "avoid_shimmer" , "Avoid extra shimmering (fast)" },
{ &avoid_other , 4, 3, "avoid_other" , "Avoid processing special colors (fast)" },
{ &flush_failure , 4, 4, "flush_failure" , "Flush input on various failures" },
{ &flush_disturb , 4, 5, "flush_disturb" , "Flush input whenever disturbed" },
{ &flush_command , 4, 6, "flush_command" , "Flush input before every command" },
{ &fresh_before , 4, 7, "fresh_before" , "Flush output before every command" },
{ &fresh_after , 4, 8, "fresh_after" , "Flush output after every command" },
{ &fresh_message , 4, 9, "fresh_message" , "Flush output after every message" },
{ &hilite_player , 4, 11, "hilite_player" , "Hilite the player with the cursor" },
{ &view_yellow_lite , 4, 12, "view_yellow_lite" , "Use special colors for torch-lit grids" },
{ &view_bright_lite , 4, 13, "view_bright_lite" , "Use special colors for 'viewable' grids" },
{ &view_granite_lite , 4, 14, "view_granite_lite" , "Use special colors for wall grids (slow)" },
{ &view_special_lite , 4, 15, "view_special_lite" , "Use special colors for floor grids (slow)" },
{ ¢er_player , 4, 16, "center_player" , "Center the view on the player (very slow)" },
// ToME options
{ &ingame_help , 5, 1, "ingame_help" , "Ingame contextual help" },
{ &auto_more , 5, 4, "auto_more" , "Automatically clear '-more-' prompts" },
{ &player_char_health , 5, 6, "player_char_health" , "Player char represent his/her health" },
{ &linear_stats , 5, 7, "linear_stats" , "Stats are represented in a linear way" },
// Birth Options
{ &preserve , 6, 2, "preserve" , "Preserve artifacts" },
{ &autoroll , 6, 3, "autoroll" , "Specify 'minimal' stats" },
{ &point_based , 6, 17, "point_based" , "Generate character using a point system" },
{ &ironman_rooms , 6, 6, "ironman_rooms" , "Always generate very unusual rooms" },
{ &joke_monsters , 6, 14, "joke_monsters" , "Allow use of some 'joke' monsters" },
{ &always_small_level , 6, 16, "always_small_level" , "Always make small levels" },
{ &fate_option , 6, 18, "fate_option" , "You can receive fates, good or bad" },
{ &no_selling , 6, 20, "no_selling" , "Items always sell for 0 gold" },
};
/*
* Cheating options
*/
std::vector<option_type> cheat_options = {
{ &cheat_peek, 0, 0, "cheat_peek", "Peek into object creation" },
{ &cheat_hear, 0, 1, "cheat_hear", "Peek into monster creation" },
{ &cheat_room, 0, 2, "cheat_room", "Peek into dungeon creation" },
{ &cheat_xtra, 0, 3, "cheat_xtra", "Peek into something else" },
{ &cheat_live, 0, 5, "cheat_live", "Allow player to avoid death" },
};
/**
* Autosave boolean options
*/
std::vector<option_type> autosave_options {
{ &autosave_l, 0, 6, "autosave_l", "Autosave when entering new levels" },
{ &autosave_t, 0, 7, "autosave_t", "Timed autosave" }
};
/*
* Reset cheat options
*/
void reset_cheat_options();
/**
* Convert delay_factor to milliseconds
*/
int delay_factor_ms() const
{
return delay_factor * delay_factor * delay_factor;
}
};
| [
"bardur@scientician.net"
] | bardur@scientician.net |
74c8986809acd39a2042682ddab6b232db72346d | 057eff64adf244988b77b3b68aeeae98f78554cd | /lib/touchgfx/framework/source/touchgfx/widgets/canvas/AbstractPainterRGBA2222.cpp | 089d3f5be6b03cd281be64f7c81e4e47e74684a6 | [] | no_license | tBeslan/F746_disco_mbed_tgfx | b9c79b87dc79c0772c6969ec902f69af33311a8c | 8c6bf13f26b0c90f6f96437d1b5ba0c0d824fc37 | refs/heads/master | 2022-12-15T21:44:05.185681 | 2020-09-04T07:58:06 | 2020-09-04T07:58:06 | 292,780,121 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,661 | cpp | /**
******************************************************************************
* This file is part of the TouchGFX 4.14.0 distribution.
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <touchgfx/Color.hpp>
#include <touchgfx/widgets/canvas/AbstractPainterRGBA2222.hpp>
namespace touchgfx
{
void AbstractPainterRGBA2222::render(uint8_t* ptr,
int x,
int xAdjust,
int y,
unsigned count,
const uint8_t* covers)
{
uint8_t* p = ptr + (x + xAdjust);
currentX = x + areaOffsetX;
currentY = y + areaOffsetY;
if (renderInit())
{
do
{
uint8_t red, green, blue, alpha;
if (renderNext(red, green, blue, alpha))
{
uint8_t combinedAlpha = LCD::div255((*covers) * LCD::div255(alpha * widgetAlpha));
covers++;
if (combinedAlpha == 0xFF) // max alpha=0xFF on "*covers" and max alpha=0xFF on "widgetAlpha"
{
// Render a solid pixel
renderPixel(p, red, green, blue);
}
else
{
uint8_t ialpha = 0xFF - combinedAlpha;
uint8_t p_red = LCD8bpp_RGBA2222::getRedFromColor(*p);
uint8_t p_green = LCD8bpp_RGBA2222::getGreenFromColor(*p);
uint8_t p_blue = LCD8bpp_RGBA2222::getBlueFromColor(*p);
renderPixel(p,
LCD::div255(red * combinedAlpha + p_red * ialpha),
LCD::div255(green * combinedAlpha + p_green * ialpha),
LCD::div255(blue * combinedAlpha + p_blue * ialpha));
}
}
p++;
currentX++;
}
while (--count != 0);
}
}
void AbstractPainterRGBA2222::renderPixel(uint8_t* p, uint8_t red, uint8_t green, uint8_t blue)
{
*p = LCD8bpp_RGBA2222::getColorFromRGB(red, green, blue);
}
} // namespace touchgfx
| [
"tbeslan@gmail.com"
] | tbeslan@gmail.com |
8959e3407427face7cb765ccdeaf710e3f1470fa | 88378ba2d674539b7184d06d09dd6ac1f5120c73 | /src/qt/macos_appnap.h | 18d709660317a5a1c9cedc1c1d76d4476e810ea6 | [
"MIT"
] | permissive | aurarad/Auroracoin | c1868ee0f89986fe18583ff9ea3b97da99bbd851 | 68551e406426dbea315139e58ac683ea69621365 | refs/heads/master | 2023-07-07T02:00:32.639831 | 2023-07-03T07:41:57 | 2023-07-03T07:41:57 | 54,232,156 | 36 | 34 | MIT | 2023-06-06T08:24:51 | 2016-03-18T21:20:48 | C++ | UTF-8 | C++ | false | false | 605 | h | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Copyright (c) 2014-2020 The Auroracoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef AURORACOIN_QT_MACOS_APPNAP_H
#define AURORACOIN_QT_MACOS_APPNAP_H
#include <memory>
class CAppNapInhibitor final
{
public:
explicit CAppNapInhibitor();
~CAppNapInhibitor();
void disableAppNap();
void enableAppNap();
private:
class CAppNapImpl;
std::unique_ptr<CAppNapImpl> impl;
};
#endif // AURORACOIN_QT_MACOS_APPNAP_H | [
"myckel@sdf.org"
] | myckel@sdf.org |
b0165a10e90ac6b7c906adf721d736f625815cdf | 46b00b71d5fa7fc6f7b5d8e4e3a1ac6123406fa8 | /src/objects/sound/AudioExporter.h | ae1132c7e69e78b6ddbeb10b31ed5028e778bef0 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SoftwareWorks/ofxVisualProgramming-visual-programming-node-editor | 7a42ce4556baa17c7866c527f7d8c4a13691d9a0 | e47840fdedd9245c07c552af17ccb3a8e6e33b5d | refs/heads/master | 2020-09-16T05:25:59.044749 | 2019-11-23T09:59:17 | 2019-11-23T09:59:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,955 | h | /*==============================================================================
ofxVisualProgramming: A visual programming patching environment for OF
Copyright (c) 2019 Emanuele Mazza aka n3m3da <emanuelemazza@d3cod3.org>
ofxVisualProgramming is distributed under the MIT License.
This gives everyone the freedoms to use ofxVisualProgramming in any context:
commercial or non-commercial, public or private, open or closed source.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
See https://github.com/d3cod3/ofxVisualProgramming for documentation
==============================================================================*/
#pragma once
#include "PatchObject.h"
#include "ofxFFmpegRecorder.h"
class AudioExporter : public PatchObject {
public:
AudioExporter();
void newObject();
void setupObjectContent(shared_ptr<ofAppGLFWWindow> &mainWindow);
void updateObjectContent(map<int,PatchObject*> &patchObjects, ofxThreadedFileDialog &fd);
void drawObjectContent(ofxFontStash *font);
void removeObjectContent();
void loadAudioSettings();
void audioInObject(ofSoundBuffer &inputBuffer);
void mouseMovedObjectContent(ofVec3f _m);
void dragGUIObject(ofVec3f _m);
void fileDialogResponse(ofxThreadedFileDialogResponse &response);
void onToggleEvent(ofxDatGuiToggleEvent e);
ofxFFmpegRecorder recorder;
ofPolyline waveform;
bool exportAudioFlag;
bool audioSaved;
int bufferSize;
int sampleRate;
size_t lastAudioTimeReset;
float audioFPS;
int audioCounter;
ofxDatGui* gui;
ofxDatGuiHeader* header;
ofxDatGuiToggle* recButton;
};
| [
"n3m3da@d3cod3.org"
] | n3m3da@d3cod3.org |
5b81bf28ec9e37d047dd3f378390bdcf90c6b1c6 | aca4f00c884e1d0e6b2978512e4e08e52eebd6e9 | /2014/zoj/ZPC14/proD.cpp | b021b0c3489bd46d2a3daa196114fa8bbed5f824 | [] | no_license | jki14/competitive-programming | 2d28f1ac8c7de62e5e82105ae1eac2b62434e2a4 | ba80bee7827521520eb16a2d151fc0c3ca1f7454 | refs/heads/master | 2023-08-07T19:07:22.894480 | 2023-07-30T12:18:36 | 2023-07-30T12:18:36 | 166,743,930 | 2 | 0 | null | 2021-09-04T09:25:40 | 2019-01-21T03:40:47 | C++ | UTF-8 | C++ | false | false | 7,813 | cpp | #include<iostream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<climits>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<list>
#include<bitset>
#include<set>
#include<map>
#include<functional>
#include<numeric>
#include<utility>
#include<iomanip>
using namespace std;
//HEAD_OF_TEMPLATE_BY_JKI14
//TYPEDEF
typedef long long lld;
typedef double dou;
typedef pair<int,int> pii;
//COMPARE
inline int min(const int &x, const int &y){ return x<y?x:y; }
inline lld min(const lld &x, const lld &y){ return x<y?x:y; }
inline dou min(const dou &x, const dou &y){ return x<y?x:y; }
inline int max(const int &x, const int &y){ return x>y?x:y; }
inline lld max(const lld &x, const lld &y){ return x>y?x:y; }
inline dou max(const dou &x, const dou &y){ return x>y?x:y; }
template<class T> inline void _updmin(T &x,const T &y){ if(x>y)x=y; }
template<class T> inline void _updmax(T &x,const T &y){ if(x<y)x=y; }
//STL
#define _size(x) ((int)(x.size()))
#define _mkpr(x,y) make_pair(x,y)
//BIT
#define _ni(x) (1<<(x))
#define _niL(x) (1LL<<(x))
#define _has(s,x) ((s&(_ni(x)))!=0)
#define _hasL(s,x) ((s&(_niL(x)))!=0LL)
template<class T> inline T _lowbit(const T &x){ return (x^(x-1))&x; }
template<class T> inline int _bitsize(const T &x){ return (x==0)?0:(1+_bitsize(x&(x-1))); }
//CONST VALUE
const dou _pi=acos(-1.0);
const dou _eps=1e-5;
//CALCULATE
template<class T> inline T _sqr(const T &x){ return x*x; }
//NUMBERIC
template<class T> inline T _gcd(const T &x,const T &y){
if(x<0)return _gcd(-x,y);
if(y<0)return _gcd(x,-y);
return (y==0)?x:_gcd(y,x%y);
}
template<class T> inline T _lcm(const T &x,const T &y){
if(x<0)return _lcm(-x,y);
if(y<0)return _lcm(x,-y);
return x*(y/_gcd(x,y));
}
template<class T> inline T _euc(const T &a,const T &b,T &x,T &y){
/* a*x+b*y == _euc(); */
if(a<0){T d=_euc(-a,b,x,y);x=-x;return d;}
if(b<0){T d=_euc(a,-b,x,y);y=-y;return d;}
if(b==0){
x=1;y=0;return a;
}else{
T d=_euc(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;
return d;
}
}
template<class T> inline vector<pair<T,int> > _fac(T n){
vector<pair<T,int> > ret;for (T i=2;n>1;){
if (n%i==0){int cnt=0;for (;n%i==0;cnt++,n/=i);ret.push_back(_mkpr(i,cnt));}
i++;if (i>n/i) i=n;
}
if (n>1) ret.push_back(_mkpr(n,1));return ret;
}
template<class T> inline int _prm(const T &x){
if(x<=1)return 0;
for(T i=2;sqr(i)<=x;i++)if(x%i==0)return 0;
return 1;
}
template<class T> inline T _phi(T x){
/* EularFunction:return the number of integers which are the relatively prime number of x and less than x. */
vector<pair<T,int> > f=_fac(x);T ret=x;
for(int i=0;i<_size(f);i++)ret=ret/f[i].first*(f[i].first-1);
return ret;
}
template<class T> inline T _inv(T a,T b){
/* if(k%a==0) (k/a)%b==((k%b)*(_inv()%b))%b */
/* original code begin
T x0=1,y0=0,x1=0,y1=1;
for(T r=a%b;r!=0;r=a%b){ T k=a/b,dx=x0-k*x1,dy=y0-k*y1;x0=x1;y0=y1;x1=dx;y1=dy;a=b;b=r; }
if(x1==0)x1=1;return x1;
original code end */
T x,y;_euc(a,b,x,y);
if(x==0)x=1;return x;
}
template<class T> inline T _cmod(T x,T m){ return (x%m+m)%m; }
template<class T> inline T _amod(T x,T y,T m){ return x=((x+y)%m+m)%m; }
template<class T> inline T _mmod(T x,T y,T m){ return (T)((((lld)x)*((lld)y)%((lld)m)+((lld)m))%((lld)m)); }
template<class T> inline T _pmod(T x,T y,T m){
if(y==0)return 1%m;else if((y&1)==0){
T z=_pmod(x,y>>1,m);return _mmod(z,z,m);
}else return _mmod(_pmod(x,y^1,m),x,m);
}
#define _cmd(x) _cmod(x,mod)
#define _amd(x,y) _amod(x,y,mod)
#define _mmd(x,y) _mmod(x,y,mod)
#define _pmd(x,y) _pmod(x,y,mod)
//MATRIX OPERATIONS
const int _MTRXSIZE = 40;
template<class T> inline void _shwMTRX(int n,T A[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++){ for(int j=0;j<n;j++)cout<<A[i][j]<<" ";cout<<endl; }
}
template<class T> inline void _stdMTRX(int n,T A[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++)for(int j=0;j<n;j++) A[i][j]=(i==j)?1:0;
}
template<class T> inline void _addMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];
}
template<class T> inline void _subMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];
}
template<class T> inline void _mulMTRX(int n,T C[_MTRXSIZE][_MTRXSIZE],T _A[_MTRXSIZE][_MTRXSIZE],T _B[_MTRXSIZE][_MTRXSIZE]){
T A[_MTRXSIZE][_MTRXSIZE],B[_MTRXSIZE][_MTRXSIZE];
for(int i=0;i<n;i++)for(int j=0;j<n;j++){ A[i][j]=_A[i][j];B[i][j]=_B[i][j];C[i][j]=0; }
for(int i=0;i<n;i++)for(int j=0;j<n;j++)for(int k=0;k<n;k++)C[i][j]+=A[i][k]*B[k][j];
}
template<class T> inline void _addModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=_cmod(A[i][j]+B[i][j],m);
}
template<class T> inline void _subModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T A[_MTRXSIZE][_MTRXSIZE],T B[_MTRXSIZE][_MTRXSIZE]){
for(int i=0;i<n;i++)for(int j=0;j<n;j++) C[i][j]=_cmod(A[i][j]-B[i][j],m);
}
template<class T> inline void _mulModMTRX(int n,T m,T C[_MTRXSIZE][_MTRXSIZE],T _A[_MTRXSIZE][_MTRXSIZE],T _B[_MTRXSIZE][_MTRXSIZE]){
T A[_MTRXSIZE][_MTRXSIZE],B[_MTRXSIZE][_MTRXSIZE];
for(int i=0;i<n;i++)for(int j=0;j<n;j++){ A[i][j]=_A[i][j];B[i][j]=_B[i][j];C[i][j]=0; }
for(int i=0;i<n;i++)for(int j=0;j<n;j++)for(int k=0;k<n;k++)C[i][j]=(C[i][j]+_mmod(A[i][k],B[k][j],m))%m;
}
template<class T> inline void _powModMTRX(int n,T y,T m,T C[_MTRXSIZE][_MTRXSIZE],T X[_MTRXSIZE][_MTRXSIZE]){
T R[_MTRXSIZE][_MTRXSIZE];for(int i=0;i<n;i++)for(int j=0;j<n;j++)R[i][j]=X[i][j];_stdMTRX(n,C);
if(y>0)for(T i=1;;i<<=1){
if(y&i)_mulModMTRX(n,m,C,C,R);
_mulModMTRX(n,m,R,R,R);
if(i>(y>>1))break;
}
}
//FRACTION
template<class T> struct _frct{T a,b;_frct(T a=0,T b=1);string toString();};
template<class T> _frct<T>::_frct(T a,T b){T d=_gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;}
template<class T> string _frct<T>::toString(){ostringstream tout;tout<<a<<"/"<<b;return tout.str();}
template<class T> _frct<T> operator+(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b+q.a*p.b,p.b*q.b);}
template<class T> _frct<T> operator-(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b-q.a*p.b,p.b*q.b);}
template<class T> _frct<T> operator*(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.a,p.b*q.b);}
template<class T> _frct<T> operator/(_frct<T> p,_frct<T> q){return _frct<T>(p.a*q.b,p.b*q.a);}
//TAIL_OF_TEMPLATE_BY_JKI14
#define N 2100
const double per[7]={ 1.0,1.0,0.3,0.2,0.07,0.03 };
struct date{
int yy,mm,dd;
bool operator < (const date &_op) const{
if(_op.yy!=yy)return _op.yy>yy;
if(_op.mm!=mm)return _op.mm>mm;
return _op.dd>dd;
}
bool operator != (const date &_op) const{
if(_op.yy!=yy)return true;
if(_op.mm!=mm)return true;
return _op.dd!=dd;
}
};
struct member{
int id,sc,fl;
date dt;
bool operator < (const member &_op) const{
if(_op.sc!=sc)return _op.sc<sc;
if(_op.dt!=dt)return dt<_op.dt;
return _op.id>id;
}
} a[N];
int n,mem;
int ans[N];
int main(){
int T;scanf("%d",&T);
while(T--){scanf("%d",&n);mem=0;
for(int i=0;i<n;i++){
scanf("%d %d/%d/%d %d",&a[i].id,&a[i].dt.yy,&a[i].dt.mm,&a[i].dt.dd,&a[i].sc);
if(a[i].sc)mem++;a[i].fl=i;
}
sort(a,a+n);
int lev=7,cnt=0;
for(int i=0;i<n;i++){
if(!a[i].sc)
ans[a[i].fl]=1;
else{
if(lev==2){
ans[a[i].fl]=2;
continue;
}
while(lev>2 && cnt+1>(int)(((double)mem)*per[lev-1])){ lev--;cnt=0; }
ans[a[i].fl]=lev;cnt++;
}
}
for(int i=0;i<n;i++)printf("LV%d\n",ans[i]);
}
return 0;
}
| [
"jki14wz@gmail.com"
] | jki14wz@gmail.com |
a19736bcdddf18f5637db2387ce1f480afed8f93 | b04ad40334b32c948bedc863668ce2a27bbe3219 | /ncnn_project/crnn/main.cpp | abeef84a5b14f350aacea1a4e0ba95eda4a5d5c3 | [] | no_license | sunhailin-Leo/chineseocr_lite | b82e91bcc45883329a56156a5a5dd7ae9eafc593 | 9abac5e0a4dd4f6863afd93d7fc4548ecd499e4d | refs/heads/master | 2021-03-14T09:33:23.369732 | 2020-03-12T07:55:10 | 2020-03-12T07:55:10 | 246,756,131 | 3 | 0 | null | 2020-03-12T06:02:44 | 2020-03-12T06:02:43 | null | UTF-8 | C++ | false | false | 21,920 | cpp | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 <iostream>
#include <math.h>
#include <cstdio>
#include <vector>
#include <numeric>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <string>
#include <boost/locale.hpp>
#include "platform.h"
#include "net.h"
using namespace std;
std::string alphabetChinese= u8"\'疗绚诚娇溜题贿者廖更纳加奉公一就汴计与路房原妇208-7其>:],,骑刈全消昏傈安久钟嗅不影处驽蜿资关椤地瘸专问忖票嫉炎韵要月田节陂鄙捌备拳伺眼网盎大傍心东愉汇蹿科每业里航晏字平录先13彤鲶产稍督腴有象岳注绍在泺文定核名水过理让偷率等这发”为含肥酉相鄱七编猥锛日镀蒂掰倒辆栾栗综涩州雌滑馀了机块司宰甙兴矽抚保用沧秩如收息滥页疑埠!!姥异橹钇向下跄的椴沫国绥獠报开民蜇何分凇长讥藏掏施羽中讲派嘟人提浼间世而古多倪唇饯控庚首赛蜓味断制觉技替艰溢潮夕钺外摘枋动双单啮户枇确锦曜杜或能效霜盒然侗电晁放步鹃新杖蜂吒濂瞬评总隍对独合也是府青天诲墙组滴级邀帘示已时骸仄泅和遨店雇疫持巍踮境只亨目鉴崤闲体泄杂作般轰化解迂诿蛭璀腾告版服省师小规程线海办引二桧牌砺洄裴修图痫胡许犊事郛基柴呼食研奶律蛋因葆察戏褒戒再李骁工貂油鹅章啄休场给睡纷豆器捎说敏学会浒设诊格廓查来霓室溆¢诡寥焕舜柒狐回戟砾厄实翩尿五入径惭喹股宇篝|;美期云九祺扮靠锝槌系企酰阊暂蚕忻豁本羹执条钦H獒限进季楦于芘玖铋茯未答粘括样精欠矢甥帷嵩扣令仔风皈行支部蓉刮站蜡救钊汗松嫌成可.鹤院从交政怕活调球局验髌第韫谗串到圆年米/*友忿检区看自敢刃个兹弄流留同没齿星聆轼湖什三建蛔儿椋汕震颧鲤跟力情璺铨陪务指族训滦鄣濮扒商箱十召慷辗所莞管护臭横硒嗓接侦六露党馋驾剖高侬妪幂猗绺骐央酐孝筝课徇缰门男西项句谙瞒秃篇教碲罚声呐景前富嘴鳌稀免朋啬睐去赈鱼住肩愕速旁波厅健茼厥鲟谅投攸炔数方击呋谈绩别愫僚躬鹧胪炳招喇膨泵蹦毛结54谱识陕粽婚拟构且搜任潘比郢妨醪陀桔碘扎选哈骷楷亿明缆脯监睫逻婵共赴淝凡惦及达揖谩澹减焰蛹番祁柏员禄怡峤龙白叽生闯起细装谕竟聚钙上导渊按艾辘挡耒盹饪臀记邮蕙受各医搂普滇朗茸带翻酚(光堤墟蔷万幻〓瑙辈昧盏亘蛀吉铰请子假闻税井诩哨嫂好面琐校馊鬣缂营访炖占农缀否经钚棵趟张亟吏茶谨捻论迸堂玉信吧瞠乡姬寺咬溏苄皿意赉宝尔钰艺特唳踉都荣倚登荐丧奇涵批炭近符傩感道着菊虹仲众懈濯颞眺南释北缝标既茗整撼迤贲挎耱拒某妍卫哇英矶藩治他元领膜遮穗蛾飞荒棺劫么市火温拈棚洼转果奕卸迪伸泳斗邡侄涨屯萋胭氡崮枞惧冒彩斜手豚随旭淑妞形菌吲沱争驯歹挟兆柱传至包内响临红功弩衡寂禁老棍耆渍织害氵渑布载靥嗬虽苹咨娄库雉榜帜嘲套瑚亲簸欧边6腿旮抛吹瞳得镓梗厨继漾愣憨士策窑抑躯襟脏参贸言干绸鳄穷藜音折详)举悍甸癌黎谴死罩迁寒驷袖媒蒋掘模纠恣观祖蛆碍位稿主澧跌筏京锏帝贴证糠才黄鲸略炯饱四出园犀牧容汉杆浈汰瑷造虫瘩怪驴济应花沣谔夙旅价矿以考su呦晒巡茅准肟瓴詹仟褂译桌混宁怦郑抿些余鄂饴攒珑群阖岔琨藓预环洮岌宀杲瀵最常囡周踊女鼓袭喉简范薯遐疏粱黜禧法箔斤遥汝奥直贞撑置绱集她馅逗钧橱魉[恙躁唤9旺膘待脾惫购吗依盲度瘿蠖俾之镗拇鲵厝簧续款展啃表剔品钻腭损清锶统涌寸滨贪链吠冈伎迥咏吁览防迅失汾阔逵绀蔑列川凭努熨揪利俱绉抢鸨我即责膦易毓鹊刹玷岿空嘞绊排术估锷违们苟铜播肘件烫审鲂广像铌惰铟巳胍鲍康憧色恢想拷尤疳知SYFDA峄裕帮握搔氐氘难墒沮雨叁缥悴藐湫娟苑稠颛簇后阕闭蕤缚怎佞码嘤蔡痊舱螯帕赫昵升烬岫、疵蜻髁蕨隶烛械丑盂梁强鲛由拘揉劭龟撤钩呕孛费妻漂求阑崖秤甘通深补赃坎床啪承吼量暇钼烨阂擎脱逮称P神属矗华届狍葑汹育患窒蛰佼静槎运鳗庆逝曼疱克代官此麸耧蚌晟例础榛副测唰缢迹灬霁身岁赭扛又菡乜雾板读陷徉贯郁虑变钓菜圾现琢式乐维渔浜左吾脑钡警T啵拴偌漱湿硕止骼魄积燥联踢玛|则窿见振畿送班钽您赵刨印讨踝籍谡舌崧汽蔽沪酥绒怖财帖肱私莎勋羔霸励哼帐将帅渠纪婴娩岭厘滕吻伤坝冠戊隆瘁介涧物黍并姗奢蹑掣垸锴命箍捉病辖琰眭迩艘绌繁寅若毋思诉类诈燮轲酮狂重反职筱县委磕绣奖晋濉志徽肠呈獐坻口片碰几村柿劳料获亩惕晕厌号罢池正鏖煨家棕复尝懋蜥锅岛扰队坠瘾钬@卧疣镇譬冰彷频黯据垄采八缪瘫型熹砰楠襁箐但嘶绳啤拍盥穆傲洗盯塘怔筛丿台恒喂葛永¥烟酒桦书砂蚝缉态瀚袄圳轻蛛超榧遛姒奘铮右荽望偻卡丶氰附做革索戚坨桷唁垅榻岐偎坛莨山殊微骇陈爨推嗝驹澡藁呤卤嘻糅逛侵郓酌德摇※鬃被慨殡羸昌泡戛鞋河宪沿玲鲨翅哽源铅语照邯址荃佬顺鸳町霭睾瓢夸椁晓酿痈咔侏券噎湍签嚷离午尚社锤背孟使浪缦潍鞅军姹驶笑鳟鲁》孽钜绿洱礴焯椰颖囔乌孔巴互性椽哞聘昨早暮胶炀隧低彗昝铁呓氽藉喔癖瑗姨权胱韦堑蜜酋楝砝毁靓歙锲究屋喳骨辨碑武鸠宫辜烊适坡殃培佩供走蜈迟翼况姣凛浔吃飘债犟金促苛崇坂莳畔绂兵蠕斋根砍亢欢恬崔剁餐榫快扶‖濒缠鳜当彭驭浦篮昀锆秸钳弋娣瞑夷龛苫拱致%嵊障隐弑初娓抉汩累蓖\"唬助苓昙押毙破城郧逢嚏獭瞻溱婿赊跨恼璧萃姻貉灵炉密氛陶砸谬衔点琛沛枳层岱诺脍榈埂征冷裁打蹴素瘘逞蛐聊激腱萘踵飒蓟吆取咙簋涓矩曝挺揣座你史舵焱尘苏笈脚溉榨诵樊邓焊义庶儋蟋蒲赦呷杞诠豪还试颓茉太除紫逃痴草充鳕珉祗墨渭烩蘸慕璇镶穴嵘恶骂险绋幕碉肺戳刘潞秣纾潜銮洛须罘销瘪汞兮屉r林厕质探划狸殚善煊烹〒锈逯宸辍泱柚袍远蹋嶙绝峥娥缍雀徵认镱谷=贩勉撩鄯斐洋非祚泾诒饿撬威晷搭芍锥笺蓦候琊档礁沼卵荠忑朝凹瑞头仪弧孵畏铆突衲车浩气茂悖厢枕酝戴湾邹飚攘锂写宵翁岷无喜丈挑嗟绛殉议槽具醇淞笃郴阅饼底壕砚弈询缕庹翟零筷暨舟闺甯撞麂茌蔼很珲捕棠角阉媛娲诽剿尉爵睬韩诰匣危糍镯立浏阳少盆舔擘匪申尬铣旯抖赘瓯居ˇ哮游锭茏歌坏甚秒舞沙仗劲潺阿燧郭嗖霏忠材奂耐跺砀输岖媳氟极摆灿今扔腻枝奎药熄吨话q额慑嘌协喀壳埭视著於愧陲翌峁颅佛腹聋侯咎叟秀颇存较罪哄岗扫栏钾羌己璨枭霉煌涸衿键镝益岢奏连夯睿冥均糖狞蹊稻爸刿胥煜丽肿璃掸跚灾垂樾濑乎莲窄犹撮战馄软络显鸢胸宾妲恕埔蝌份遇巧瞟粒恰剥桡博讯凯堇阶滤卖斌骚彬兑磺樱舷两娱福仃差找桁÷净把阴污戬雷碓蕲楚罡焖抽妫咒仑闱尽邑菁爱贷沥鞑牡嗉崴骤塌嗦订拮滓捡锻次坪杩臃箬融珂鹗宗枚降鸬妯阄堰盐毅必杨崃俺甬状莘货耸菱腼铸唏痤孚澳懒溅翘疙杷淼缙骰喊悉砻坷艇赁界谤纣宴晃茹归饭梢铡街抄肼鬟苯颂撷戈炒咆茭瘙负仰客琉铢封卑珥椿镧窨鬲寿御袤铃萎砖餮脒裳肪孕嫣馗嵇恳氯江石褶冢祸阻狈羞银靳透咳叼敷芷啥它瓤兰痘懊逑肌往捺坊甩呻〃沦忘膻祟菅剧崆智坯臧霍墅攻眯倘拢骠铐庭岙瓠′缺泥迢捶??郏喙掷沌纯秘种听绘固螨团香盗妒埚蓝拖旱荞铀血遏汲辰叩拽幅硬惶桀漠措泼唑齐肾念酱虚屁耶旗砦闵婉馆拭绅韧忏窝醋葺顾辞倜堆辋逆玟贱疾董惘倌锕淘嘀莽俭笏绑鲷杈择蟀粥嗯驰逾案谪褓胫哩昕颚鲢绠躺鹄崂儒俨丝尕泌啊萸彰幺吟骄苣弦脊瑰〈诛镁析闪剪侧哟框螃守嬗燕狭铈缮概迳痧鲲俯售笼痣扉挖满咋援邱扇歪便玑绦峡蛇叨〖泽胃斓喋怂坟猪该蚬炕弥赞棣晔娠挲狡创疖铕镭稷挫弭啾翔粉履苘哦楼秕铂土锣瘟挣栉习享桢袅磨桂谦延坚蔚噗署谟猬钎恐嬉雒倦衅亏璩睹刻殿王算雕麻丘柯骆丸塍谚添鲈垓桎蚯芥予飕镦谌窗醚菀亮搪莺蒿羁足J真轶悬衷靛翊掩哒炅掐冼妮l谐稚荆擒犯陵虏浓崽刍陌傻孜千靖演矜钕煽杰酗渗伞栋俗泫戍罕沾疽灏煦芬磴叱阱榉湃蜀叉醒彪租郡篷屎良垢隗弱陨峪砷掴颁胎雯绵贬沐撵隘篙暖曹陡栓填臼彦瓶琪潼哪鸡摩啦俟锋域耻蔫疯纹撇毒绶痛酯忍爪赳歆嘹辕烈册朴钱吮毯癜娃谀邵厮炽璞邃丐追词瓒忆轧芫谯喷弟半冕裙掖墉绮寝苔势顷褥切衮君佳嫒蚩霞佚洙逊镖暹唛&殒顶碗獗轭铺蛊废恹汨崩珍那杵曲纺夏薰傀闳淬姘舀拧卷楂恍讪厩寮篪赓乘灭盅鞣沟慎挂饺鼾杳树缨丛絮娌臻嗳篡侩述衰矛圈蚜匕筹匿濞晨叶骋郝挚蚴滞增侍描瓣吖嫦蟒匾圣赌毡癞恺百曳需篓肮庖帏卿驿遗蹬鬓骡歉芎胳屐禽烦晌寄媾狄翡苒船廉终痞殇々畦饶改拆悻萄£瓿乃訾桅匮溧拥纱铍骗蕃龋缬父佐疚栎醍掳蓄x惆颜鲆榆〔猎敌暴谥鲫贾罗玻缄扦芪癣落徒臾恿猩托邴肄牵春陛耀刊拓蓓邳堕寇枉淌啡湄兽酷萼碚濠萤夹旬戮梭琥椭昔勺蜊绐晚孺僵宣摄冽旨萌忙蚤眉噼蟑付契瓜悼颡壁曾窕颢澎仿俑浑嵌浣乍碌褪乱蔟隙玩剐葫箫纲围伐决伙漩瑟刑肓镳缓蹭氨皓典畲坍铑檐塑洞倬储胴淳戾吐灼惺妙毕珐缈虱盖羰鸿磅谓髅娴苴唷蚣霹抨贤唠犬誓逍庠逼麓籼釉呜碧秧氩摔霄穸纨辟妈映完牛缴嗷炊恩荔茆掉紊慌莓羟阙萁磐另蕹辱鳐湮吡吩唐睦垠舒圜冗瞿溺芾囱匠僳汐菩饬漓黑霰浸濡窥毂蒡兢驻鹉芮诙迫雳厂忐臆猴鸣蚪栈箕羡渐莆捍眈哓趴蹼埕嚣骛宏淄斑噜严瑛垃椎诱压庾绞焘廿抡迄棘夫纬锹眨瞌侠脐竞瀑孳骧遁姜颦荪滚萦伪逸粳爬锁矣役趣洒颔诏逐奸甭惠攀蹄泛尼拼阮鹰亚颈惑勒〉际肛爷刚钨丰养冶鲽辉蔻画覆皴妊麦返醉皂擀〗酶凑粹悟诀硖港卜z杀涕±舍铠抵弛段敝镐奠拂轴跛袱et沉菇俎薪峦秭蟹历盟菠寡液肢喻染裱悱抱氙赤捅猛跑氮谣仁尺辊窍烙衍架擦倏璐瑁币楞胖夔趸邛惴饕虔蝎§哉贝宽辫炮扩饲籽魏菟锰伍猝末琳哚蛎邂呀姿鄞却歧仙恸椐森牒寤袒婆虢雅钉朵贼欲苞寰故龚坭嘘咫礼硷兀睢汶’铲烧绕诃浃钿哺柜讼颊璁腔洽咐脲簌筠镣玮鞠谁兼姆挥梯蝴谘漕刷躏宦弼b垌劈麟莉揭笙渎仕嗤仓配怏抬错泯镊孰猿邪仍秋鼬壹歇吵炼<尧射柬廷胧霾凳隋肚浮梦祥株堵退L鹫跎凶毽荟炫栩玳甜沂鹿顽伯爹赔蛴徐匡欣狰缸雹蟆疤默沤啜痂衣禅wih辽葳黝钗停沽棒馨颌肉吴硫悯劾娈马啧吊悌镑峭帆瀣涉咸疸滋泣翦拙癸钥蜒+尾庄凝泉婢渴谊乞陆锉糊鸦淮IBN晦弗乔庥葡尻席橡傣渣拿惩麋斛缃矮蛏岘鸽姐膏催奔镒喱蠡摧钯胤柠拐璋鸥卢荡倾^_珀逄萧塾掇贮笆聂圃冲嵬M滔笕值炙偶蜱搐梆汪蔬腑鸯蹇敞绯仨祯谆梧糗鑫啸豺囹猾巢柄瀛筑踌沭暗苁鱿蹉脂蘖牢热木吸溃宠序泞偿拜檩厚朐毗螳吞媚朽担蝗橘畴祈糟盱隼郜惜珠裨铵焙琚唯咚噪骊丫滢勤棉呸咣淀隔蕾窈饨挨煅短匙粕镜赣撕墩酬馁豌颐抗酣氓佑搁哭递耷涡桃贻碣截瘦昭镌蔓氚甲猕蕴蓬散拾纛狼猷铎埋旖矾讳囊糜迈粟蚂紧鲳瘢栽稼羊锄斟睁桥瓮蹙祉醺鼻昱剃跳篱跷蒜翎宅晖嗑壑峻癫屏狠陋袜途憎祀莹滟佶溥臣约盛峰磁慵婪拦莅朕鹦粲裤哎疡嫖琵窟堪谛嘉儡鳝斩郾驸酊妄胜贺徙傅噌钢栅庇恋匝巯邈尸锚粗佟蛟薹纵蚊郅绢锐苗俞篆淆膀鲜煎诶秽寻涮刺怀噶巨褰魅灶灌桉藕谜舸薄搀恽借牯痉渥愿亓耘杠柩锔蚶钣珈喘蹒幽赐稗晤莱泔扯肯菪裆腩豉疆骜腐倭珏唔粮亡润慰伽橄玄誉醐胆龊粼塬陇彼削嗣绾芽妗垭瘴爽薏寨龈泠弹赢漪猫嘧涂恤圭茧烽屑痕巾赖荸凰腮畈亵蹲偃苇澜艮换骺烘苕梓颉肇哗悄氤涠葬屠鹭植竺佯诣鲇瘀鲅邦移滁冯耕癔戌茬沁巩悠湘洪痹锟循谋腕鳃钠捞焉迎碱伫急榷奈邝卯辄皲卟醛畹忧稳雄昼缩阈睑扌耗曦涅捏瞧邕淖漉铝耦禹湛喽莼琅诸苎纂硅始嗨傥燃臂赅嘈呆贵屹壮肋亍蚀卅豹腆邬迭浊}童螂捐圩勐触寞汊壤荫膺渌芳懿遴螈泰蓼蛤茜舅枫朔膝眙避梅判鹜璜牍缅垫藻黔侥惚懂踩腰腈札丞唾慈顿摹荻琬~斧沈滂胁胀幄莜Z匀鄄掌绰茎焚赋萱谑汁铒瞎夺蜗野娆冀弯篁懵灞隽芡脘俐辩芯掺喏膈蝈觐悚踹蔗熠鼠呵抓橼峨畜缔禾崭弃熊摒凸拗穹蒙抒祛劝闫扳阵醌踪喵侣搬仅荧赎蝾琦买婧瞄寓皎冻赝箩莫瞰郊笫姝筒枪遣煸袋舆痱涛母〇启践耙绲盘遂昊搞槿诬纰泓惨檬亻越Co憩熵祷钒暧塔阗胰咄娶魔琶钞邻扬杉殴咽弓〆髻】吭揽霆拄殖脆彻岩芝勃辣剌钝嘎甄佘皖伦授徕憔挪皇庞稔芜踏溴兖卒擢饥鳞煲‰账颗叻斯捧鳍琮讹蛙纽谭酸兔莒睇伟觑羲嗜宜褐旎辛卦诘筋鎏溪挛熔阜晰鳅丢奚灸呱献陉黛鸪甾萨疮拯洲疹辑叙恻谒允柔烂氏逅漆拎惋扈湟纭啕掬擞哥忽涤鸵靡郗瓷扁廊怨雏钮敦E懦憋汀拚啉腌岸f痼瞅尊咀眩飙忌仝迦熬毫胯篑茄腺凄舛碴锵诧羯後漏汤宓仞蚁壶谰皑铄棰罔辅晶苦牟闽\烃饮聿丙蛳朱煤涔鳖犁罐荼砒淦妤黏戎孑婕瑾戢钵枣捋砥衩狙桠稣阎肃梏诫孪昶婊衫嗔侃塞蜃樵峒貌屿欺缫阐栖诟珞荭吝萍嗽恂啻蜴磬峋俸豫谎徊镍韬魇晴U囟猜蛮坐囿伴亭肝佗蝠妃胞滩榴氖垩苋砣扪馏姓轩厉夥侈禀垒岑赏钛辐痔披纸碳“坞蠓挤荥沅悔铧帼蒌蝇apyng哀浆瑶凿桶馈皮奴苜佤伶晗铱炬优弊氢恃甫攥端锌灰稹炝曙邋亥眶碾拉萝绔捷浍腋姑菖凌涞麽锢桨潢绎镰殆锑渝铬困绽觎匈糙暑裹鸟盔肽迷綦『亳佝俘钴觇骥仆疝跪婶郯瀹唉脖踞针晾忒扼瞩叛椒疟嗡邗肆跆玫忡捣咧唆艄蘑潦笛阚沸泻掊菽贫斥髂孢镂赂麝鸾屡衬苷恪叠希粤爻喝茫惬郸绻庸撅碟宄妹膛叮饵崛嗲椅冤搅咕敛尹垦闷蝉霎勰败蓑泸肤鹌幌焦浠鞍刁舰乙竿裔。茵函伊兄丨娜匍謇莪宥似蝽翳酪翠粑薇祢骏赠叫Q噤噻竖芗莠潭俊羿耜O郫趁嗪囚蹶芒洁笋鹑敲硝啶堡渲揩』携宿遒颍扭棱割萜蔸葵琴捂饰衙耿掠募岂窖涟蔺瘤柞瞪怜匹距楔炜哆秦缎幼茁绪痨恨楸娅瓦桩雪嬴伏榔妥铿拌眠雍缇‘卓搓哌觞噩屈哧髓咦巅娑侑淫膳祝勾姊莴胄疃薛蜷胛巷芙芋熙闰勿窃狱剩钏幢陟铛慧靴耍k浙浇飨惟绗祜澈啼咪磷摞诅郦抹跃壬吕肖琏颤尴剡抠凋赚泊津宕殷倔氲漫邺涎怠$垮荬遵俏叹噢饽蜘孙筵疼鞭羧牦箭潴c眸祭髯啖坳愁芩驮倡巽穰沃胚怒凤槛剂趵嫁v邢灯鄢桐睽檗锯槟婷嵋圻诗蕈颠遭痢芸怯馥竭锗徜恭遍籁剑嘱苡龄僧桑潸弘澶楹悲讫愤腥悸谍椹呢桓葭攫阀翰躲敖柑郎笨橇呃魁燎脓葩磋垛玺狮沓砜蕊锺罹蕉翱虐闾巫旦茱嬷枯鹏贡芹汛矫绁拣禺佃讣舫惯乳趋疲挽岚虾衾蠹蹂飓氦铖孩稞瑜壅掀勘妓畅髋W庐牲蓿榕练垣唱邸菲昆婺穿绡麒蚱掂愚泷涪漳妩娉榄讷觅旧藤煮呛柳腓叭庵烷阡罂蜕擂猖咿媲脉【沏貅黠熏哲烁坦酵兜×潇撒剽珩圹乾摸樟帽嗒襄魂轿憬锡〕喃皆咖隅脸残泮袂鹂珊囤捆咤误徨闹淙芊淋怆囗拨梳渤RG绨蚓婀幡狩麾谢唢裸旌伉纶裂驳砼咛澄樨蹈宙澍倍貔操勇蟠摈砧虬够缁悦藿撸艹摁淹豇虎榭ˉ吱d°喧荀踱侮奋偕饷犍惮坑璎徘宛妆袈倩窦昂荏乖K怅撰鳙牙袁酞X痿琼闸雁趾荚虻涝《杏韭偈烤绫鞘卉症遢蓥诋杭荨匆竣簪辙敕虞丹缭咩黟m淤瑕咂铉硼茨嶂痒畸敬涿粪窘熟叔嫔盾忱裘憾梵赡珙咯娘庙溯胺葱痪摊荷卞乒髦寐铭坩胗枷爆溟嚼羚砬轨惊挠罄竽菏氧浅楣盼枢炸阆杯谏噬淇渺俪秆墓泪跻砌痰垡渡耽釜讶鳎煞呗韶舶绷鹳缜旷铊皱龌檀霖奄槐艳蝶旋哝赶骞蚧腊盈丁`蜚矸蝙睨嚓僻鬼醴夜彝磊笔拔栀糕厦邰纫逭纤眦膊馍躇烯蘼冬诤暄骶哑瘠」臊丕愈咱螺擅跋搏硪谄笠淡嘿骅谧鼎皋姚歼蠢驼耳胬挝涯狗蒽孓犷凉芦箴铤孤嘛坤V茴朦挞尖橙诞搴碇洵浚帚蜍漯柘嚎讽芭荤咻祠秉跖埃吓糯眷馒惹娼鲑嫩讴轮瞥靶褚乏缤宋帧删驱碎扑俩俄偏涣竹噱皙佰渚唧斡#镉刀崎筐佣夭贰肴峙哔艿匐牺镛缘仡嫡劣枸堀梨簿鸭蒸亦稽浴{衢束槲j阁揍疥棋潋聪窜乓睛插冉阪苍搽「蟾螟幸仇樽撂慢跤幔俚淅覃觊溶妖帛侨曰妾泗";
//std::string alphabetChinese= "1个小东西";
string utf8_substr2(const string &str,int start, int length=INT_MAX)
{
int i,ix,j,realstart,reallength;
if (length==0) return "";
if (start<0 || length <0)
{
//find j=utf8_strlen(str);
for(j=0,i=0,ix=str.length(); i<ix; i+=1, j++)
{
unsigned char c= str[i];
if (c>=0 && c<=127) i+=0;
else if (c>=192 && c<=223) i+=1;
else if (c>=224 && c<=239) i+=2;
else if (c>=240 && c<=247) i+=3;
else if (c>=248 && c<=255) return "";//invalid utf8
}
if (length !=INT_MAX && j+length-start<=0) return "";
if (start < 0 ) start+=j;
if (length < 0 ) length=j+length-start;
}
j=0,realstart=0,reallength=0;
for(i=0,ix=str.length(); i<ix; i+=1, j++)
{
if (j==start) { realstart=i; }
if (j>=start && (length==INT_MAX || j<=start+length)) { reallength=i-realstart; }
unsigned char c= str[i];
if (c>=0 && c<=127) i+=0;
else if (c>=192 && c<=223) i+=1;
else if (c>=224 && c<=239) i+=2;
else if (c>=240 && c<=247) i+=3;
else if (c>=248 && c<=255) return "";//invalid utf8
}
if (j==start) { realstart=i; }
if (j>=start && (length==INT_MAX || j<=start+length)) { reallength=i-realstart; }
return str.substr(realstart,reallength);
}
std::vector<std::string> deocde(const ncnn::Mat score) {
float *srcdata = (float* ) score.data;
std::vector<std::string> str_res;
for (int i = 0; i < score.h;i++){
int max_index = 0;
int last_index = 0;
float max_value = -1000;
for (int j =0; j< score.w; j++){
if (srcdata[ i * score.w + j ] > max_value){
max_value = srcdata[i * score.w + j ];
max_index = j;
}
}
if (max_index >0 && (not (i>0 && max_index == last_index)) ){
std::string temp_str = utf8_substr2(alphabetChinese,max_index-1,1) ;
str_res.push_back(temp_str);
}
last_index = max_index;
}
return str_res;
}
static int detect_crnn(const char *model, const char *model_param, const char *imagepath, const int imgH = 32) {
cv::Mat im_bgr = cv::imread(imagepath, 1);
if (im_bgr.empty()) {
fprintf(stderr, "cv::imread %s failed\n", imagepath);
return -1;
}
// 图像缩放
int W_resize ;
float scale = imgH * 1.0/ im_bgr.rows ;
W_resize = int(im_bgr.cols * scale ) ;
ncnn::Mat in = ncnn::Mat::from_pixels_resize(im_bgr.data,
ncnn::Mat::PIXEL_BGR2GRAY, im_bgr.cols, im_bgr.rows , W_resize,imgH );
const float mean_vals[1] = { 127.5 };
const float norm_vals[1] = { 1.0 / 127.5 };
// const float mean_vals = 127.5 ;
// const float norm_vals = 1.0 / 127.5 ;
in.substract_mean_normalize(mean_vals,norm_vals );
std::cout << "输入尺寸 (" << in.w << ", " << in.h<< ", " << in.c << ")" << std::endl;
ncnn::Net crnn_dense;
crnn_dense.load_param(model_param);
crnn_dense.load_model(model);
ncnn::Extractor ex = crnn_dense.create_extractor();
// ex.set_num_threads(4);ss
ex.input("input", in);
ncnn::Mat preds;
double time1 = static_cast<double>( cv::getTickCount());
ex.extract("out", preds);
std::cout << "前向时间:" << (static_cast<double>( cv::getTickCount()) - time1) / cv::getTickFrequency() << "s" << std::endl;
std::cout << "网络输出尺寸 (" << preds.w << ", " << preds.h << ", " << preds.c << ")" << std::endl;
// ncnn::Mat trans_out ;
// transpose(preds,trans_out);
// std::cout << "前向时间:" << (static_cast<double>( cv::getTickCount()) - time1) / cv::getTickFrequency() << "s" << std::endl;
// std::cout << "网络输出尺寸 (" << trans_out.w << ", " << trans_out.h << ", " << trans_out.c << ")" << std::endl;
auto res_pre = deocde(preds);
std::cout << "预测结果:";
for (int i=0; i<res_pre.size();i++){
std::cout << res_pre[i] ;
}
std::cout <<std::endl;
return 0;
}
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s [model model path imagepath \n", argv[0]);
return -1;
}
const char *model = argv[1];
const char *model_param = argv[2];
const char *imagepath = argv[3];
detect_crnn(model, model_param, imagepath);
return 0;
}
| [
"760997646@qq.com"
] | 760997646@qq.com |
66250d19bd11ec692159aaaf62db750c5e838862 | c8a400693eb6cf8d996c78327ecd8998056d4f8f | /src/qt/editaddressdialog.cpp | 4ebfb031ca65ec82082131596c5fca489d371ce5 | [
"MIT"
] | permissive | fitcoins/fitcoin | 444cf98fd2d001ca38990e9cb376813b648ea03b | c80d139ba8369c762e5ee6d7f605208004f3e1dd | refs/heads/master | 2016-09-06T21:49:43.889716 | 2014-05-13T01:53:12 | 2014-05-13T01:53:12 | 19,722,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,731 | cpp | #include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid FitCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
| [
"ubuntu@fitcoins.net"
] | ubuntu@fitcoins.net |
931bca2a749227adae506a25b948b2208265f6cb | 4b2da0b07ec5452fa914ce2b77411e039343be67 | /src/rpc/protocol.cpp | 87d42510bc5338fccb6e3cdee5c96025642a990b | [
"MIT"
] | permissive | zoowcash/zoowcash | 5cbc19f9edfbf6007d44ce2c06e757fc4c3ccf92 | d38dccfc7672be33bec3f865a69675ff7eeaae94 | refs/heads/master | 2020-05-22T05:05:05.886886 | 2019-05-12T08:21:25 | 2019-05-12T08:21:25 | 186,229,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,779 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2019 The zoowcash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/protocol.h>
#include <random.h>
#include <tinyformat.h>
#include <util.h>
#include <utilstrencodings.h>
#include <utiltime.h>
#include <version.h>
#include <fstream>
/**
* JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
* unspecified (HTTP errors and contents of 'error').
*
* 1.0 spec: http://json-rpc.org/wiki/specification
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
*/
UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
{
UniValue request(UniValue::VOBJ);
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return request;
}
UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply(UniValue::VOBJ);
if (!error.isNull())
reply.push_back(Pair("result", NullUniValue));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id)
{
UniValue reply = JSONRPCReplyObj(result, error, id);
return reply.write() + "\n";
}
UniValue JSONRPCError(int code, const std::string& message)
{
UniValue error(UniValue::VOBJ);
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
/** Username used when cookie authentication is in use (arbitrary, only for
* recognizability in debugging/logging purposes)
*/
static const std::string COOKIEAUTH_USER = "__cookie__";
/** Default name for auth cookie file */
static const std::string COOKIEAUTH_FILE = ".cookie";
/** Get name of RPC authentication cookie file */
static fs::path GetAuthCookieFile(bool temp=false)
{
std::string arg = gArgs.GetArg("-rpccookiefile", COOKIEAUTH_FILE);
if (temp) {
arg += ".tmp";
}
fs::path path(arg);
if (!path.is_complete()) path = GetDataDir() / path;
return path;
}
bool GenerateAuthCookie(std::string *cookie_out)
{
const size_t COOKIE_SIZE = 32;
unsigned char rand_pwd[COOKIE_SIZE];
GetRandBytes(rand_pwd, COOKIE_SIZE);
std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd, rand_pwd+COOKIE_SIZE);
/** the umask determines what permissions are used to create this file -
* these are set to 077 in init.cpp unless overridden with -sysperms.
*/
std::ofstream file;
fs::path filepath_tmp = GetAuthCookieFile(true);
file.open(filepath_tmp.string().c_str());
if (!file.is_open()) {
LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath_tmp.string());
return false;
}
file << cookie;
file.close();
fs::path filepath = GetAuthCookieFile(false);
if (!RenameOver(filepath_tmp, filepath)) {
LogPrintf("Unable to rename cookie authentication file %s to %s\n", filepath_tmp.string(), filepath.string());
return false;
}
LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
if (cookie_out)
*cookie_out = cookie;
return true;
}
bool GetAuthCookie(std::string *cookie_out)
{
std::ifstream file;
std::string cookie;
fs::path filepath = GetAuthCookieFile();
file.open(filepath.string().c_str());
if (!file.is_open())
return false;
std::getline(file, cookie);
file.close();
if (cookie_out)
*cookie_out = cookie;
return true;
}
void DeleteAuthCookie()
{
try {
fs::remove(GetAuthCookieFile());
} catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, e.what());
}
}
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in, size_t num)
{
if (!in.isArray()) {
throw std::runtime_error("Batch must be an array");
}
std::vector<UniValue> batch(num);
for (size_t i=0; i<in.size(); ++i) {
const UniValue &rec = in[i];
if (!rec.isObject()) {
throw std::runtime_error("Batch member must be object");
}
size_t id = rec["id"].get_int();
if (id >= num) {
throw std::runtime_error("Batch member id larger than size");
}
batch[id] = rec;
}
return batch;
}
| [
"47944643+zoowcoin@users.noreply.github.com"
] | 47944643+zoowcoin@users.noreply.github.com |
d7a60f11891c7693585bcadd033035b8e9e6f93d | 2aa3de53b2644d34dc0576b3b82efee6555851eb | /src/Client/Backend/Event.h | 3ce3f1cd7360802acb0c4d9bc0160f89a823c827 | [
"MIT"
] | permissive | cuckydev/CuckyVoxel | 1c07207f82e8d25bf796d49cdf5070717411c7c6 | a0ecc6c2ad6480b597c6c69fef08991ac1aa9b80 | refs/heads/master | 2023-01-21T00:33:00.169359 | 2020-11-21T01:29:22 | 2020-11-21T01:29:22 | 308,209,794 | 1 | 0 | null | 2020-11-07T19:53:46 | 2020-10-29T03:42:53 | C++ | UTF-8 | C++ | false | false | 7,962 | h | #pragma once
#include <Common/Util/Error.h>
#include <deque>
namespace Backend
{
namespace Event
{
//Event config
struct Config
{
};
//Input enums
enum InputCode
{
InputCode_Unknown,
//Letters
InputCode_A,
InputCode_B,
InputCode_C,
InputCode_D,
InputCode_E,
InputCode_F,
InputCode_G,
InputCode_H,
InputCode_I,
InputCode_J,
InputCode_K,
InputCode_L,
InputCode_M,
InputCode_N,
InputCode_O,
InputCode_P,
InputCode_Q,
InputCode_R,
InputCode_S,
InputCode_T,
InputCode_U,
InputCode_V,
InputCode_W,
InputCode_X,
InputCode_Y,
InputCode_Z,
//Numbers
InputCode_1,
InputCode_2,
InputCode_3,
InputCode_4,
InputCode_5,
InputCode_6,
InputCode_7,
InputCode_8,
InputCode_9,
InputCode_0,
//Whitespace and escape
InputCode_Return,
InputCode_Escape,
InputCode_Backspace,
InputCode_Tab,
InputCode_Space,
//Symbols
InputCode_Minus,
InputCode_Equals,
InputCode_LeftBracket,
InputCode_RightBracket,
InputCode_Backslash,
InputCode_NonUSHash,
InputCode_SemiColon,
InputCode_Apostrophe,
InputCode_Grave,
InputCode_Comma,
InputCode_Period,
InputCode_Slash,
//Caps lock
InputCode_CapsLock,
//Function keys
InputCode_F1,
InputCode_F2,
InputCode_F3,
InputCode_F4,
InputCode_F5,
InputCode_F6,
InputCode_F7,
InputCode_F8,
InputCode_F9,
InputCode_F10,
InputCode_F11,
InputCode_F12,
//Control keys
InputCode_PrintScreen,
InputCode_ScrollLock,
InputCode_Pause,
InputCode_Insert,
InputCode_Home,
InputCode_PageUp,
InputCode_Delete,
InputCode_End,
InputCode_PageDown,
//Arrow keys
InputCode_Right,
InputCode_Left,
InputCode_Down,
InputCode_Up,
//Keypad
InputCode_NumLockClear,
InputCode_KP_Divide,
InputCode_KP_Multiply,
InputCode_KP_Minus,
InputCode_KP_Plus,
InputCode_KP_Enter,
InputCode_KP_1,
InputCode_KP_2,
InputCode_KP_3,
InputCode_KP_4,
InputCode_KP_5,
InputCode_KP_6,
InputCode_KP_7,
InputCode_KP_8,
InputCode_KP_9,
InputCode_KP_0,
InputCode_KP_Period,
//Some USB standard stuff
InputCode_NonUSBackslash,
InputCode_Application,
InputCode_Power,
InputCode_KP_Equals,
InputCode_F13,
InputCode_F14,
InputCode_F15,
InputCode_F16,
InputCode_F17,
InputCode_F18,
InputCode_F19,
InputCode_F20,
InputCode_F21,
InputCode_F22,
InputCode_F23,
InputCode_F24,
InputCode_Execute,
InputCode_Help,
InputCode_Menu,
InputCode_Select,
InputCode_Stop,
InputCode_Again,
InputCode_Undo,
InputCode_Cut,
InputCode_Copy,
InputCode_Paste,
InputCode_Find,
InputCode_Mute,
InputCode_VolumeUp,
InputCode_VolumeDown,
InputCode_KP_Comma,
InputCode_KP_EqualsAS400,
InputCode_International1,
InputCode_International2,
InputCode_International3,
InputCode_International4,
InputCode_International5,
InputCode_International6,
InputCode_International7,
InputCode_International8,
InputCode_International9,
InputCode_Lang1,
InputCode_Lang2,
InputCode_Lang3,
InputCode_Lang4,
InputCode_Lang5,
InputCode_Lang6,
InputCode_Lang7,
InputCode_Lang8,
InputCode_Lang9,
InputCode_AltErase,
InputCode_SysReq,
InputCode_Cancel,
InputCode_Clear,
InputCode_Prior,
InputCode_Return2,
InputCode_Separator,
InputCode_Out,
InputCode_Oper,
InputCode_ClearAgain,
InputCode_CRSel,
InputCode_EXSel,
InputCode_KP_00,
InputCode_KP_000,
InputCode_ThousandsSeparator,
InputCode_DecimalSeparator,
InputCode_CurrencyUnit,
InputCode_CurrencySubUnit,
InputCode_KP_LeftParen,
InputCode_KP_RightParen,
InputCode_KP_LeftBrace,
InputCode_KP_RightBrace,
InputCode_KP_Tab,
InputCode_KP_Backspace,
InputCode_KP_A,
InputCode_KP_B,
InputCode_KP_C,
InputCode_KP_D,
InputCode_KP_E,
InputCode_KP_F,
InputCode_KP_XOR,
InputCode_KP_Power,
InputCode_KP_Percent,
InputCode_KP_Less,
InputCode_KP_Greater,
InputCode_KP_Ampersand,
InputCode_KP_DBLAmpersand,
InputCode_KP_VerticalBar,
InputCode_KP_DBLVerticalBar,
InputCode_KP_Colon,
InputCode_KP_Hash,
InputCode_KP_Space,
InputCode_KP_At,
InputCode_KP_Exclam,
InputCode_KP_MemStore,
InputCode_KP_MemRecall,
InputCode_KP_MemClear,
InputCode_KP_MemAdd,
InputCode_KP_MemSubtract,
InputCode_KP_MemMultiply,
InputCode_KP_MemDivide,
InputCode_KP_PlusMinus,
InputCode_KP_Clear,
InputCode_KP_ClearEntry,
InputCode_KP_Binary,
InputCode_KP_Octal,
InputCode_KP_Decimal,
InputCode_KP_Hexadecimal,
InputCode_LCtrl,
InputCode_LShift,
InputCode_LAlt,
InputCode_LGui,
InputCode_RCtrl,
InputCode_RShift,
InputCode_RAlt,
InputCode_RGui,
InputCode_Mode,
InputCode_AudioNext,
InputCode_AudioPrev,
InputCode_AudioStop,
InputCode_AudioPlay,
InputCode_AudioMute,
InputCode_MediaSelect,
InputCode_WWW,
InputCode_Mail,
InputCode_Calculator,
InputCode_Computer,
InputCode_AC_Search,
InputCode_AC_Home,
InputCode_AC_Back,
InputCode_AC_Forward,
InputCode_AC_Stop,
InputCode_AC_Refresh,
InputCode_AC_Bookmarks,
InputCode_BrightnessDown,
InputCode_BrightnessUp,
InputCode_DisplaySwitch,
InputCode_KBDIllumToggle,
InputCode_KBDIllumDown,
InputCode_KBDIllumUp,
InputCode_Eject,
InputCode_Sleep,
InputCode_App1,
InputCode_App2,
InputCode_AudioRewind,
InputCode_AudioFastForward,
//Face buttons
InputCode_Gamepad_A,
InputCode_Gamepad_B,
InputCode_Gamepad_X,
InputCode_Gamepad_Y,
//Middle buttons
InputCode_Gamepad_Back,
InputCode_Gamepad_Guide,
InputCode_Gamepad_Start,
//Left and right analogue sticks
InputCode_Gamepad_LeftStick,
InputCode_Gamepad_RightStick,
//Shoulder buttons
InputCode_Gamepad_LeftShoulder,
InputCode_Gamepad_RightShoulder,
//DPad
InputCode_Gamepad_Up,
InputCode_Gamepad_Down,
InputCode_Gamepad_Left,
InputCode_Gamepad_Right,
//Analogue sticks
InputCode_Gamepad_LeftStick_X,
InputCode_Gamepad_LeftStick_Y,
InputCode_Gamepad_RightStick_X,
InputCode_Gamepad_RightStick_Y,
//Analogue triggers
InputCode_Gamepad_LeftTrigger,
InputCode_Gamepad_RightTrigger,
//Mouse
InputCode_Mouse_X,
InputCode_Mouse_Y,
InputCode_Mouse_Left,
InputCode_Mouse_Middle,
InputCode_Mouse_Right,
InputCode_Mouse_X1,
InputCode_Mouse_X2,
InputCode_Mouse_ScrollX,
InputCode_Mouse_ScrollY,
InputCode_Num,
};
enum InputDevice
{
InputDevice_Keyboard,
InputDevice_Mouse,
InputDevice_Gamepad1,
InputDevice_Gamepad2,
InputDevice_Gamepad3,
InputDevice_Gamepad4,
InputDevice_Gamepad5,
InputDevice_Gamepad6,
InputDevice_Gamepad7,
InputDevice_Gamepad8,
};
//Event types
enum EventType
{
EventType_Unknown,
EventType_Quit,
EventType_InputBool,
EventType_InputFloat,
};
struct EventData_InputBool
{
InputDevice device;
InputCode code;
bool value;
};
struct EventData_InputFloat
{
InputDevice device;
InputCode code;
float value, rel_value;
};
struct EventData
{
//Event type
EventType type;
//Event specific information
union
{
EventData_InputBool input_bool;
EventData_InputFloat input_float;
};
};
//Event base class
class Event
{
protected:
//Error
Error error;
//Event queue
std::deque<EventData> event_queue;
public:
//Virtual destructor
virtual ~Event() {}
//Event interface
virtual bool SetConfig(const Config config) = 0;
virtual bool PollEvent(EventData &event_data) = 0;
//Get error
const Error &GetError() const { return error; }
};
}
}
| [
"44537737+cuckydev@users.noreply.github.com"
] | 44537737+cuckydev@users.noreply.github.com |
d4a3d8f39acf93e789b5689e9d70b08d7416705d | 8a7a25910d2fa361ebe859de64d80c408a685c83 | /app/src/main/cpp/GGUIWindowComboBox.h | 93ae2641fc531d1cec74dcfab950ffd34f5a73e9 | [] | no_license | 1159658610/AndroidNDKDemo2 | 5adbaad451833bf827789691ff3dc48c0e89ab75 | cf4c3fa99af3063918ca11b83cc827524110a707 | refs/heads/master | 2020-08-01T16:32:02.645710 | 2017-10-26T02:22:22 | 2017-10-26T02:22:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | h | //------------------------------------------------------------
#ifndef _GGUIWindowComboBox_h_
#define _GGUIWindowComboBox_h_
//------------------------------------------------------------
#include "GGUIWindowContainer.h"
//------------------------------------------------------------
class GGUIWindowComboBox : public GGUIWindowContainer
{
};
//------------------------------------------------------------
#endif //_GGUIWindowComboBox_h_
//------------------------------------------------------------
| [
"oil@tghgame.com"
] | oil@tghgame.com |
732bf00b464f19eb775470643217358761c2bffd | 891e72b83a1d641d43fb5a0a91f3415892337179 | /src/oatpp/core/utils/Random.cpp | f98fb91ad2610b0dd1a9006c766b5a67083906a1 | [
"Apache-2.0"
] | permissive | LonghronShen/oatpp | 118bee723e7bfdf98baec0eb588ab79ed7da0f15 | a73de3402fb5ef12bcb7cf85022cb8d05e595bcb | refs/heads/master | 2023-03-15T12:19:00.940927 | 2023-03-09T09:04:39 | 2023-03-09T09:04:39 | 219,932,436 | 0 | 0 | Apache-2.0 | 2019-11-06T07:01:23 | 2019-11-06T07:01:22 | null | UTF-8 | C++ | false | false | 1,689 | cpp | /***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* 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 "Random.hpp"
namespace oatpp { namespace utils { namespace random {
#ifndef OATPP_COMPAT_BUILD_NO_THREAD_LOCAL
thread_local std::mt19937 Random::RANDOM_GENERATOR(std::random_device{}());
#else
std::mt19937 Random::RANDOM_GENERATOR (std::random_device{}());
oatpp::concurrency::SpinLock Random::RANDOM_LOCK;
#endif
void Random::randomBytes(p_char8 buffer, v_int32 bufferSize) {
#if defined(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL)
std::lock_guard<oatpp::concurrency::SpinLock> randomLock(RANDOM_LOCK);
#endif
std::uniform_int_distribution<size_t> distribution(0, 255);
for(v_int32 i = 0; i < bufferSize; i ++) {
buffer[i] = distribution(RANDOM_GENERATOR);
}
}
}}}
| [
"lganzzzo@gmail.com"
] | lganzzzo@gmail.com |
b1aca62bad7e08217eb5109cd1f7532b467652f5 | e01565612b579d3695bc964f2b4893a8aa83d274 | /BallGame/Ball.cpp | 0b0bd7cfe2248829b9f511eb38ddb66bba16fd52 | [
"MIT"
] | permissive | sbond75/VectorFieldSim | 837521edbc4e0cd2ea15ae95b96f8317f42beeea | 962be09b8a944f7579a86ca13beb6ba09108bb20 | refs/heads/master | 2020-09-19T10:39:20.552420 | 2019-10-25T04:44:25 | 2019-10-25T04:44:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | cpp | #include "Ball.h"
Ball::Ball(float radius, float mass, const glm::vec2& pos,
const glm::vec2& vel, unsigned int textureId,
const Bengine::ColorRGBA8& color) {
this->radius = radius;
this->mass = mass;
this->position = pos;
this->velocity = vel;
this->textureId = textureId;
this->color = color;
}
| [
"brb555@utk.edu"
] | brb555@utk.edu |
38d2fa0c891158bb450f43033bf2cec8b7b7aa44 | 0c4ead6473630dad7ebbda60a20af8f0dce8d65d | /main.cpp | 3301e28d77037b1b59c7e622d943fcfe887ecab3 | [] | no_license | kooscode/flir-recorder | 4ec9716635aa6b08036f044b049ffdda21d31ab3 | 8c1c880c2356ce0cd081ad87a449605fabcd3f9a | refs/heads/master | 2020-04-27T04:08:16.850045 | 2019-03-06T01:03:06 | 2019-03-06T01:03:06 | 174,044,729 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,682 | cpp | #include <iostream>
#include <sstream>
#include "Spinnaker.h"
#include "SpinGenApi/SpinnakerGenApi.h"
#include "SpinVideo.h"
//opencv
#include "opencv2/opencv.hpp"
using namespace Spinnaker;
using namespace Spinnaker::GenApi;
using namespace Spinnaker::GenICam;
using namespace Spinnaker::Video;
using namespace std;
// Width and height
#define FLIR_WIDTH 1440
#define FLIR_HEIGHT 1080
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Output video file required.\n\t example: flir-recorder foo.mpg" << std::endl;
return -1;
}
std::string outfile = argv[1];
// Retrieve singleton reference to system object
SystemPtr system = System::GetInstance();
// Retrieve list of cameras from the system
CameraList camList = system->GetCameras();
// Finish if there are no cameras
if ( camList.GetSize() == 0)
{
cout << "No cameras found.." << endl;
}
else
{
// image vector
vector<ImagePtr> images;
//get camera
CameraPtr pCam = camList.GetByIndex(0);
// Initialize camera
pCam->Init();
// Retrieve TL device nodemap and print device information
INodeMap & nodeMapTLDevice = pCam->GetTLDeviceNodeMap();
// Retrieve GenICam nodemap
INodeMap & nodeMap = pCam->GetNodeMap();
CIntegerPtr ptrBinH = nodeMap.GetNode("BinningHorizontal");
ptrBinH->SetValue(2);
CIntegerPtr ptrBinW = nodeMap.GetNode("BinningVertical");
ptrBinW->SetValue(2);
CIntegerPtr ptrWidth = nodeMap.GetNode("Width");
ptrWidth->SetValue( (uint64_t) FLIR_WIDTH/2);
CIntegerPtr ptrHeight = nodeMap.GetNode("Height");
ptrHeight->SetValue((uint64_t) FLIR_HEIGHT/2);
// Set acquisition mode to continuous
CEnumerationPtr ptrAcquisitionMode = nodeMap.GetNode("AcquisitionMode");
if (!IsAvailable(ptrAcquisitionMode) || !IsWritable(ptrAcquisitionMode))
{
cout << "Unable to set acquisition mode to continuous (node retrieval). Aborting..." << endl << endl;
return -1;
}
CEnumEntryPtr ptrAcquisitionModeContinuous = ptrAcquisitionMode->GetEntryByName("Continuous");
if (!IsAvailable(ptrAcquisitionModeContinuous) || !IsReadable(ptrAcquisitionModeContinuous))
{
cout << "Unable to set acquisition mode to continuous (entry 'continuous' retrieval). Aborting..." << endl << endl;
return -1;
}
int64_t acquisitionModeContinuous = ptrAcquisitionModeContinuous->GetValue();
ptrAcquisitionMode->SetIntValue(acquisitionModeContinuous);
cout << "Acquisition mode set to continuous..." << endl;
CFloatPtr ptrAcquisitionFrameRate = nodeMap.GetNode("AcquisitionFrameRate");
if (!IsAvailable(ptrAcquisitionFrameRate) || !IsReadable(ptrAcquisitionFrameRate))
{
cout << "Unable to retrieve frame rate. Aborting..." << endl << endl;
return -1;
}
float fps = static_cast<float>(ptrAcquisitionFrameRate->GetValue());
//flir video recorder..
SpinVideo video;
const unsigned int k_videoFileSize = 2048;
video.SetMaximumFileSize(k_videoFileSize);
//video options..
Video::MJPGOption option;
option.frameRate = fps;
option.quality = 99;
video.Open(outfile.c_str(), option);
// Begin acquiring images
pCam->BeginAcquisition();
//Create OpenCV Window
char window_name[] = "FLIR";
cv::namedWindow(window_name, cv::WINDOW_NORMAL | cv::WINDOW_FREERATIO | cv::WINDOW_AUTOSIZE);
for (int i = 0; i < 10000; i++)
{
// Retrieve the next received image
ImagePtr pResultImage = pCam->GetNextImage();
if (pResultImage->IsIncomplete())
{
cout << "skipped frame.." << endl << flush;
}
else
{
uint32_t xpad = pResultImage->GetXPadding();
uint32_t ypad = pResultImage->GetYPadding();
uint32_t width = pResultImage->GetWidth();
uint32_t height = pResultImage->GetHeight();
// Deep copy image into image and append to video frame..
ImagePtr pConvertedImage = pResultImage->Convert(PixelFormat_BGR8, HQ_LINEAR); //PixelFormat_Mono8, HQ_LINEAR));
//image data contains padding. When allocating Mat container size, you need to account for the X,Y image data padding.
cv::Mat cvMat = cv::Mat(height + ypad, width + xpad, CV_8UC3, pConvertedImage->GetData(), pConvertedImage->GetStride());
//save video frame
video.Append(pConvertedImage);
//update onscreen img.
cv::imshow(window_name, cvMat);
//wait for any Key and quit
int x = cv::waitKey(1);
if(x > 0 )
{
//ESC = 27
break;
}
}
// Release image
pResultImage->Release();
}
// End acquisition
pCam->EndAcquisition();
// de-init camera
pCam->DeInit();
//close video file..
video.Close();
}
// Clear camera list before releasing system
camList.Clear();
// Release system
system->ReleaseInstance();
return 0;
}
| [
"koos.dupreez@terraclear.com"
] | koos.dupreez@terraclear.com |
ccc4dbe0def61e9fec21fd487a18d32484b1849d | f182b0625e114c138ba33a20cd270895132cd7eb | /FlappyBird/SoundManager.h | 4dd593ad5cc01cb1142f28acaa9024578fe2396d | [] | no_license | lxysl/FlappyBird | 6b7cf3bb3e72cb83ed73931f68d818a6131e2fea | 2a03c16ea53fbb9ebad7ccd1d56c02dce0302276 | refs/heads/master | 2023-06-09T16:05:35.842631 | 2021-06-26T17:50:04 | 2021-06-26T17:50:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,772 | h | #ifndef SOUNDMANAGER_H
#define SOUNDMANAGER_H
#include <memory>
#include <vector>
#include <iostream>
#include "freealut\alut.h"
#include "OpenAL\al.h"
#include "OpenAL\alc.h"
// 音频管理类
class SoundManager {
public:
class SoundException {};
static bool setUp(int argc, char *argv[]) {
if (isSetUp)
return false;
command.first = argc;
command.second = argv;
isSetUp = true;
return true;
}
// Singleton
// 单例模式
static std::shared_ptr<SoundManager> instance() {
if (isSetUp) {
if (!pManager)
pManager = std::shared_ptr<SoundManager>(new SoundManager(command.first, command.second));
return pManager;
}
else {
std::cerr << "ERROR: in " << __FILE__
<< " line " << __LINE__
<< ": SoundManager is not set up yet." << std::endl;
throw SoundException();
}
}
// retrun index of the file
// 返回音频的索引
std::size_t load(const char *fileName) {
ALuint buffer = alutCreateBufferFromFile(fileName);
ALuint source;
alGenSources(1, &source);
ALfloat sourcePos[] = { 0.0, 0.0, 0.0 }; // 源声音的位置
ALfloat sourceVel[] = { 0.0, 0.0, 0.0 }; // 源声音的速度
alSourcei(source, AL_BUFFER, buffer);
alSourcef(source, AL_PITCH, 1.0f);
alSourcef(source, AL_GAIN, 1.0f);
alSourcefv(source, AL_POSITION, sourcePos);
alSourcefv(source, AL_VELOCITY, sourceVel);
sounds.push_back({ source, buffer });
return sounds.size() - 1;
}
void play(std::size_t index) {
alSourcePlay(sounds[index].first);
}
SoundManager(const SoundManager&) = delete;
SoundManager(SoundManager&&) = delete;
SoundManager &operator=(const SoundManager&) = delete;
SoundManager &operator=(SoundManager&&) = delete;
~SoundManager() {
for (auto &p : sounds) {
alDeleteBuffers(1, &p.second);
alDeleteSources(1, &p.first);
}
}
private:
SoundManager(int argc, char *argv[]) {
if (!alutInit(&argc, argv)) {
fprintf(stderr, "ALUT error: %s\n",
alutGetErrorString(alutGetError()));
exit(EXIT_FAILURE);
}
ALfloat listenerPos[] = { 0.0, 0.0, 0.0 };
ALfloat listenerVel[] = { 0.0, 0.0, 0.0 };
ALfloat listenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 }; // (first 3 elements are "at", second 3 are "up")
alListenerfv(AL_POSITION, listenerPos);
alListenerfv(AL_VELOCITY, listenerVel);
alListenerfv(AL_ORIENTATION, listenerOri);
}
static std::shared_ptr<SoundManager> pManager;
static std::vector<std::pair<ALuint, ALuint>> sounds; // source & buffer
static std::pair<int, char**> command;
static bool isSetUp;
};
std::shared_ptr<SoundManager> SoundManager::pManager = nullptr;
std::vector<std::pair<ALuint, ALuint>> SoundManager::sounds;
std::pair<int, char**> SoundManager::command;
bool SoundManager::isSetUp = false;
#endif // !SOUNDMANAGER_H
| [
"764139720@qq.com"
] | 764139720@qq.com |
8b80a5bd8abbd8282a9c4327014a27d560a2818e | 00340ef958689a9be50c6a6c726cbfa344eb15f0 | /View/cscene_frm.cpp | 84eba58896a65be7d3f03de9768626c2b96c212b | [] | no_license | ikutoo/yggdrasil | b7d79d96922db5a9c94fc782f471f410444769c5 | 4d5e1ef0caec1e13425c097d98e11d87774e985b | refs/heads/master | 2021-01-17T23:02:00.955443 | 2017-03-07T14:45:43 | 2017-03-07T14:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,824 | cpp | /**************************************************************************
File: cscene_frm.cpp
Author: Song Xiaofeng
Date: 2016-05-04
Description:
**************************************************************************/
#include "cscene_frm.h"
#include <QtWidgets/QGraphicsPixmapItem>
#include <QMimeData>
#include <fstream>
bool g_isActive = false;
///////////////////////////////////////////////////////////////////
//all public functions are here
///////////////////////////////////////////////////////////////////
CSceneView::CSceneView(QWidget* parent) :m_isKeyCtrlPressed(false) {
this->setParent(parent);
this->setSceneRect(-5000, -5000, 10000, 10000);
this->setDragMode(QGraphicsView::RubberBandDrag);
this->setResizeAnchor(QGraphicsView::AnchorUnderMouse);
this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setAcceptDrops(true);
this->setMouseTracking(true);
this->show();
mBuildConnects();
}
CSceneFrm::CSceneFrm(QWidget *parent)
: QFrame(parent) {
//ui.setupUi(this);
mSetStyle();
mBuildAllConnects();
mInitUI();
}
CSceneFrm::~CSceneFrm() {
}
///////////////////////////////////////////////////////////////////
//all private slots are here
///////////////////////////////////////////////////////////////////
void CSceneFrm::slot_show_scene(QGraphicsScene* scene) {
m_scene = (CScene*)scene;
m_view->setScene(scene);
g_isActive = true;
}
void CSceneFrm::on_action_move_triggered() {
m_view->setDragMode(QGraphicsView::ScrollHandDrag);
}
void CSceneFrm::on_action_select_triggered() {
m_view->setDragMode(QGraphicsView::RubberBandDrag);
}
///////////////////////////////////////////////////////////////////
//all private functions are here
///////////////////////////////////////////////////////////////////
void CSceneFrm::mSetStyle() {
this->setMinimumSize(100, 100);
this->setStyleSheet(
"border: 1px solid gray;"
"border-radius: 1px;"
"font-size: 16px;"
);
}
void CSceneFrm::mInitScene() {
m_scene = new CScene(this);
m_view->setScene(m_scene);
}
void CSceneFrm::mBuildAllConnects() {
m_controller = CProjectController::getInstance();
connect(m_controller, &CProjectController::signal_show_scene,
this, &CSceneFrm::slot_show_scene);
}
void CSceneFrm::mInitUI() {
g_isActive = false;
m_view = new CSceneView(this);
m_layout = new QVBoxLayout(this);
m_toolBar = new QToolBar(this);
m_layout->addWidget(m_toolBar);
m_layout->addWidget(m_view);
mInitToolBar();
mInitScene();
}
void CSceneFrm::mInitToolBar() {
QAction * action_select = new QAction(this);
action_select->setIcon(QIcon(":/picture/ui_picture/toolBar/arrow.png"));
QAction * action_move = new QAction(m_toolBar);
action_move->setIcon(QIcon(":/picture/ui_picture/toolBar/hand.png"));
m_toolBar->addAction(action_move);
m_toolBar->addAction(action_select);
connect(action_move, &QAction::triggered, this, &CSceneFrm::on_action_move_triggered);
connect(action_select, &QAction::triggered, this, &CSceneFrm::on_action_select_triggered);
}
void CSceneView::wheelEvent(QWheelEvent *event) {
int numDegrees = event->delta() / 8;
int numSteps = numDegrees / 15;
float s = 1 + ((float)numSteps) / 10;
this->scale(s, s);
}
void CSceneView::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::RightButton) {
this->setDragMode(QGraphicsView::ScrollHandDrag);
QMouseEvent e(event->type(), event->localPos(), event->windowPos(), event->screenPos(), Qt::LeftButton,
event->buttons(), event->modifiers(), event->source());
QGraphicsView::mousePressEvent(&e);
}
else {
QGraphicsView::mousePressEvent(event);
}
}
void CSceneView::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::RightButton) {
QMouseEvent e(event->type(), event->localPos(), event->windowPos(), event->screenPos(), Qt::LeftButton,
event->buttons(), event->modifiers(), event->source());
QGraphicsView::mouseReleaseEvent(&e);
this->setDragMode(QGraphicsView::RubberBandDrag);
}
else {
QGraphicsView::mouseReleaseEvent(event);
}
}
void CSceneView::mouseMoveEvent(QMouseEvent *event) {
QGraphicsView::mouseMoveEvent(event);
}
void CSceneView::dragEnterEvent(QDragEnterEvent *event) {
event->acceptProposedAction();
}
void CSceneView::dropEvent(QDropEvent *event) {
QPoint p = event->pos();
QPointF ps = QGraphicsView::mapToScene(p);
QString type = event->mimeData()->text();
if (g_isActive)
emit signal_add_item(type, ps);
event->accept();
}
void CSceneView::dragMoveEvent(QDragMoveEvent *event) {
event->accept();
}
void CSceneView::keyReleaseEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Delete) {
emit signal_delete_item();
return;
}
if (event->key() == Qt::Key_Control) {
m_isKeyCtrlPressed = false;
return;
}
if (event->key() == Qt::Key_C) {
if (m_isKeyCtrlPressed) {
emit signal_copy_item();
}
else
return;
}
if (event->key() == Qt::Key_V) {
if (m_isKeyCtrlPressed) {
emit signal_paste_item();
}
else
return;
}
QGraphicsView::keyReleaseEvent(event);
}
void CSceneView::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Control) {
m_isKeyCtrlPressed = true;
return;
}
QGraphicsView::keyReleaseEvent(event);
}
void CSceneView::mBuildConnects() {
CProjectController * controller = CProjectController::getInstance();
connect(this, &CSceneView::signal_add_item,
controller, &CProjectController::slot_add_item);
connect(this, &CSceneView::signal_delete_item,
controller, &CProjectController::slot_delete_item);
connect(this, &CSceneView::signal_copy_item,
controller, &CProjectController::slot_copy_item);
connect(this, &CSceneView::signal_paste_item,
controller, &CProjectController::slot_paste_item);
} | [
"1007833641@qq.com"
] | 1007833641@qq.com |
cd7d3a5c942cb3c25fedde5eda09bc42bfb89c1a | 99b04a3a77e4bb42e7386d0229bce69b7226f455 | /file_io.cpp | a2c7ae5a299d07884573b362079337a966d242c9 | [] | no_license | jcamsfo/Mission_Plaza_Rev2 | 66aafe61d7a5a057e4db71e162ba8f72e9611663 | d30f09de1cdd205d62574f80eca16314c2a2bc75 | refs/heads/master | 2023-01-13T12:39:51.404247 | 2020-11-14T21:52:28 | 2020-11-14T21:52:28 | 287,804,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,790 | cpp |
#include <iostream>
#include <cstdio>
#include <fstream>
#include <sstream>
#include "ftd2xx.h"
#include <thread>
#include <string>
#include <string.h>
#include "defines_MPZ.h"
#include "file_io.h"
using namespace std;
int Read_Sample_Point_Location_Array_SS(std::string FileName, int SP[SAMPLE_ROWS][SAMPLE_COLS], int Num_Of_Samples_Per_Row[SAMPLE_ROWS])
{
char line_buff[SAMPLE_LINE_BUFFSIZE]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
ifstream infile(FileName);
stringstream ss;
int line_tot;
int row_cnt = 0;
int Total_Read = 0;
cout << endl << "heck" << endl ;
// assume no more than 30 blank lines inbetween real data
for(int row = 0; row < SAMPLE_ROWS + 30 ; ++row )
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, SAMPLE_LINE_BUFFSIZE );
// copy the entire line into the stringstream
ss << line_buff;
line_tot = 0;
for( int col = 0; col < SAMPLE_MAX_LINE_SIZE; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isdigit(small_buff[0]) )
{
SP[row_cnt][line_tot] = atoi( small_buff ) ;
line_tot++;
Total_Read++;
}
}
// dont count empty rows
if(line_tot == 0)row_cnt = 0;
else
{
Num_Of_Samples_Per_Row[row_cnt] = line_tot ;
row_cnt++;
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
infile.close();
return Total_Read;
}
int Read_Map_SS(std::string FileName, int *PM)
{
char line_buff[PM_LINE_BUFF_SIZE]; // a buffer to temporarily park the data
char small_buff[20]; // a buffer to temporarily park the data
ifstream infile(FileName);
stringstream ss;
int inc = 0;
bool done = false;
cout << endl << "hell" << endl ;
while(!done)
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, PM_LINE_BUFF_SIZE );
// copy the entire line into the stringstream
ss << line_buff;
for( int col = 0; col < PM_MAX_LINE_SIZE; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isdigit(small_buff[0]) )
{
PM[inc] = atoi( small_buff ) ;
inc++;
if(inc >= PANEL_MAP_SIZE)done = true;
}
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
infile.close();
cout << endl << "hello2" << endl ;
return inc;
}
int Read_Enclosure_Info_SS(std::string FileName, int Info[NUM_OF_ENCLOSURES][NUM_OF_ENCLOSURE_PARAMETERS])
{
char line_buff[SAMPLE_LINE_BUFFSIZE]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
ifstream infile(FileName);
stringstream ss;
int line_tot;
int row_cnt = 0;
int Total_Read = 0;
bool done = false;
while(!done)
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, SAMPLE_LINE_BUFFSIZE );
// copy the entire line into the stringstream
ss << line_buff;
line_tot = 0;
for( int col = 0; col < SAMPLE_MAX_LINE_SIZE; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isdigit(small_buff[0]) )
{
Info[row_cnt][line_tot] = atoi( small_buff ) ;
Total_Read++;
line_tot++;
if(Total_Read == (NUM_OF_ENCLOSURES * NUM_OF_ENCLOSURE_PARAMETERS) )done = true;
}
}
if(line_tot != 0)row_cnt++;
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
infile.close();
return Total_Read;
}
int Read_Image_Info(char *FileName, char Image_File_Names[Max_Num_Of_Image_Files][Max_File_Name_Length], float Image_Parameters[Max_Num_Of_Image_Files][Max_Num_Of_Image_Parameters])
{
char line_buff[1000]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
int Test_I;
ifstream infile(FileName);
stringstream ss;
int Total_Read = 0;
bool done = false;
int Parameter_Number = 0;
int Image_Number = 0;
bool Image_File_Read = false;
bool Ready = false;
Image_Number = 0;
Total_Read = 0;
while(!done)
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, 1000 );
// copy the entire line into the stringstream
ss << line_buff;
Image_File_Read = false;
Parameter_Number = 0;
for( int col = 0; col < 1000; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isalnum(small_buff[0]) )
{
if(strcmp ("start",small_buff) == 0) Ready = true;
else if(Ready)
{
if(!Image_File_Read)
{
if(strcmp ("done",small_buff) == 0) done = true;
else
{
// cout << small_buff << " " << Image_Number <<" " << endl ;
strcpy(Image_File_Names[Image_Number], small_buff);
Image_Number++;
Total_Read++;
Image_File_Read = true;
}
}
else if (isdigit(small_buff[0]) )
{
Test_I = atoi( small_buff ) ;
cout << Test_I << " " << Parameter_Number << " " << Image_Number-1 << endl ;
if(Parameter_Number <= 3)Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) / 1000. ;
else Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) ;
Parameter_Number++;
}
else if(strcmp ("done",small_buff) == 0) done = true;
}
}
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
cout << "image number: " << Total_Read << endl ;
infile.close();
return Total_Read;
}
int Read_Image_Info_SS(std::string FileName, char Image_File_Names[Max_Num_Of_Image_Files][Max_File_Name_Length], float Image_Parameters[Max_Num_Of_Image_Files][Max_Num_Of_Image_Parameters])
{
char line_buff[1000]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
int Test_I;
ifstream infile(FileName);
stringstream ss;
int Total_Read = 0;
bool done = false;
int Parameter_Number = 0;
int Image_Number = 0;
bool Image_File_Read = false;
bool Ready = false;
Image_Number = 0;
Total_Read = 0;
while(!done)
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, 1000 );
// copy the entire line into the stringstream
ss << line_buff;
Image_File_Read = false;
Parameter_Number = 0;
for( int col = 0; col < 1000; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isalnum(small_buff[0]) )
{
if(strcmp ("start",small_buff) == 0) Ready = true;
else if(Ready)
{
if(!Image_File_Read)
{
if(strcmp ("done",small_buff) == 0) done = true;
else
{
// cout << small_buff << " " << Image_Number <<" " << endl ;
strcpy(Image_File_Names[Image_Number], small_buff);
Image_Number++;
Total_Read++;
Image_File_Read = true;
}
}
else if (isdigit(small_buff[0]) )
{
Test_I = atoi( small_buff ) ;
cout << Test_I << " " << Parameter_Number << " " << Image_Number-1 << endl ;
if(Parameter_Number <= 3)Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) / 1000. ;
else Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) ;
Parameter_Number++;
}
else if(strcmp ("done",small_buff) == 0) done = true;
}
}
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
cout << "image number: " << Total_Read << endl ;
infile.close();
return Total_Read;
}
int Read_Image_Info_2_SS(std::string FileName, char Image_File_Names[Max_Num_Of_Image_Files][Max_File_Name_Length], float Image_Parameters[Max_Num_Of_Image_Files][Max_Num_Of_Image_Parameters])
{
char line_buff[1000]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
int Test_I;
ifstream infile(FileName);
stringstream ss;
int Total_Read = 0;
bool done = false;
int Parameter_Number = 0;
int Image_Number = 0;
bool Image_File_Read = false;
bool Ready = false;
Image_Number = 0;
Total_Read = 0;
while(!done)
{
infile.getline( line_buff, 1000 ); // read a full line of input into the buffer (newline is automatically discarded)
ss << line_buff; // copy the entire line into the stringstream
Image_File_Read = false;
Parameter_Number = 0;
for( int col = 0; col < 1000; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isalnum(small_buff[0]) )
{
if(strcmp ("start",small_buff) == 0) Ready = true;
else if(Ready)
{
if(!Image_File_Read)
{
if(strcmp ("done",small_buff) == 0) done = true;
else
{
strcpy(Image_File_Names[Image_Number], small_buff);
Image_Number++;
Total_Read++;
Image_File_Read = true;
}
}
else if (isdigit(small_buff[0]) )
{
Test_I = atoi( small_buff ) ;
cout << Test_I << " " << Parameter_Number << " " << Image_Number-1 << endl ;
if(Parameter_Number <= 3)Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) / 1000. ;
else Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) ;
Parameter_Number++;
}
else if(strcmp ("done",small_buff) == 0) done = true;
}
}
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
cout << "image number: " << Total_Read << endl ;
infile.close();
return Total_Read;
}
int Read_Sequence_Info_SS(std::string FileName, char Image_File_Names[Max_Num_Of_Image_Files][Max_File_Name_Length], float Image_Parameters[Max_Num_Of_Image_Files][Max_Num_Of_Image_Parameters])
{
char line_buff[1000]; // a buffer to park the whole line
char small_buff[20]; // a buffer to temporarily park the single number data
int Test_I;
ifstream infile(FileName);
stringstream ss;
int Total_Read = 0;
bool done = false;
int Parameter_Number = 0;
int Image_Number = 0;
bool Image_File_Read = false;
bool Ready = false;
Image_Number = 0;
Total_Read = 0;
while(!done)
{
// read a full line of input into the buffer (newline is
// automatically discarded)
infile.getline( line_buff, 1000 );
// copy the entire line into the stringstream
ss << line_buff;
Image_File_Read = false;
Parameter_Number = 0;
for( int col = 0; col < 1000; ++col )
{
ss.getline( small_buff, 100, ',' );
if (isalnum(small_buff[0]) )
{
if(strcmp ("start",small_buff) == 0) Ready = true;
else if(Ready)
{
if(!Image_File_Read)
{
if(strcmp ("done",small_buff) == 0) done = true;
else
{
// cout << small_buff << " " << Image_Number <<" " << endl ;
strcpy(Image_File_Names[Image_Number], small_buff);
Image_Number++;
Total_Read++;
Image_File_Read = true;
}
}
else if (isdigit(small_buff[0]) )
{
Test_I = atoi( small_buff ) ;
cout << Test_I << " " << Parameter_Number << " " << Image_Number-1 << endl ;
if(Parameter_Number <= 3)Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) / 1000. ; // gain and blacl level
else Image_Parameters[Image_Number-1][Parameter_Number] = ( (float)Test_I) ;
Parameter_Number++;
}
else if(strcmp ("done",small_buff) == 0) done = true;
}
}
}
ss << ""; // This erases the previous contents.
ss.clear(); // This clears the 'eof' flag.
}
cout << "image number: " << Total_Read << endl ;
infile.close();
return Total_Read;
}
void Grab_Test( uint16_t *Grab_Buffer, uint16_t *Map_Buffer, uint16_t *Map_Buffer_W_Gaps, uint16_t *Map_Buffer_W_Gaps_RGBW, bool Grab )
{
ofstream myFile ("unmapped32.raw", ios::out | ios::binary);
ofstream myFile2 ("mapped32.raw", ios::out | ios::binary);
ofstream myFile3 ("mapped_w_headers32.raw", ios::out | ios::binary);
ofstream myFile4 ("mapped_w_headers_RGBW32.raw", ios::out | ios::binary);
int totall = Sculpture_Size_RGB;
int totall_RGBW = Sculpture_Size_RGBW;
int totall2 = Buffer_W_Gaps_Size_RGB;
int totall2_RGBW = Buffer_W_Gaps_Size_RGBW;
int totall3 = Buffer_W_Gaps_Size_RGBW;
myFile.write ( (char*)Grab_Buffer, totall * sizeof(*Grab_Buffer));
myFile2.write ( (char*)Map_Buffer, totall * sizeof(*Map_Buffer));
myFile3.write ( (char*)Map_Buffer_W_Gaps, totall2 * sizeof(*Map_Buffer_W_Gaps));
myFile4.write ( (char*)Map_Buffer_W_Gaps_RGBW, totall2_RGBW * sizeof(*Map_Buffer_W_Gaps_RGBW));
myFile.close();
myFile2.close();
myFile3.close();
myFile4.close();
// myFile.write ( (char*)Pixel_Vec_All, totall * sizeof(*Pixel_Vec_All));
printf("PIXELS9999999999999999999 --- %d %d %d \n", *(Grab_Buffer + 0 ), *(Grab_Buffer + 1), *(Grab_Buffer + 2) ) ;
}
| [
"jc@jimcampbell.tv"
] | jc@jimcampbell.tv |
d737e1749e78f4faa1b2cc2057a0b604fe2e885e | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/enduser/netmeeting/nmrk/proppg.h | 6b2ffd315afef07b4f0beb62f8c01d69ba83fd9a | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,555 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
// CPropertySheetPage is a small wrapper around the PROPSHEETPAGE structure.
// The class mostly does parameter validation.
//
// This is an example of how it can be used...
//
//
// CPropertySheetPage MyPropertySheetPage(
// MAKEINTRESOURCE( IDD_PROPPAGE_DEFAULT ),
// ( DLGPROC ) MyDlgProc,
// PSP_HASHELP
// );
//
//
// The casting operators are defined to cast a CPropertySheetPage to a LPPROPSHEETPAGE, which is
// useful for assigning to the elements in a PROPSHEETHEADER
//
//
// PROPSHEETHEADER Psh;
// LPPROPSHEETPAGE pPageAry;
// extern PROPSHEETPAGE OtherPage;
//
// pPageAry = new PROPSHEETPAGE[ 2 ]
//
//
// pPageAry[ 0 ] = MyPropertySheetPage;
// pPageAry[ 0 ] = OtherPage;
//
// Psh . ppsp = pPageAry;
//
//
//
//
// NOTE: this is the signature for the callback function, if specified:
//
// UINT (CALLBACK FAR * LPFNPSPCALLBACKA)(HWND hwnd, UINT uMsg, struct _PROPSHEETPAGEA FAR *ppsp);
//
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __PropPg_h__
#define __PropPg_h__
////////////////////////////////////////////////////////////////////////////////////////////////////
// comment this out if you don't want data validation ( class essentially does nothing )
//
#define CPropertySheetPage_ValidateParameters
////////////////////////////////////////////////////////////////////////////////////////////////////
class CPropertySheetPage : public PROPSHEETPAGE {
public: // Construction / destruction
CPropertySheetPage( void ); // So We can make an Array of these things
CPropertySheetPage( const CPropertySheetPage& r );
// pssTemplate can specify either the resource identifier of the template
// or the address of a string that specifies the name of the template
CPropertySheetPage( LPCTSTR pszTemplate, DLGPROC pfnDlgProc,
DWORD dwFlags = 0, LPARAM lParam = 0L
);
CPropertySheetPage( LPCDLGTEMPLATE pResource, DLGPROC pfnDlgProc,
DWORD dwFlags = 0, LPARAM lParam = 0L
);
// psTemplate can specify either the resource identifier of the template
// or the address of a string that specifies the name of the template
CPropertySheetPage( LPCTSTR pszTemplate, DLGPROC pfnDlgProc,
HICON hIcon, LPCTSTR pszTitle = NULL, DWORD dwFlags = 0,
LPARAM lParam = NULL, LPFNPSPCALLBACK pfnCallBack = NULL,
UINT FAR * pcRefParent = NULL
);
CPropertySheetPage( LPCDLGTEMPLATE pResource, DLGPROC pfnDlgProc,
HICON hIcon, LPCTSTR pszTitle = NULL, DWORD dwFlags = 0,
LPARAM lParam = NULL, LPFNPSPCALLBACK pfnCallBack = NULL,
UINT FAR * pcRefParent = NULL
);
// pszTemplate can specify either the resource identifier of the template
// or the address of a string that specifies the name of the template
CPropertySheetPage( LPCTSTR pszTemplate, DLGPROC pfnDlgProc,
LPCTSTR pszIcon, LPCTSTR pszTitle = NULL, DWORD dwFlags = 0,
LPARAM lParam = NULL, LPFNPSPCALLBACK pfnCallBack = NULL,
UINT FAR * pcRefParent = NULL
);
CPropertySheetPage( LPCDLGTEMPLATE pResource, DLGPROC pfnDlgProc,
LPCTSTR pszIcon, LPCTSTR pszTitle = NULL, DWORD dwFlags = 0,
LPARAM lParam = NULL, LPFNPSPCALLBACK pfnCallBack = NULL,
UINT FAR * pcRefParent = NULL
);
CPropertySheetPage( LPCPROPSHEETPAGE pPageVector );
CPropertySheetPage& operator=( const CPropertySheetPage& r );
~CPropertySheetPage( void );
// conversion operator
operator LPPROPSHEETPAGE() { return this; }
operator LPCPROPSHEETPAGE() { return this; }
private: // Helper Fns
void _InitData( void );
BOOL _IsRightToLeftLocale( void ) const;
// Set with optional validation, defined in the cpp file
BOOL _Set_hInstance( HINSTANCE hInst );
BOOL _Set_pszTemplate( LPCTSTR pszTemplate );
BOOL _Set_pResource( LPCDLGTEMPLATE pResource );
BOOL _Set_hIcon( HICON hIcon );
BOOL _Set_pszIcon( LPCTSTR pszIcon );
BOOL _Set_pszTitle( LPCTSTR pszTitle );
BOOL _Set_pfnDlgProc( DLGPROC pfnDlgProc );
BOOL _Set_pfnCallback( LPFNPSPCALLBACK pfnCallBack );
BOOL _Set_lParam( LPARAM lParam );
BOOL _Set_pcRefParent( UINT FAR * pcRefParent );
BOOL _Validate( void ) const;
};
#endif // __PropPg_h__
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
777df6a0ee9e52a0003e79483024dd57a3f532d0 | 720f9f7c3732c7b48d8bff2a41e57dd6b6f7d5eb | /searchInABinarySearchTree/searchBST.cpp | 3ebb7703adc475e5cea0890ee95d8187cc35698a | [] | no_license | WindZQ/LintCode | 99364e6861dd1c20412831b8fffff9f5c385b3fc | ec4c69ce90ec705d331a71362d44a29a04cd8204 | refs/heads/master | 2023-05-01T09:03:12.792290 | 2023-04-16T04:19:35 | 2023-04-16T04:19:35 | 202,881,696 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | #define method1 1
#define method2 0
class TreeNode
{
public:
int val;
TreeNode *left, *right;
TreeNode(int val)
{
this->val = val;
this->left = this->right = NULL;
}
};
class Solution
{
public:
#if method1
TreeNode *searchBST(TreeNode *root, int val)
{
if (root == nullptr) return nullptr;
if (val == root->val) return root;
return searchBST(val < root->val ? root->left : root->right, val);
}
#endif
#if method2
TreeNode *searchBST(TreeNode *root, int val)
{
while (root)
{
if (val == root->val) return root;
root = val < root->val ? root->left : root->right;
}
return nullptr;
}
#endif
};
| [
"1049498972@qq.com"
] | 1049498972@qq.com |
6b4e0c3f714ca3ab17bd5c9184fc9917b7facd23 | b51e9b3d5526c577095829a60e2c25bc7a826206 | /codeforce/contest_990/A.cpp | 1a20211f53d7e6f280480b072ad7499d17acdda1 | [] | no_license | kimsj0302/algorithm_study | 167e9fd0c6bf08fd22a662375277c49f8ac31c3e | 5d6221f0bc3264c335f959ce64356748936af947 | refs/heads/master | 2021-07-04T08:40:43.932944 | 2020-07-30T06:43:35 | 2020-07-30T06:43:35 | 129,777,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int n, m;
scanf("%d %d", &n, &m);
vector<int> arr;
for (int i = 0; i < n; i++) {
int tmp;
scanf("%d", &tmp);
arr.push_back(tmp);
}
int count = 0;
for (int i = 0; i<n && arr[i] <= m; i++) {
count++;
}
reverse(arr.begin(), arr.end());
for (int i = 0; i<n && arr[i] <= m; i++) {
count++;
}
printf("%d\n", min(n,count));
} | [
"kimsj0302@postech.ac.kr"
] | kimsj0302@postech.ac.kr |
dae93f98b19727ad1d7b3a1267fcdb9c25493211 | d223f5f893c4173256eb8b94336f02ad2757459d | /HackerRank/30_Days_of_Code/Day_3_Conditional_statements.cpp | 0c6f9c09c4a8d4386f394b0898ecdbcb18ec46cb | [
"MIT"
] | permissive | tanvipenumudy/Competitive-Programming-Solutions | 679c3f426bf0405447da373e27a2d956c6511989 | 9619181d79b7a861bbc80eff8a796866880b95e0 | refs/heads/master | 2023-02-26T14:20:41.213055 | 2021-01-29T07:09:02 | 2021-01-29T07:09:02 | 325,483,258 | 0 | 0 | MIT | 2021-01-29T07:09:03 | 2020-12-30T07:20:35 | null | UTF-8 | C++ | false | false | 221 | cpp | #include <iostream>
using namespace std;
int main(){
int N;
cin >> N;
if(N%2 != 0 || (N%2 == 0) && N >= 6 && N <= 20){
cout << "Weird" << endl;
}else cout << "Not Weird" << endl;
return 0;
}
| [
"kumari.sneha98@gmail.com"
] | kumari.sneha98@gmail.com |
0af5f52af9d63186caf382e11d3a8a11e0d1f439 | 41743c4b7962f2c953c16d24c7323d06ebc025f9 | /221-Maximal-Square/solution.cpp | 58cf66ad3e44dc4b1318f56a4c67eb4c04d550d1 | [] | no_license | yqliving/Practice | e3bd4d28d8e1e9dabd0ca413dee7d96db136fd22 | 34669d62b079949a329d9869dc6a8b6db791283a | refs/heads/master | 2021-06-04T21:04:57.977020 | 2016-09-05T19:18:41 | 2016-09-05T19:18:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | cpp | //dynamic programing. 以当前点(x,y) = '1' 为右下角的最大正方形的边长f(x,y) = min( f(x-1,y), f(x,y-1), f(x-1,y-1)) + 1. 递推公式已建立, dp就自然而然了.
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int row = matrix.size();
int col = matrix[0].size();
int maxSize = 0;
vector<vector<int>> dp(row, vector<int>(col));
for (int i=0; i<matrix.size(); i++) {
for (int j=0; j<matrix[i].size(); j++){
//convert the `char` to `int`
dp[i][j] = matrix[i][j] -'0';
//for the first row and first column, or matrix[i][j], dp[i][j] is ZERO
//so, it's done during the previous conversion
// i>0 && j>0 && matrix[i][j]=='1'
if (i!=0 && j!=0 & dp[i][j]!=0){
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
}
maxSize = max(maxSize, dp[i][j]);
//tracking the maxSize
}
}
return maxSize*maxSize;
}
};
| [
"yqliving@gmail.com"
] | yqliving@gmail.com |
3b56a3f3416cab3f011a11b4b13066b397932533 | 891f4b08ae193d6d824c60ade4011614c2e1e69d | /practices/cpp/level1/p11_Fighters/MenuState.h | 7ccf1746446682a9eb29e7f44f2389b67ae5fb6a | [] | no_license | Medill-East/CCpp2017 | 807d5bf3a2fa742c0b98de1f643fa8cd9611e900 | de191ff7dcd4f389d975713897b60b1166dd36ac | refs/heads/master | 2021-01-20T15:27:22.039719 | 2017-06-19T11:03:42 | 2017-06-19T11:03:42 | 82,816,855 | 0 | 0 | null | 2017-02-22T14:57:01 | 2017-02-22T14:57:01 | null | UTF-8 | C++ | false | false | 417 | h |
#include "State.h"
#include "Container.h"
#include <SFML\Graphics\Sprite.hpp>
#include <SFML\Graphics\Text.hpp>
class MenuState : public State
{
public:
MenuState(StateStack& stack, Context context);
virtual void draw();
virtual bool update(sf::Time dt);
virtual bool handleEvent(const sf::Event& event);
private:
sf::Sprite mBackgroundSprite;
GUI::Container mGUIContainer;
};
| [
"NEMailLHD@163.com"
] | NEMailLHD@163.com |
3fb0e82d1eae1e037888dc0d8773c11145eee58f | 917b3bbb89f497b8b53408e4058a600e13108b0a | /A2/sort.h | 21b092562d367ad0b273a3f207c213f890f6d8dd | [] | no_license | qinqi-wang/csce-221 | 1510c551b0976537b8c9fdacc4d3725d9a7d9a8e | ab4ab062205521ac9bb30fe2b019d6e73d07869f | refs/heads/master | 2021-01-10T04:48:10.285926 | 2016-03-26T21:50:03 | 2016-03-26T21:50:03 | 54,510,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,405 | h | //============================================================================
// Name : sort.h
// Author :
// Date :
// Copyright :
// Description : Sort interface and various sorting algorithms in C++
//============================================================================
#ifndef SORT_H_
#define SORT_H_
class Sort {
protected:
unsigned long num_cmps; // number of comparisons performed in sort function
public:
virtual void sort(int A[], int size) = 0; // main entry point
bool testIfSorted(int A[], int size); // returns false if not sorted
// true otherwise
unsigned long getNumCmps() { return num_cmps; } // returns # of comparisons
void resetNumCmps() { num_cmps = 0; }
};
class SelectionSort:public Sort { // SelectionSort class
public:
void sort(int A[], int size); // main entry point
};
class InsertionSort:public Sort { // InsertionSort class
public:
void sort(int A[], int size); // main entry point
};
class BubbleSort:public Sort { // BubbleSort class
public:
void sort(int A[], int size); // main entry point
};
class ShellSort:public Sort { // ShellSort class
public:
void sort(int A[], int size); // main entry point
};
class RadixSort:public Sort { // RadixSort class
public:
void sort(int A[], int size); // main entry point
};
#endif //SORT_H_
| [
"qinqi402@gmail.com"
] | qinqi402@gmail.com |
41e1a9c620faba205af3a3f0378f5cd954b38639 | 44c694feba8825b84584cadda3b645330e73d739 | /PluginDshow/include/DirectShowUtil.h | 8c7abd0a069fd76c96a11dfcf2586bf3f3aa20f0 | [] | no_license | mcntech/OnyxVirtualStudio | 415dd5c5a9e6631cb3ed4ec4c6d400c1a5d9e4ca | 6d707d491e9dca507824ed356363dbb232fb934a | refs/heads/master | 2022-12-14T16:51:14.553598 | 2020-08-29T22:46:49 | 2020-08-29T22:46:49 | 291,202,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,914 | h | #ifndef __DirectShowUtil__
#define __DirectShowUtil__
#include <DShow.h>
#include <Ogre.h>
#include <OgreVector2.h>
#include <initguid.h>
#include <DsUtil.h>
DEFINE_GUID(CLSID_SampleGrabber, 0xc1f400a0, 0x3f08,0x11d3, 0x9f, 0x0b, 0x00, 0x60, 0x08, 0x03, 0x9e, 0x37);
DEFINE_GUID(IID_ISampleGrabber, 0x6B652FFF, 0x11FE, 0x4fce, 0x92, 0xAD, 0x02, 0x66, 0xB5, 0xD7, 0xC7, 0x8F);
DEFINE_GUID(IID_ISampleGrabberCB, 0x0579154A, 0x2B53, 0x4994, 0xB0, 0xD0, 0xE7, 0x73, 0x14, 0x8E, 0xFF, 0x85);
//DEFINE_GUID(CLSID_NullRenderer, 0xd11dfe19, 0x8864, 0x4a60, 0xb2, 0x6c, 0x55, 0x2f, 0x9a, 0xa4, 0x72, 0xe1);
DEFINE_GUID(CLSID_NullRenderer, 0xC1F400A4, 0x3F08, 0x11D3, 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37);
DEFINE_GUID(CLSID_CWMVDecMediaObject,0x82d353df, 0x90bd, 0x4382, 0x8b, 0xc2, 0x3f, 0x61, 0x92, 0xb7, 0x6e, 0x34);
DEFINE_GUID(CLSID_WMAsfReader, 0x187463a0, 0x5bb7, 0x11d3, 0xac, 0xbe, 0x0, 0x80, 0xc7, 0x5e, 0x24, 0x6e);
// LG Smart TV SDK
DEFINE_GUID(CLSID_TSSOurce, 0xF9FC285E, 0xAC6D, 0x44D6, 0x81, 0xE2, 0x6F, 0x57, 0xCB, 0xFA, 0xF0, 0x07);
DEFINE_GUID(CLSID_McnH264DecoderFilter, 0x51751ec4, 0xe794, 0x4393, 0x8e, 0xca, 0x9b, 0x8a, 0x60, 0xc6, 0x5a, 0xfa);
DEFINE_GUID(CLSID_MCNTsRtspSrc, 0xfcfafe5b, 0xc781, 0x4e95, 0x89, 0x99, 0x92, 0xc5, 0x2f, 0xa2, 0x36, 0x11);
EXTERN_GUID(CLSID_McnH264MediaObject, 0x3a82ba53, 0xddf2, 0x4565, 0xbc, 0xfd, 0x4a, 0xb8, 0x4, 0xd9, 0x1a, 0xca);
EXTERN_GUID(CLSID_McnMp4Demux, 0x860019cb, 0x76f6, 0x4506, 0x9d, 0x8b, 0x6e, 0xb1, 0x24, 0x2f, 0xbb, 0x55);
EXTERN_GUID(CLSID_CMPEG2VidDecoderDS, 0x212690FB, 0x83E5, 0x4526, 0x8F, 0xD7, 0x74, 0x47, 0x8B, 0x79, 0x39, 0xCD);
MIDL_INTERFACE("0579154A-2B53-4994-B0D0-E773148EFF85")
ISampleGrabberCB : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE SampleCB(
double SampleTime,
IMediaSample *pSample) = 0;
virtual HRESULT STDMETHODCALLTYPE BufferCB(
double SampleTime,
BYTE *pBuffer,
long BufferLen) = 0;
};
MIDL_INTERFACE("6B652FFF-11FE-4fce-92AD-0266B5D7C78F")
ISampleGrabber : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE SetOneShot(
BOOL OneShot) = 0;
virtual HRESULT STDMETHODCALLTYPE SetMediaType(
const AM_MEDIA_TYPE *pType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType(
AM_MEDIA_TYPE *pType) = 0;
virtual HRESULT STDMETHODCALLTYPE SetBufferSamples(
BOOL BufferThem) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer(
/* [out][in] */ long *pBufferSize,
/* [out] */ long *pBuffer) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentSample(
/* [retval][out] */ IMediaSample **ppSample) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCallback(
ISampleGrabberCB *pCallback,
long WhichMethodToCallback) = 0;
};
class CCompositorCB
{
public:
virtual int NextFrameCB(unsigned char *pData, long lSize, double Pts) = 0;
};
struct DirectShowData
{
IGraphBuilder *pGraph;
IMediaControl *pControl;
IMediaEvent *pEvent;
IBaseFilter *pGrabberF;
IBaseFilter *pVidDecF;
ISampleGrabber *pGrabber;
IMediaSeeking *pSeeking;
IVideoWindow *pWindow;
IBaseFilter *pVidSrc;
IBaseFilter *pAudSrc;
int videoWidth;
int videoHeight;
int verticalFlip;
};
WCHAR* util_convertCStringToWString(const char* string);
class CDsPlayer : public CDsUtil
{
public:
CDsPlayer(CCompositorCB *pCompositorCB=NULL);
virtual ~CDsPlayer();
int BuildWmvGraph(std::string moviePath);
int BuildRtspGraph(std::string moviePath);
int BuildTsFilePlayGraph(std::string moviePath);
int BuildMp4Graph(std::string moviePath);
int BuildCaptureGraph(std::string moviePath, int nCapWidth, int nCapHeight);
HRESULT FindCaptureDevice(std::string DeviceName, IBaseFilter ** ppSrcFilter);
int loadMovie(const Ogre::String& moviePath, int nCapWidth = 0, int nCapHeight = 0);
Ogre::Vector2 getMovieDimensions();
void unloadMovie();
void pauseMovie();
void playMovie();
void rewindMovie();
void stopMovie();
bool isPlayingMovie();
bool isEndOfPlay();
int getFrame(char *pBuffer, int *pnSize);
void logMessage(std::string msg)
{
Ogre::LogManager::getSingletonPtr()->logMessage("PlugInDshow:" + msg);
};
int getWidth()
{
if(dsdata) return dsdata->videoWidth; else return 0;
}
int getHeight()
{
if(dsdata) return dsdata->videoHeight; else return 0;
}
int getVerticalFlip()
{
if(dsdata) return dsdata->verticalFlip; else return 0;
}
public:
CCompositorCB *mCompositorCB;
protected:
DirectShowData* dsdata;
DWORD mdwRegister;
};
#endif // __DirectShowUtil__ | [
"rampenke@gmail.com"
] | rampenke@gmail.com |
358a6827b844fa5326fc7c3d696518f06ab1592c | 7425b73c5c4301b73efee73a2a97c478e3d9c94f | /src/sleipnir/src/hmmi.h | f51b7cc682624a36a2bfb30222d83879ca84579a | [
"CC-BY-3.0"
] | permissive | mehdiAT/diseasequest-docker | 318202ced87e5e5ed1bd609fe268ebc530c65e96 | 31943d2fafa8516b866fa13ff3d0d79989aef361 | refs/heads/master | 2020-05-15T01:21:21.530861 | 2018-04-16T22:42:34 | 2018-04-16T22:42:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,345 | h | /*****************************************************************************
* This file is provided under the Creative Commons Attribution 3.0 license.
*
* You are free to share, copy, distribute, transmit, or adapt this work
* PROVIDED THAT you attribute the work to the authors listed below.
* For more information, please see the following web page:
* http://creativecommons.org/licenses/by/3.0/
*
* This file is a component of the Sleipnir library for functional genomics,
* authored by:
* Curtis Huttenhower (chuttenh@princeton.edu)
* Mark Schroeder
* Maria D. Chikina
* Olga G. Troyanskaya (ogt@princeton.edu, primary contact)
*
* If you use this library, the included executable tools, or any related
* code in your work, please cite the following publication:
* Curtis Huttenhower, Mark Schroeder, Maria D. Chikina, and
* Olga G. Troyanskaya.
* "The Sleipnir library for computational functional genomics"
*****************************************************************************/
#ifndef HMMI_H
#define HMMI_H
#include "fullmatrix.h"
#include <cstdlib>
namespace Sleipnir {
class CHMMImpl {
protected:
size_t GetStates( ) const {
size_t i, iRet;
iRet = 1;
for( i = 0; i < m_iDegree; ++i )
iRet *= GetSymbols( );
return iRet; }
size_t GetSymbols( ) const {
return ( m_strAlphabet.length( ) + 1 ); }
size_t Encode( const std::string& strData, size_t iCount ) const {
size_t i, iRet;
iRet = 0;
for( i = 0; ( i < iCount ) && ( i < strData.size( ) ); ++i )
iRet = ( iRet * GetSymbols( ) ) + Encode( strData[ i ] ) + 1;
return iRet; }
std::string Decode( size_t iState ) const {
std::string strRet;
size_t i, iCur;
for( i = 0; i < m_iDegree; ++i ) {
iCur = iState % GetSymbols( );
strRet = ( iCur ? m_strAlphabet[ iCur - 1 ] : '_' ) + strRet;
iState = ( iState - iCur ) / GetSymbols( ); }
return strRet; }
size_t Encode( char cDatum ) const {
size_t i;
for( i = 0; i < m_strAlphabet.length( ); ++i )
if( cDatum == m_strAlphabet[ i ] )
return i;
// I can't think of a better way to handle all exception cases...
return ( rand( ) % m_strAlphabet.length( ) ); }
std::string m_strAlphabet;
size_t m_iDegree;
CFullMatrix<size_t> m_MatTransitions;
};
}
#endif // HMMI_H
| [
"vicyao@gmail.com"
] | vicyao@gmail.com |
e1ef7d13658f6fe0a8f68220934c3d93e9f0ba10 | 1b68b820f7f1a2f2c6f127c72d5ebbebc340875c | /rotor.cpp | 7ba01d1c3c4a62aab4670659666a7307e9b8a729 | [] | no_license | elleggert/enigma_oop | 83ff2e4c0c6052ca80477d23177cb4c30ff384f5 | b92f7dfa06ab60a9313688c4fd231e0ddefa4d02 | refs/heads/master | 2023-03-28T16:50:10.802567 | 2021-03-28T12:38:08 | 2021-03-28T12:38:08 | 352,323,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,183 | cpp | #include "rotor.h"
#include "errors.h"
using namespace std;
Rotor::Rotor(string const& call_string){
int count = 0;
string rot_digit_string;
ifstream is_rotor;
is_rotor.open(call_string, ios::in);
if (!is_rotor)
exit_code = ERROR_OPENING_CONFIGURATION_FILE;
//FILLING THE ROTOR
is_rotor >> rot_digit_string;
while (!exit_code && count < ALPHABET){
if (!exit_code)
is_numeric(rot_digit_string, exit_code);
if (!exit_code)
input_in_range(rot_digit_string, exit_code);
if (!exit_code)
rot_configuration[count] = stoi(rot_digit_string);
if (!exit_code && !is_repetitive(count, rot_configuration))
exit_code = INVALID_ROTOR_MAPPING;
if (!exit_code)
is_rotor >> rot_digit_string;
count++;
}
// FILLING THE NOTCHES
if (!exit_code && is_rotor){
for (int j = 0; !is_rotor.eof(); j++){
if (!exit_code)
is_numeric(rot_digit_string, exit_code);
if (!exit_code)
input_in_range(rot_digit_string, exit_code);
if (!exit_code){
notches[j] = stoi(rot_digit_string);
notches[j+1] = -1;
is_rotor >> rot_digit_string;
}
}
}
is_rotor.close();
}
/*END OF FUNCTION*/
void Rotor::rotate(){
int k = this->notches[0];
//Rotating a rotor
//If hitting a notch, recursively rotating the rotor to the left
this->reference_no = (this->reference_no + 1) % ALPHABET;
for (int i = 1 ; k > 0 ; i++){
if (this->reference_no == k){
if (this->left)
(this->left)->rotate();
}
k = this->notches[i];
}
return;
}
/*END OF FUNCTION*/
int Rotor::encrypt_forward(int digit){
digit = (this->rot_configuration[(digit + reference_no) % ALPHABET] -
this->reference_no + ALPHABET) % ALPHABET;
if (this->left)
digit = (this->left)->encrypt_forward(digit);
return digit;
}
/*END OF FUNCTION*/
int Rotor::encrypt_backwards(int digit){
for (int i = 0; i < ALPHABET ; i++)
if (this->rot_configuration[i] == (digit + this->reference_no) % ALPHABET){
digit = (i - reference_no + ALPHABET) % ALPHABET;
if (this->right)
digit = (this->right)->encrypt_backwards(digit);
break;
}
return digit;
}
/*END OF FUNCTION*/
| [
"edgareggert@MacBook-Pro.fritz.box"
] | edgareggert@MacBook-Pro.fritz.box |
4c2e7262557aaad3293ba0593ee001128a31bf21 | 48e316e88aefc59a3591d91852ee0441c6888bbd | /wssa_lab2_2/wssa_lab2_2.ino | 5fbe9332852cc7a9fd5af049302ba5803f377651 | [] | no_license | marklangster/wssa_lab_2 | 4b15e2f220a315a3a3fda8c6932054c14ccce2e8 | 372cbdc076160690474458c2215cd98b3a076f76 | refs/heads/master | 2020-07-31T04:35:37.295370 | 2019-10-01T02:55:57 | 2019-10-01T02:55:57 | 210,486,738 | 0 | 0 | null | 2019-09-28T21:05:43 | 2019-09-24T01:41:48 | C++ | UTF-8 | C++ | false | false | 5,139 | ino |
#include <FreeRTOS_ARM.h>
#define BLUE 8
#define GREEN 7
#define RED 6
String strBlink = "red\n";
int pin = RED;
/*
Midi Parser Callback functions
*/
//typedef struct notes{
// uint8_t note;
// uint8_t velocity;
// uint8_t status;
//}notes;
//
//
// uint32_t _bpm = 120; //default values
// uint16_t _ticksPerNote = 96; // default values
//
//void onError(int errorCode){
// SerialUSB.print("Error received: ");
// SerialUSB.println(errorCode);
//}
//
//void onReady(){
// SerialUSB.println("Device ready");
// SerialUSB.print("Device IP: ");
// //SerialUSB.println(IPAddress(PowerDueWiFi.getDeviceIP()));
// xTaskCreate(TcpMIDIStream, "tcp",configMINIMAL_STACK_SIZE, NULL, 1, NULL);
//}
//
//
//void midi_handleEvent(uint64_t delayTicks, uint8_t status, uint8_t note, uint8_t velocity){
//// if (status == STATUS_NOTE_ON && velocity > 0){
//// SerialUSB.println(freq[note]);
//// Codec.playTone(freq[note]);
//// }else{
//// Codec.stopTone();
//// }
//
////
//// uint32_t waitTimeMS = TRACK_TIMER_PERIOD_MS(_ticksPerNote, _bpm) * delayTicks;
//// delay(waitTimeMS);
//// if (status == STATUS_NOTE_ON && velocity > 0){
//// Codec.playTone(freq[note]);
//// }else{
//// Codec.stopTone();
//// }
//
// notes newNote;
// newNote.note = note;
// newNote.velocity = velocity;
// newNote.status = status;
// vTaskDelay(pdMS_TO_TICKS(TRACK_TIMER_PERIOD_MS(_ticksPerNote, _bpm)* delayTicks));
// xQueueSend(xQueue, &newNote, 5000);
//}
//void midi_volumeChanged(uint8_t volume){
// WMSynth.setMasterVolume(volume);
//}
//
//void midi_trackStart(void){
//
//}
//
//void midi_tackEnd(void){
//
//}
//
//void midi_setTicksPerNote(uint16_t ticksPerNote){
//
//
// _ticksPerNote = ticksPerNote;
//
//}
//
//void midi_setBPM(uint32_t bpm){
//
// _bpm = bpm;
//
//}
SemaphoreHandle_t sem;
void setup() {
SerialUSB.begin(9600);
pinMode(RED, OUTPUT);
pinMode(BLUE, OUTPUT);
pinMode(GREEN, OUTPUT);
digitalWrite(RED, LOW);
digitalWrite(BLUE, LOW);
digitalWrite(GREEN, LOW);
while (!SerialUSB);
SerialUSB.println("Before");
sem = xSemaphoreCreateBinary();
SerialUSB.println("After");
xTaskCreate(serialBlink, "serialBlink", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
xTaskCreate(timeBlink, "timeBlink", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
// xTaskCreate(queueRead, "queueRead",configMINIMAL_STACK_SIZE, NULL, 1, NULL);
// xTaskCreate(serialRead, "serialRead",configMINIMAL_STACK_SIZE, NULL, 1, NULL);
vTaskStartScheduler();
while(1);
}
void loop() {
// if (SerialUSB.available()){
// parser->feed(SerialUSB.read());
// }
}
//void TcpMIDIStream (void *arg) {
// MidiParser parser = MidiParser(&midiCallbacks);
// uint8_t buf[BUFSIZE];
// struct sockaddr_in serverAddr;
// int socklen;
// memset(&serverAddr, 0, sizeof(serverAddr));
//
// serverAddr.sin_len = sizeof(serverAddr);
// serverAddr.sin_family = AF_INET;
// serverAddr.sin_port = htons(SERVER_PORT);
// inet_pton(AF_INET, SERVER_ADDR, &(serverAddr.sin_addr));
//
// int s = lwip_socket (AF_INET, SOCK_STREAM, 0);
// if (lwip_connect(s, (struct sockaddr *)&serverAddr, sizeof(serverAddr))) {
// SerialUSB.println("Failed to connect to server");
// assert(false);
// }
// //register with the server
// lwip_write(s, ANDREW_ID, strlen(ANDREW_ID));
//
// SerialUSB.println("Connected and waiting for events!");
//
// //listen for incoming events
// while (1) {
// memset(&buf, 0, BUFSIZE);
// int n = lwip_read(s, buf, BUFSIZE);
// for (int i = 0; i < n; i++){
// parser1->feed(buf[i]);
// }
// }
//
// //close socket after everything is done
// lwip_close(s);
//}
//
//void queueRead (void *arg){
// while (1){
// notes newNote;
// xQueueReceive(xQueue, &(newNote), 5000);
//
// if (newNote.status == STATUS_NOTE_ON && newNote.velocity > 0){
// WMSynth.playToneN(newNote.note,newNote.velocity,0);
// } else{
// WMSynth.stopToneN(newNote.note);
// }
// }
//}
void timeBlink (void *arg){
while(1){
SerialUSB.println("before");
xSemaphoreTake(sem, portMAX_DELAY);
SerialUSB.println("after");
if (strBlink == "red\n"){
pin = RED;
}
else if (strBlink == "blue\n"){
pin = BLUE;
}
else {
pin = GREEN;
}
digitalWrite(pin, HIGH);
vTaskDelay((500L * configTICK_RATE_HZ)/ 1000L);
digitalWrite(pin, LOW);
vTaskDelay((500L * configTICK_RATE_HZ)/ 1000L);
xSemaphoreGive(sem);
}
}
void serialBlink (void *arg){
while(1){
xSemaphoreTake(sem, portMAX_DELAY);
if (SerialUSB.available()){
String re = SerialUSB.readString();
SerialUSB.println(re);
SerialUSB.println(re == "b\n");
if (re == "blue\n" || re == "red\n" || re == "green\n"){
strBlink = re;
SerialUSB.print("Light changed to ");
SerialUSB.println(strBlink);
}
}
xSemaphoreGive(sem);
}
}
//
//void serialRead (void *arg){
// while(1){
// if (SerialUSB.available()){
// uint8_t re = SerialUSB.read();
// parser2->feed(re);
// }
// }
//}
| [
"ajravi@cmu.edu"
] | ajravi@cmu.edu |
52413ab223b56869afcc324234c6b3a461977a4b | a6bf1b33cd201ec3f153cfbece69cd4216bdebcd | /Chapter09/Mesh.h | 678b598e8d0a1888bd9061036b87fc14a30961c4 | [] | no_license | lehmamic/gameprogcpp | 2fe9ac91b4e73e4aeb4002415d300a02c121aa80 | 46e34a0dcdb426a71ee3088a0535837b6479dbb9 | refs/heads/master | 2023-02-25T17:54:17.558290 | 2021-02-02T19:16:05 | 2021-02-02T19:16:05 | 328,257,940 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | h | //
// Mesh.hpp
// Game-mac
//
// Created by Michael Lehmann on 14.01.21.
// Copyright © 2021 Sanjay Madhav. All rights reserved.
//
#ifndef Mesh_hpp
#define Mesh_hpp
#include <vector>
#include <string>
class Mesh
{
public:
Mesh();
~Mesh();
// Load/unload mesh
bool Load(const std::string& fileName, class Renderer* renderer);
void Unload();
// Get the vertex array associated with this mesh
class VertexArray* GetVertexArray() { return mVertexArray; }
// Get a texture from specified index
class Texture* GetTexture(size_t index);
// Get name of shader
const std::string& GetShaderName() const { return mShaderName; }
// Get object space bounding sphere radius
float GetRadius() const { return mRadius; }
// Get specular power of mesh
float GetSpecPower() const { return mSpecPower; }
private:
// Texture associated with this mesh
std::vector<class Texture*> mTextures;
// Vertex array associated with this mesh
class VertexArray* mVertexArray;
// Name if shader specified by mesh
std::string mShaderName;
// Stores object space bounding sphere
float mRadius;
// Specular power of surface
float mSpecPower;
};
#endif /* Mesh_hpp */
| [
"michael.lehmann1@swisscom.com"
] | michael.lehmann1@swisscom.com |
56f0e825afe18fb81212766aecfe5c2894967040 | 408b6800407e111ebd0aa63bb8e77ca7838ccc67 | /HashEx/Bloque.h | 69f3f8b325c3e1c79f4796be76cda865733c074a | [] | no_license | AlexR1712/tpdatos-cyberchamuyo | 1b6b7ce0e509e642320745e896804207f4fc7264 | 975179bba5898eb4fc924c2c89ae8f5d00b18db7 | refs/heads/master | 2021-01-13T00:49:03.752634 | 2012-12-09T04:07:17 | 2012-12-09T04:07:17 | 47,661,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,909 | h | /*
* File: Bloque.h
*
*
*/
#ifndef BLOQUE_H
#define BLOQUE_H
#include "RegistroVariable.h"
#include "BloqueCtes.h"
#include <list>
#include <stdexcept>
using std::runtime_error;
typedef std::list <RegistroVariable*> listaReg;
typedef std::list <RegistroVariable*>::iterator itListaReg;
// BLOQUE: Clase que representa la entidad bloque. Contiene
// registros variables que podrán ser agregados dependiendo
// del total de memoria disponible que posea.
// ATRIBUTOS BLOQUE
//
// TAMANOBLOQUE: Contiene el tamaño del bloque.
//
// REGISTRO: La lista de registros variables que contiene
// el bloque.
//
// ESPACIOLIBRE: La cantidad de espacio libre qu poseé el bloque.
//
// CANTIDAD REGISTROS: La cantidad total de registros que poseé
// el bloque.
//
class Bloque
{
private:
long tamanoBloque;
listaReg registros;
long espacioLibre;
int cantRegistros;
void setEspacioLibre(long espacioOcupado);
virtual void print(std::ostream& oss) const = 0;
virtual void input(std::istream& oss) const = 0;
virtual void LlenarRegistros(std::istream& oss, int cantReg) = 0;
void borrarDatos(void);
public:
Bloque(long tamanoBloque);
long getTamanoBloque();
long getEspacioLibre();
virtual void ImprimirATexto(std::ostream& oss) = 0;
int addRegistro(RegistroVariable* registro);
RegistroVariable* getRegistro(int posicion);
void setCantRegistros(int cantReg);
int getCantRegistros();
void anularRegistros(void);
void vaciar(void);
void borrarRegistro(int posicion);
bool estaVacio(void);
virtual ~Bloque();
friend std::ostream& operator<<(std::ostream& oss,
Bloque &bl);
friend std::istream& operator>>(std::istream& oss,
Bloque &bl);
};
class ExcepcionPosicionInvalidaEnBloque : std::exception
{
virtual const char* what() const throw() {
return "Error PosicionInvalida";
}
};
#endif /* BLOQUE_H */
| [
"transparencia.tornasolada@gmail.com"
] | transparencia.tornasolada@gmail.com |
51d147b835b1aa4e77263e18260c46b7e856545a | 1771a4f5365581f36a074b4ff3ad7533da69c165 | /PistonOptix/inc/LightParameters.h | 4719daefe8264fdc00b6e9cce5544a39c98ce905 | [] | no_license | surajsubudhi10/PistonOptix | 19f11c31858321453ac9fecdd90a72c705edeee4 | d0af842ba7f2f236f3e0b5988a99784ed4b76ae1 | refs/heads/master | 2020-05-23T04:25:16.726058 | 2019-06-08T07:01:05 | 2019-06-08T07:01:05 | 186,630,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | h | #pragma once
#ifndef LIGHT_PARAMETERS_H
#define LIGHT_PARAMETERS_H
#include "PistonOptix\shaders\shader_common.h"
#include "PistonOptix\shaders\rt_function.h"
namespace POptix
{
enum ELightType
{
SPHERE,
QUAD,
DIRECTIONAL,
NUM_OF_LIGHT_TYPE
};
struct Light
{
optix::float3 position;
optix::float3 normal; // for directional light its the direction of light
optix::float3 emission;
optix::float3 u;
optix::float3 v;
float area;
float radius;
bool isDelta;
ELightType lightType;
};
struct LightSample
{
optix::float3 surfacePos;
int index;
optix::float3 direction; // Direction is from the hit point to the light surface (wi)
float distance;
optix::float3 emission;
float pdf;
};
}
#endif // LIGHT_PARAMETERS_H
| [
"surajsubudhi10@gmail.com"
] | surajsubudhi10@gmail.com |
a07068e59c0c80eea0f8d831662cf546f433ef3f | 0bc8816d6cd37f489a30329634ea50228489eeac | /operatorParent.cpp | 5781199f3062c563fa1b59ee22bffa69f3aacf61 | [] | no_license | gspeiliu/AnnotatedSTLSrc | 93e5ff73e5bd9d8f9bfb5789b1e4ba3c95c601a7 | 85469a41dd2e26a93d3aa6aa437fe1a50c6f3fd1 | refs/heads/master | 2021-01-10T10:54:51.770472 | 2016-03-23T12:37:55 | 2016-03-23T12:37:55 | 54,553,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | #include <iostream>
using namespace std;
template <typename T>
struct Plus {
T operator() (const T& x, const T& y) const {
return x + y;
}
};
template <class T>
struct Minus {
T operator() (const T& x, const T& y) const {
return x - y;
}
};
int main()
{
Plus<int> plusObj;
Minus<int> minusObj;
std::cout << plusObj(3, 5) << std::endl;
std::cout << minusObj(3, 5) << std::endl;
std::cout << Plus<int>()(43, 50) << std::endl;
std::cout << Minus<int>() (43, 50) << std::endl;
return 0;
} | [
"liupeifox@gmail.com"
] | liupeifox@gmail.com |
9ce0bcd103931ac3f156c631b17b78c4c33ef2bc | 7553bd56c098f4e8ba5843a5523e9dc98bb18e27 | /src/ReactionTimer/ReactionTimer.ino | a70304c33fdc60f6011e58c47056d6b22e80b519 | [] | no_license | DerbyGrammar/ReactionTimer | 2e274b53d7b37a928e23ddfc23139a0621890004 | 62305bd8d6231973e3d56466606f7d9985f222ac | refs/heads/master | 2020-04-16T23:51:50.092533 | 2016-09-28T06:31:46 | 2016-09-28T06:31:46 | 51,642,052 | 1 | 0 | null | 2016-03-29T19:19:43 | 2016-02-13T10:48:05 | Arduino | UTF-8 | C++ | false | false | 4,961 | ino | /*
Chris Nethercott
Reaction Timer
*/
#include <Wire.h> // Wire library for communicating with the I2C devices.
#include <LiquidCrystal_I2C.h> // LCD library for outputing text to the I2C LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // Sets the address for the LCD I2C
const int switchPin = 8; // Switch Pin
const int ledArray[] = {2,3,4,5,6}; // Array for the LED Pins
int randomTimeMin = 3; // Mininium Time (s)
int randomTimeMax = 8; // Maximium Time (s)
int ledDelayTime = 1000; // Amount of time between the leds coming on
boolean lastButton = LOW; // If the state of the button has changed
boolean currentButton = LOW; // If the state of the button has changed
boolean Started = false; // If the reaction timer has started
boolean timer = false; // If the timer has started
long startTime; // startTime for measuring the reaction time
long endTime; // endTime for measuring the reaction time
long randomTime; // randomTime delay from all LEDs on to them all off
float elapsedTime; // startTime - endTime
String firstLine = "Reaction Timer"; // first line of the LCD, must be below 16 char
void setup() {
pinModes(); // Uses a subroutine to set all of the inputs/outputs
Serial.begin(9600); // Begins the Serial port for printing with the operator
randomSeed(analogRead(-1)); // You will need this to generate proper 'random' numbers
lcd.begin(); // Begins the LCD
lcd.backlight(); // Turns on the backlight
lcdClear();
digitalWrite(switchPin, HIGH); // Writes the switch HIGH, because we use a two prong switch, instead of a push button
}
void lcdClear() {
lcd.clear(); // Clears the LCD
lcd.print(firstLine); // Prints Reaction Timer
}
void pinModes() {
pinMode(switchPin, INPUT); // Sets switch as an input
for(int i = 0; i < sizeof(ledArray); i++) {
pinMode(ledArray[i], OUTPUT);
}
}
boolean debounce(boolean last) { // To see if the button has been pressed
boolean current = digitalRead(switchPin); // Sets the boolean to the current state of the button
if(last != current) { // If the last state does NOT equal current
delay(5); // Use for stability
current = digitalRead(switchPin); // Reads the state again, see if it has changed
}
return current; // Returns the state of the button
}
void loop() { // Loop runs every milisecond
currentButton = debounce(lastButton);
if(lastButton == HIGH && currentButton == LOW) { // When the button was high, but now is low
Started = !Started; // Toggles the started state
lastButton = LOW; // Sets the lastButton to low
}
lastButton = currentButton; // Sets the lastButton state to currentButton
if(Started == true && timer == false) { // When started is true and timer isn't running
Random(); // Starts the Reaction Timer
timer = true; // Starts the timer
}
if(Started == false && timer == true) { // When started is false and the timer is running
Stop(); // Stops the Reaction Timer
timer = false; // Turns off the timer
}
}
void Random() {
randomTime = random(randomTimeMin,randomTimeMax); // Generates the random number
randomTime = randomTime*1000; // Converts the number from ms to s
lcdClear();
lcd.setCursor(0,1); // Sets the LCD cursor to bottom left
lcd.print("Get Ready!");
Serial.print("Random Time: "); // Prints to the operator the randomTime
Serial.println(randomTime);
ledSequence(); // Starts the super cool f1 lighting sequence
delay(randomTime); // Delays the randomTime which was generated earlier
Start(); // Calls the Start() subroutine
}
void ledSequence() { // LED Sequence
for(int i = 0; i < sizeof(ledArray); i++) {
digitalWrite(ledArray[i], HIGH);
delay(ledDelayTime);
}
}
void Start() {
lcdClear();
lcd.setCursor(0,1); // Sets the cursor to the second line
lcd.print("Go!"); // Prints Go!
startTime = millis(); // Sets the start time using the millis() function.
allLedsLow(); // Turns all LEDs off
}
void allLedsLow() {
for(int i = 0; i < sizeof(ledArray); i++) {
digitalWrite(ledArray[i], LOW);
}
}
void Stop() {
endTime = millis(); // Sets the end time
elapsedTime = (endTime - startTime)+5; // Sets the elasped time to start-end
elapsedTime = elapsedTime/1000; // Changed it from ms to s
Serial.print("Reaction Time: "); // Prints to the operator the reaction time
Serial.println(elapsedTime);
lcd.clear(); // Clears the LCD
lcd.print("Time: "); // Tells the user their reaction time
lcd.print(elapsedTime);
lcd.print("s");
lcd.setCursor(0,1); // Moves the LCD cursor to the second line
if(elapsedTime < 0.2) { // Custom Messages depending on the time
lcd.print("You are fast!");
}
else if(elapsedTime < 0.5) {
lcd.print("Awesome!");
}
else if(elapsedTime < 1) {
lcd.print("Too Slow!");
}
else {
lcd.print("Try Again!");
}
allLedsLow(); // Turns all LEDs off
Serial.println("New User"); // Prints to the operator that there is a new user
}
| [
"c.nethercott@icloud.com"
] | c.nethercott@icloud.com |
ad04e82d5ab3f9e59702a56d128b9ee302a5949a | 3ca8c05f1271506c881c4b24915508883d7b0eee | /Source/BaseBlank/Powers/Configurations/PowersListConfigurationAsset.cpp | 490799eb53918c19d043c7cbefae410f2a38e760 | [] | no_license | AlessandroOsima/JDPro | 4fd40cf4a0589b8db9162d897461870865fae6a1 | 3de1b0dd0e9e248c2e65b95a6e63f80bc84a761f | refs/heads/master | 2021-03-27T14:57:17.762412 | 2015-01-05T13:48:52 | 2015-01-05T13:48:52 | 26,095,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79 | cpp |
#include "BaseBlank.h"
#include "PowersListConfigurationAsset.h"
| [
"alex_osima@yahoo.it"
] | alex_osima@yahoo.it |
e7e5ce30324bb18cac2b11ff1eed2549744ce262 | 24a237096fcffd9b93d0cda3cb4c8e12de7ea840 | /interrupts.ino | f1601bae1b0e22e24c3238c236ac824c0cbede9f | [] | no_license | Larspiproj/Arduino_Sketches | b284fd6f89271eca5db07d30586db215dafcc616 | 2b0d9b90039ecbe228d7e0112ede4e57e833dca8 | refs/heads/main | 2023-01-20T20:02:05.809376 | 2020-12-04T15:39:48 | 2020-12-04T15:39:48 | 305,786,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | ino | const byte interruptPin = 2;
void setup() {
pinMode(interruptPin, INPUT_PULLDOWN);
attachInterrupt(digitalPinToInterrupt(interruptPin), print, RISING);
Serial.begin(57600);
}
void print() {
Serial.println("RISING");
}
void loop() {
}
| [
"lars.gustavsson@live.com"
] | lars.gustavsson@live.com |
0ff0d06c2b7e71e1b2565dc089517486c53f8917 | ead4ce1743f186f31c1c83264dd483fc1ad10c4d | /arduino/source/mylib/Button/Button.cpp | f7a610cb67378d28d52ac70a70d9c8d029295ce6 | [] | no_license | suhliebe/TIL | aab9ab41b50cd1d0ae056f3a8e23cfd4483cd2d7 | 60946889f5e6d1dca7662a276027a728ddbac418 | refs/heads/master | 2023-06-26T23:17:55.579342 | 2021-04-02T07:12:37 | 2021-04-02T07:12:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include "button.h"
Button::Button(int pin) : pin(pin){
pinMode(pin, INPUT_PULLUP);
state_previous = true;
callback = NULL;
}
void Button::setCallback(button_callback_t callback){
this -> callback = callback;
}
int Button::read(){
return !digitalRead(pin);
}
int Button::check() {
state_current = digitalRead(pin);
if(!state_current){
if(state_previous == true){
state_previous = false;
if(callback != NULL){
callback();
}
}
delay(5);
}
else{
state_previous = true;
}
} | [
"suhliebe@gmail.com"
] | suhliebe@gmail.com |
b4c731147be63fa91166d401f2aba46a303413ca | eedd904304046caceb3e982dec1d829c529da653 | /OLD/ncurses_test2.cpp | f31d53966993c9e19776bb916e7e810fe998b0d5 | [] | no_license | PaulFSherwood/cplusplus | b550a9a573e9bca5b828b10849663e40fd614ff0 | 999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938 | refs/heads/master | 2023-06-07T09:00:20.421362 | 2023-05-21T03:36:50 | 2023-05-21T03:36:50 | 12,607,904 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | #include </usr/include/ncurses.h>
int main()
{
int ch;
initscr(); /* Start curses mode */
raw(); /* Line buffering diabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc... */
noecho(); /* Don't echo() while we do getch */
printw("type any cahacter to see it in bold\n");
ch = getch(); /* If raw() hadn't been called
* we have to press enter before it
* gets to the program */
if(ch == KEY_F(1)) /* Without keypad enabled this will */
printw("F1 Key pressed"); /* not get to us either
* characters might have been printed
* on screen */
else
{
printw("The pressed key is ");
attron(A_BOLD);
printw("%c", ch);
attroff(A_BOLD);
}
refresh(); /* Print it on the real screen */
getch(); /* Wait for user input */
endwin(); /* End curses mode */
return 0;
}
| [
"paulfsherwood@gmail.com"
] | paulfsherwood@gmail.com |
b244521f49f43d36b4989418ef2885943c2f6f17 | cd8a4912aae145176e1b5570ac343ce8e15c5c49 | /Project/Project/Notepad.cpp | d1a95b2b487f0323d7047fe0178377a4050f46e9 | [] | no_license | abdulakhir98/Notepad | c1b6a519f8762640f0c53217c3beb0f5f8f76fd7 | 9ce48c78d919467915464e87f89f653cdfc2b824 | refs/heads/main | 2023-05-29T17:16:56.360196 | 2021-06-13T19:13:53 | 2021-06-13T19:13:53 | 376,609,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,511 | cpp | //#include<iostream>
//#include<fstream>
//#include <windows.h>
//#include <conio.h>
//using namespace std;
//
//int x = 0;
//int y = 0;
//
//struct node
//{
// char letter;
// node*next;
// node*prev;
// node*up;
// node*down;
//};
//
//void gotoxy(int x, int y)
//{
// COORD coord;
// coord.X = x; coord.Y = y;
// SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
//}
//
//class TwoDDLLADT
//{
// node * first, *cursor;
//
//public:
// TwoDDLLADT();
// ~TwoDDLLADT();
// void Insert(char c);
// void Print();
// void Save();
// void Load();
// bool Delete(); //delete a character wherever the pointer cursor is pointing.
// bool Up();
// bool Down();
// bool Left();
// bool Right(); // functions control the movement of the pointer cursor
//
//};
//
//TwoDDLLADT::TwoDDLLADT() {
// first = 0;
// cursor = 0;
//}
//
//TwoDDLLADT::~TwoDDLLADT() {
//
//}
//
//void TwoDDLLADT::Insert(char c) {
// node *temp = new node;
// temp->letter = c;
// temp->next = 0;
// temp->prev = 0;
// temp->up = 0;
// temp->down = 0;
// if (first == 0) {
// first = temp;
// cursor = temp;
// x = x++;
// }
// else if (temp->letter != 13)
// {
// node *move = cursor->next;
// node *above = cursor->up;
// node *current = cursor;
// while (current->prev != 0)
// {
// current = current->prev;
// }
// node *below = cursor->down;
// if (current == cursor) {
// current = 0;
// }
// if (cursor->letter != 13) {
// if (move != 0)
// {
// move->prev = temp;
// temp->next = move;
// cursor->next = temp;
// temp->prev = cursor;
// cursor = temp;
// x = x++;
// }
// else
// {
// cursor->next = temp;
// temp->prev = cursor;
// cursor = temp;
// x = x++;
// }
// if (above != 0)
// {
// move = cursor;
// above = above->next;
// while (above != 0 && move != 0)
// {
// above->down = move;
// move->up = above;
// above = above->next;
// move = move->next;
// }
// }
// while (above != 0) {
// above->down = 0;
// above = above->next;
// }
// while (move != 0) {
// move->up = 0;
// move = move->next;
// }
// if (below != 0)
// {
// move = cursor;
// below = below->next;
// while (below != 0 && move != 0)
// {
// move->down = below;
// below->up = move;
// move = move->next;
// below = below->next;
// }
// }
// while (below != 0) {
// below->up = 0;
// below = below->next;
// }
// while (move != 0) {
// move->down = 0;
// move = move->next;
// }
// }
// else {
// temp->prev = cursor->prev;
// cursor->prev->next = temp;
// temp->next = cursor;
// cursor->prev = temp;
// x = x++;
// if (above != 0)
// {
// move = temp;
// while (above != 0 && move != 0)
// {
// above->down = move;
// move->up = above;
// above = above->next;
// move = move->next;
// }
// }
// while (above != 0) {
// above->down = 0;
// above = above->next;
// }
// while (move != 0) {
// move->up = 0;
// move = move->next;
// }
// if (below != 0)
// {
// move = temp;
// while (below != 0 && move != 0)
// {
// move->down = below;
// below->up = move;
// move = move->next;
// below = below->next;
// }
// }
// while (below != 0) {
// below->up = 0;
// below = below->next;
// }
// while (move != 0) {
// move->down = 0;
// move = move->next;
// }
// }
// }
// else if (temp->letter == 13) {
// node *move = cursor;
// node *above = cursor->up;
// node *current = cursor;
// while (current->prev != 0)
// {
// current = current->prev;
// }
// node *below = cursor->down;
// if (current == cursor) {
// current = 0;
// }
// if (move == 0 && current->down == 0) {
// cursor->next = temp;
// temp->prev = cursor;
// cursor = temp;
// y = y++;
// }
// else if (move != 0 && current->down == 0) {
// cursor->next = temp;
// temp->prev = cursor;
// cursor = temp;
// current->down = move;
// move->up = current;
// move = move->next;
// current = current->next;
// while (current != 0 && move != 0) {
// current->down = move;
// move->up = current;
// current = current->next;
// move = move->next;
// }
// while (current != 0) {
// current->down = 0;
// current = current->next;
// }
// while (move != 0) {
// move->up = 0;
// move = move->next;
// }
// y = y++;
// }
// else if (move != 0 && current->down != 0) {
// node*n = current->down;
// node*k = move;
// cursor->next = temp;
// temp->prev = cursor;
// current = current->next;
// while (current != 0 && move != 0) {
// current->down = move;
// move->up = current;
// current = current->next;
// move = move->next;
// }
// while (current != 0) {
// current->down = 0;
// current = current->next;
// }
// while (move != 0) {
// move->up = 0;
// move = move->next;
// }
// while (k != 0 && n != 0) {
// k->prev->down = n;
// n->up = k;
// k = k->next;
// n = n->next;
// }
// while (k != 0) {
// k->down = 0;
// k = k->next;
// }
// while (n != 0) {
// n->up = 0;
// n = n->next;
// }
// y = y++;
// }
// }
//}
//
//void TwoDDLLADT::Print() {
// node *row = first;
// node *col = first;
// while (row != 0)
// {
// while (col != 0)
// {
// if (col->letter == 13)
// {
// cout << endl;
// break;
// }
// else
// {
// cout << col->letter;
// col = col->next;
// }
// }
// row = row->down;
// col = row;
// }
//}
//
//void TwoDDLLADT::Save(){
//
//}
//
//void TwoDDLLADT::Load() {
//
//}
//
//bool TwoDDLLADT::Delete() {
// return true;
//}
//
//bool TwoDDLLADT::Up()
//{
// int a = x;
// if (first == 0)
// return false;
// node *kp = cursor;
// if (kp->prev == 0 && kp->up == 0)
// {
// return false;
// }
// while (kp->prev != 0)
// {
// if (kp->up != 0)
// break;
// kp = kp->prev;
// a = a--;
// }
// if (kp == 0)
// return false;
// if (kp->up == 0) {
// return false;
// }
// else if (kp->up->letter == 13) {
// kp = kp->up;
// kp = kp->prev;
// y = y--;
// a = a--;
// x = a;
// cursor = kp;
// }
// else {
// kp = kp->up;
// y = y--;
// cursor = kp;
// }
// return true;
//}
//
//bool TwoDDLLADT::Down()
//{
// int a = x;
// if (first == 0)
// return false;
// node *cd = cursor;
// if (cd->prev == 0 && cd->down == 0)
// return false;
// while (cd->prev != 0)
// {
// if (cd->down != 0)
// break;
// cd = cd->prev;
// a = a--;
// }
// if (cd == 0)
// return false;
// if (cd->down == 0) {
// return false;
// }
// else if (cd->down->letter == 13) {
// cd = cd->down;
// cd = cd->prev;
// a = a--;
// x = a;
// y = y++;
// }
// else
// {
// cd = cd->down;
// y = y++;
// x = a;
// cursor = cd;
// }
// return true;
//}
//
//bool TwoDDLLADT::Right() {
// int a = x;
// if (first == 0)
// return false;
// node *cr = cursor;
// if (cr->next == 0) {
// return false;
// }
// else if (cr->next->letter == 13)
// {
// node *crl = cr;
// while (crl->prev != 0) {
// crl = crl->prev;
// a = a--;
// }
// if (crl->down == 0) {
// return false;
// }
// else {
// crl = crl->down;
// cr = crl;
// y = y++;
// x = a;
// cursor = cr;
// return true;
// }
// }
// else {
// cr = cr->next;
// cursor = cr;
// x = x++;
// return true;
// }
//}
//
//bool TwoDDLLADT::Left()
//{
// if (first == 0)
// return false;
// node *cl = cursor;
// if (cl->prev == 0)
// {
// node *cll = cl;
// while (cll->prev != 0) {
// cll = cll->prev;
// }
// if (cll->up == 0) {
// return false;
// }
// else
// {
// cll = cll->up;
// while (cll->next->letter != 13)
// {
// cll = cll->next;
// x = x++;
// }
// cl = cll;
// y = y--;
// cursor = cl;
// return true;
// }
// }
// else if (cl->prev != 0)
// {
// cl = cl->prev;
// cursor = cl;
// x = x--;
// }
// return true;
//}
//
//int main()
//{
// TwoDDLLADT notepad;
// while (1) {
// char c = _getch();
// if (c == -32)
// {
// c = _getch();
// if (c == 'H') {
// notepad.Up();
// gotoxy(x, y);
// }
// else if (c == 'K') {
// notepad.Left();
// gotoxy(x, y);
// }
// else if (c == 'M') {
// notepad.Right();
// gotoxy(x, y);
// }
// else if (c == 'P') {
// notepad.Down();
// gotoxy(x, y);
// }
//
// }
// else {
// notepad.Insert(c);
// system("CLS");
// notepad.Print();
// gotoxy(x, y);
// }
// //else if c is delete or backspace
// //else if c is S for save
// //else if c is L for load
//
// }
//}
| [
"imabdulakhir@gmail.com"
] | imabdulakhir@gmail.com |
2981effcf0bb63e50dab6b924f8744a9039fc44f | 3857953209db577fb82b3b3bb3afdc1da7394d8e | /my_exception.h | 117e275d68c6a5d8a7379afbf1b6d285a1084191 | [] | no_license | KutkoSergey/Tetris | a75e59dcfb3f2211c0b64b46a913026b90453e88 | dec299583d68684127913b4322eaeaa9a793ec7b | refs/heads/master | 2021-01-21T22:01:37.871264 | 2017-06-22T19:08:04 | 2017-06-22T19:08:04 | 95,147,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | h | #ifndef ME_EXCEPTION
#define ME_EXCEPTION
#include <QMessageBox>
#include <QInputDialog>
#include <QString>
#include "control.h"
#include <iostream>
using namespace std;
class my_exception //класс для работы с исключениями
{
protected:
int code; //код ошибки
char str_error[50]; //причина ошибки
public:
my_exception() {} //конструктор
virtual ~my_exception() {} //детруктор
};
class file_exception : public my_exception //класс для исключения с файлами
{
public:
file_exception() //конструктор
{
}
file_exception(int c, char *s); //конструктор с параметрами
void show(); //вывод сообщения ошибки
};
class record_exception:public my_exception //класс для исключений со строкой
{
public:
record_exception() //конструктор
{
}
record_exception(int c, char *s); //конструктор с параметрами
void show(); //вывод сообщения ошибки
};
QString input_record(); //функция проверки ввода строки
#endif // ME_EXCEPTION
| [
"serykutsko@gmail.com"
] | serykutsko@gmail.com |
654e1a1316b26a99aeb75f7addc28f3a0228c578 | b130b7ad8c1b2d2ae0dff47fdf75dbc526e0fed3 | /leetcode/GroupAnagrams.cpp | c3e189ef1507e3842e753ddca03265586b7f62f3 | [] | no_license | junroh/algorithme | a17e79ab4316b8798aa886a3c6dbe642898ea74f | bf26d27a6655e50e95e1f5694bc76e978b953376 | refs/heads/master | 2021-04-28T04:13:37.043671 | 2020-12-30T21:21:27 | 2020-12-30T21:21:27 | 122,155,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | // https://leetcode.com/problems/group-anagrams/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string> > occur;
for(int i=0;i<strs.size();i++) {
string str = strs[i];
string conv;
if(false) {
char count[26] = {0,};
for(int j=0;j<str.size();j++) {
count[str[j]-'a']++;
}
for(int j=0;j<26;j++) {
conv += (count[j]+'0');
}
} else {
conv = str;
sort(conv.begin(), conv.end());
}
occur[conv].push_back(str);
}
vector<vector<string>> ret;
unordered_map<string, vector<string>>::iterator it;
for(it=occur.begin();it!=occur.end();it++) {
ret.push_back(it->second);
}
return ret;
}
};
| [
"jroh@mimecast.com"
] | jroh@mimecast.com |
12f78c7d31d2c4f5b76030c1e12bdb9f9ade0e16 | f67cb6b3aae6c5ecd9aae9d58ca4b326b982a135 | /old/CIS 150/Programs/Prog 1/advt_game_01.cpp | 2621494d95bfd9153684bf8430afdc2abba90bcd | [] | no_license | watsont/old_archive_classes | 2782696afa83a7a6330b00fbcc9dcbe585a81bf3 | aaa70e3886e2bfd75430754042a697d7cd7f18d1 | refs/heads/master | 2021-01-21T02:36:04.782580 | 2014-07-12T15:25:32 | 2014-07-12T15:25:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,351 | cpp | /*
Written by Watson Tong
05/10/2008
Program 1: Adventure
Revised: 05/19/2008
This program prompts the user for their name and the total number of adventurers.
For each "turn" in the story, the user will have gained treasure at a fixed amount. The program will output
the total amount of treasure the user has at the end of that "adventure".
On that same turn, the user will have lost a certain percentage of adventurers. The number of remaining
members will be outputed by the program as well.
*/
#include <iostream>
#include <string>
using namespace std;
string first; //First name
string last; //Last name
const int TREASURE_GAIN = 1234; //Rate of treasure gained per turn
const float LIVES = .75; //Fixed constant pertaining to lives lost per turn
int main()
{
int party; //Party must be integer; is the team + user
int team; //Team must be integer; is everyone except user
string notEnough; //Not enough team members; used for output on l
notEnough = "You do not have enough members. Please re-enter.";
cout << "Please enter your first name: "; //Prompts user to input first name
cin >> first; //Stores first name
cout << "Please enter your last name: "; //Prompts for last name
cin >> last; //Stores last name
cout << "Hello " << first <<" "<< last<< "!"
<< endl
<< "You have initiated the "
<< "Pirate Adventure game!" << endl << endl;
cout << "How many team members will you have?"
<< endl
<<"(please choose at least 15 members) ";
cin >> team; //Prompts number of teammates
while(team < 15) //Causes Loop if user enters less than 9 partners
{cout << notEnough << endl;
cin >> team;
}
party = team + 1; //Total amount of party members stored (Close to useless)
cout << endl << endl
<< "And so the story unfolds:"
<< endl << endl
<<"The brave party of " << party << " adventurers "
<< "go off on an adventure." << endl << endl << endl;
cout << "They come across a strange purple cave and enter it. " //Story 1
<< endl << "On entering, Wimpy Wallace wets his shorts. "
<< "He and a few cowards leave for fear of spiders. "
<< "On the plus side, he has dropped "
<< TREASURE_GAIN<< " gold, which you take greedily." << endl << endl
<< "You have "<< int((team*LIVES)+.5) //Amount of followers the user has left
<< " members left and "
<< TREASURE_GAIN << " gold."<< endl << endl;
system("PAUSE"); //Useful for Dev-C++ and makes reading easier for user to digest
cout << endl << endl
<<"Your party continues traveling. After a long journey, " //Story 2
<< endl << "you come across a giant statue whose hands hold a lever."
<< endl << "One of your party members pulls it and a trap springs."
<< endl <<"THOMP! You have gained "<< TREASURE_GAIN <<" gold, "
<< endl <<"but at the cost of your teammate's lives." << endl
<< endl<< "There are "
<< int((party*LIVES*LIVES)+.5) << " people left." //Total amount of ALL adventurers left (different from followers!)
<< endl <<"You have a total of " << TREASURE_GAIN*2<<" gold."
<< endl << endl;
system("PAUSE"); //Useful for Dev-C++ and makes reading easier for user to digest
cout << endl << endl //Story 3
<<"Your adventure comes to a halt as you reach a dead end. Not surprisingly, "
<< endl<<"your crew become mutinous. You quickly confront the rebellion and find that "
<< endl <<"the traitors have been hiding extra portions of food as well as gold "
<< endl <<"from the party the whole time. You once again have your crew under your control. "
<< endl <<"You take the traitors' share of food and gold."
<< endl << endl
<<"You have a total of "<< int((team*LIVES*LIVES*LIVES)+.5) << " crew members"
<< endl <<"that are (for the moment) loyal to you "
<<"as well as " << TREASURE_GAIN*3 //Final amount of followers as well as gold
<<" gold. " << endl << endl
<<"What an adventure! There are "<< int((party*LIVES*LIVES*LIVES)+.5)<< " lives left!"<< endl
<<"And a whopping " <<TREASURE_GAIN*3<<" gold obtained!"
<< endl << endl;
system("PAUSE"); //Useful for Dev-C++ and makes reading easier for user to digest
return 0;
}
| [
"watson.tong@outlook.com"
] | watson.tong@outlook.com |
62a1938f063d8018c92b3cd020c63a0930f9b93f | b8376621d63394958a7e9535fc7741ac8b5c3bdc | /lib/lib_XT12/Samples/PropertyGrid/OwnerDraw/StdAfx.cpp | 5e66b9808b89575d3c7f65186b8ed9b880e0b066 | [] | no_license | 15831944/job_mobile | 4f1b9dad21cb7866a35a86d2d86e79b080fb8102 | ebdf33d006025a682e9f2dbb670b23d5e3acb285 | refs/heads/master | 2021-12-02T10:58:20.932641 | 2013-01-09T05:20:33 | 2013-01-09T05:20:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 922 | cpp | // stdafx.cpp : source file that includes just the standard includes
// OwnerDraw.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// (c)1998-2008 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
| [
"whdnrfo@gmail.com"
] | whdnrfo@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.