blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ecb37a3ae889f6d99eb66d2ad271d1e47556510
|
7ee32ddb0cdfdf1993aa4967e1045790690d7089
|
/Topcoder/Aircraft.cpp
|
c1910c203eca74d17eb9cbec9ad597dc80cd9bba
|
[] |
no_license
|
ajimenezh/Programing-Contests
|
b9b91c31814875fd5544d63d7365b3fc20abd354
|
ad47d1f38b780de46997f16fbaa3338c9aca0e1a
|
refs/heads/master
| 2020-12-24T14:56:14.154367
| 2017-10-16T21:05:01
| 2017-10-16T21:05:01
| 11,746,917
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,783
|
cpp
|
Aircraft.cpp
|
#include <iostream>
#include <sstream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <stdio.h>
using namespace std;
#define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
class Aircraft {
public:
string nearMiss(vector <int> p1, vector <int> v1, vector <int> p2, vector <int> v2, int R) ;
};
int dist2(vector<int> p1, vector<int> p2) {
int d = 0;
for (int i=0; i<3; i++) {
int c = p1[i] - p2[i];
d += c*c;
}
return d;
}
vector<double> propagate(vector <int> p, vector <int> v, double t) {
vector<double> q = vector<double>(3,0.0);
for (int i=0; i<3; i++) q[i] = p[i] + (double)v[i]*t;
return q;
}
double dist(vector<double> p1, vector<double> p2) {
double d = 0;
for (int i=0; i<3; i++) {
double c = p1[i] - p2[i];
d += c*c;
}
return sqrt(d);
}
string Aircraft::nearMiss(vector <int> p1, vector <int> v1, vector <int> p2, vector <int> v2, int R) {
if (v1==v2) {
if (dist2(p1,p2)>R*R) return "NO";
else return "YES";
}
else {
double lo = -1000000.0;
double hi = 1000000.0;
for (int i=0; i<100; i++) {
double l = (2*lo + hi)/3;
double r = (2*hi + lo)/3;
vector<double> pl1 = propagate(p1, v1, l);
vector<double> pl2 = propagate(p2, v2, l);
vector<double> pr1 = propagate(p1, v1, r);
vector<double> pr2 = propagate(p2, v2, r);
double dl = dist(pl1,pl2);
double dr = dist(pr1,pr2);
//cout<<lo<<" "<<hi<<" "<<dl<<" "<<dr<<endl;
if (dl < dr) {
hi = r;
}
else {
lo = l;
}
}
vector<double> pl1 = propagate(p1, v1, lo);
vector<double> pl2 = propagate(p2, v2, lo);
double dl = dist(pl1,pl2);
if (R-dl>-1.0e-6 && lo>-1.0e-6) return "YES";
return "NO";
}
};
//BEGIN CUT HERE
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing Aircraft (250.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1391173531;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 250.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
Aircraft _obj;
string _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
int p1[] = {15,50,5};
int v1[] = {25,1,0};
int p2[] = {161,102,9};
int v2[] = {-10,-10,-1};
int R = 10;
_expected = "YES";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 1:
{
int p1[] = {0,0,0};
int v1[] = {2,2,0};
int p2[] = {9,0,5};
int v2[] = {-2,2,0};
int R = 5;
_expected = "YES";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 2:
{
int p1[] = {0,0,0};
int v1[] = {-2,2,0};
int p2[] = {9,0,5};
int v2[] = {2,2,0};
int R = 5;
_expected = "NO";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 3:
{
int p1[] = {-2838,-7940,-2936};
int v1[] = {1,1,-2};
int p2[] = {532,3850,9590};
int v2[] = {1,0,-3};
int R = 3410;
_expected = "YES";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 4:
{
int p1[] = {-8509,9560,345};
int v1[] = {-89,-33,62};
int p2[] = {-5185,-1417,2846};
int v2[] = {-58,24,26};
int R = 8344;
_expected = "YES";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 5:
{
int p1[] = {-7163,-371,-2459};
int v1[] = {-59,-41,-14};
int p2[] = {-2398,-426,-5487};
int v2[] = {-43,27,67};
int R = 5410;
_expected = "NO";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 6:
{
int p1[] = {1774,-4491,7810};
int v1[] = {-12,19,-24};
int p2[] = {2322,3793,9897};
int v2[] = {-12,19,-24};
int R = 10000;
_expected = "YES";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
case 7:
{
int p1[] = {3731,8537,5661};
int v1[] = {-70,71,32};
int p2[] = {8701,-1886,-5115};
int v2[] = {28,-13,7};
int R = 9766;
_expected = "NO";
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}
/*case 8:
{
int p1[] = ;
int v1[] = ;
int p2[] = ;
int v2[] = ;
int R = ;
_expected = ;
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}*/
/*case 9:
{
int p1[] = ;
int v1[] = ;
int p2[] = ;
int v2[] = ;
int R = ;
_expected = ;
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}*/
/*case 10:
{
int p1[] = ;
int v1[] = ;
int p2[] = ;
int v2[] = ;
int R = ;
_expected = ;
_received = _obj.nearMiss(vector <int>(p1, p1+sizeof(p1)/sizeof(int)), vector <int>(v1, v1+sizeof(v1)/sizeof(int)), vector <int>(p2, p2+sizeof(p2)/sizeof(int)), vector <int>(v2, v2+sizeof(v2)/sizeof(int)), R); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << "\"" << _expected << "\"" << endl;
cout << " Received: " << "\"" << _received << "\"" << endl;
}
}
}
//END CUT HERE
|
0d9dcd01a7f2d21591462e1ecf73c8d576723a80
|
6de1e4199216517c9247bd5103476c33a7c98c22
|
/AdvanceLevel/1026. Table Tennis.cpp
|
d7292cd83f72cef377e78a68a3ca006ab83cfeda
|
[] |
no_license
|
Aiden68/PAT
|
9da832b5999afc5d55c3f58a39bb07dad76c89f9
|
a01df198ff75bc1209b86ced79a34a5155efc11d
|
refs/heads/master
| 2021-01-12T10:08:38.073835
| 2017-03-03T07:46:16
| 2017-03-03T07:46:16
| 76,371,489
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,706
|
cpp
|
1026. Table Tennis.cpp
|
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct Player{
int arrivetime;
int vip;
int playtime;
};
struct Table{
int idletime;
bool vip;
};
bool com(Player a, Player b){return a.arrivetime < b.arrivetime;}
int main()
{
int n, k, m, hh, mm, ss;
int tablenum[105] = { 0 };
vector<Player> player;
bool flag[10001] = { false };
Table table[105] = { 8 * 3600, false};
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
Player tplayer;
scanf("%d:%d:%d %d %d", &hh, &mm, &ss, &tplayer.playtime, &tplayer.vip);
tplayer.arrivetime = hh * 3600 + mm * 60 + ss;
if(tplayer.playtime > 120)
tplayer.playtime = 120;
player.push_back(tplayer);
}
sort(player.begin(), player.end(), com);
scanf("%d%d",&k,&m);
for (int i = 0; i < m; i++)
{
int temp;
scanf("%d", &temp);
table[temp].vip = true;
}
for(int i = 1; i <= k; i++)
table[i].idletime = 8 * 3600;
for(int i = 0; i < n; i++)
{
if(flag[i]||player[i].arrivetime >= 21 * 3600)
continue;
int min = 3600 * 21,vmin = 3600 * 21,index = -1,vindex = -1;
int servetable = 0, serveid = i, at = player[i].arrivetime, st = 3600 * 21;
for(int j = 1; j <= k; j++)
{
if(at > table[j].idletime)
table[j].idletime = at;
if(!table[j].vip&&min > table[j].idletime)
{
min = table[j].idletime;
index = j;
}
else if(table[j].vip&&vmin > table[j].idletime)
{
vmin = table[j].idletime;
vindex = j;
}
}
if(player[i].vip == 1)
{
if(vmin == at||(min > at&&vmin < min))
servetable = 1;
}
else
{
if(vmin == at&&min == at&&vindex < index)
servetable = 1;
else if(vmin == at&&min > at)
servetable = 1;
else if(min > at&&vmin > at)
{
if(vmin <= min)
{
servetable = 1;
int ti = i + 1;
while(ti < n&&player[ti].arrivetime <= vmin)
{
if(player[ti].vip == 1&&flag[ti]==false)
{
serveid = ti;
i--;
break;
}
ti++;
}
}
}
}
flag[serveid] = true;
at = player[serveid].arrivetime;
if(servetable == 1)
{
if(vindex == -1)
continue;
st = vmin;
table[vindex].idletime = st + player[serveid].playtime * 60;
if(st < 21 * 3600)
tablenum[vindex]++;
}
else
{
if(index == -1)
continue;
st = min;
table[index].idletime = st + player[serveid].playtime * 60;
if(st < 21 * 3600)
tablenum[index]++;
}
if (st >= 21 * 3600)
break;
printf("%02d:%02d:%02d ", at / 3600, at / 60 % 60, at % 60);
printf("%02d:%02d:%02d %d\n", st / 3600, st / 60 % 60, st % 60,(st - at + 30) / 60);
}
for (int i = 1; i <= k; i++)
{
if (i != 1)
printf(" ");
printf("%d", tablenum[i]);
}
return 0;
}
|
3ac267a21fda19f771a435f2e7f6ed312eef8465
|
75fabbee8319f1eadf4b5123d0f0604cd8a1491d
|
/Source/MolinaMondragon/Private/UI/GameOverHUD.cpp
|
48886aef2b727f1f9025e11d7421568dbd1e1ebe
|
[] |
no_license
|
mondragonbu/MolinaMondragon
|
3b52dfe1274c67e170899ecf46f27dd7538bd26c
|
a203a7cc13587a71411b5525cf54694867df6427
|
refs/heads/master
| 2023-05-02T08:05:23.885340
| 2021-05-21T13:58:58
| 2021-05-21T13:58:58
| 349,012,524
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 663
|
cpp
|
GameOverHUD.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "UI/GameOverHUD.h"
#include "UI/GameOverMenuWidget.h"
#include "Player/MyPlayer.h"
#include "Kismet/GameplayStatics.h"
#include "GameModes/DungeonGameInstance.h"
void AGameOverHUD::BeginPlay() {
Super::BeginPlay();
gameOverWidgetInstance_ = CreateWidget<UGameOverMenuWidget>(GetWorld()->PersistentLevel->GetWorld(), gameOverWidget_);
gameOverWidgetInstance_->AddToViewport();
UDungeonGameInstance* gminstance = Cast<UDungeonGameInstance>(UGameplayStatics::GetGameInstance(GetWorld()));
gameOverWidgetInstance_->SetFinalScore(gminstance->score_);
}
|
08434bb0db9c6a0e5c1dd5a2f4b6d29bd05f8705
|
364980e64538f28a1ffc857523fd98f17340b82b
|
/include/my_exception.h
|
8eea318a4d1eb09738fd2371082525ee470c3b85
|
[] |
no_license
|
nicomatex/taller_argentum
|
dee9f8e13f295dd386377d548a3304004763a91d
|
9f5d2485356ba5d28080a5bde1458a04f3ffe6de
|
refs/heads/master
| 2022-12-04T14:14:29.037640
| 2020-08-21T19:46:17
| 2020-08-21T19:46:17
| 268,933,989
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 381
|
h
|
my_exception.h
|
#ifndef __MY_EXCEPTION_H__
#define __MY_EXCEPTION_H__
#include <stdexcept>
#define BUFF_SIZE 256
class MyException : public std::exception {
private:
char error_msg[BUFF_SIZE];
public:
MyException() noexcept;
MyException(const char* format, ...) noexcept;
virtual const char* what() const noexcept;
~MyException();
};
#endif //__MY_EXCEPTION_H__
|
0a47d3e833ad868524e925037d3412b802a54d54
|
d085217958a5aee8bf3af7e0b3addf247f0f512b
|
/SliceModel.cpp
|
8dbab5938246e812b9c1a4c08029d75e86c5a52f
|
[
"Apache-2.0"
] |
permissive
|
yajing2018/DSI-Studio
|
43804509b669a3c9dee1dbb8f79fa5a3c931785e
|
9c1d80d5755dbfdd7fec574c3f5c6e6ecff75ed2
|
refs/heads/master
| 2020-04-14T19:26:33.993054
| 2018-12-20T13:51:17
| 2018-12-20T13:51:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,092
|
cpp
|
SliceModel.cpp
|
// ---------------------------------------------------------------------------
#include <string>
#include <QFileInfo>
#include <QImage>
#include <QInputDialog>
#include <QMessageBox>
#include <QDir>
#include "SliceModel.h"
#include "prog_interface_static_link.h"
#include "fib_data.hpp"
SliceModel::SliceModel(std::shared_ptr<fib_data> handle_,int view_id_):handle(handle_),view_id(view_id_)
{
slice_visible[0] = false;
slice_visible[1] = false;
slice_visible[2] = false;
T.identity();
invT = T;
geometry = handle_->dim;
voxel_size = handle_->vs;
slice_pos[0] = geometry.width() >> 1;
slice_pos[1] = geometry.height() >> 1;
slice_pos[2] = geometry.depth() >> 1;
}
// ---------------------------------------------------------------------------
void SliceModel::get_mosaic(tipl::color_image& show_image,
unsigned int mosaic_size,
const tipl::value_to_color<float>& v2c,
unsigned int skip,
const SliceModel* overlay,
const tipl::value_to_color<float>& overlay_v2c)
{
unsigned slice_num = geometry[2] / skip;
show_image = std::move(tipl::color_image(tipl::geometry<2>(geometry[0]*mosaic_size,
geometry[1]*(std::ceil((float)slice_num/(float)mosaic_size)))));
int old_z = slice_pos[2];
for(unsigned int z = 0;z < slice_num;++z)
{
slice_pos[2] = z*skip;
tipl::color_image slice_image;
get_slice(slice_image,2,v2c,overlay,overlay_v2c);
tipl::vector<2,int> pos(geometry[0]*(z%mosaic_size),
geometry[1]*(z/mosaic_size));
tipl::draw(slice_image,show_image,pos);
}
slice_pos[2] = old_z;
}
void SliceModel::apply_overlay(tipl::color_image& show_image,
unsigned char cur_dim,
const SliceModel* other_slice,
const tipl::value_to_color<float>& overlay_v2c) const
{
std::pair<float,float> range = other_slice->get_contrast_range();
for(int y = 0,pos = 0;y < show_image.height();++y)
for(int x = 0;x < show_image.width();++x,++pos)
{
tipl::vector<3,float> v;
toOtherSlice(other_slice,cur_dim,x,y,v);
float value = 0;
if(!tipl::estimate(other_slice->get_source(),v,value))
continue;
if(value > range.first)
show_image[pos] = overlay_v2c[value];
}
}
// ---------------------------------------------------------------------------
std::pair<float,float> SliceModel::get_value_range(void) const
{
return std::make_pair(handle->view_item[view_id].min_value,handle->view_item[view_id].max_value);
}
// ---------------------------------------------------------------------------
std::pair<float,float> SliceModel::get_contrast_range(void) const
{
return std::make_pair(handle->view_item[view_id].contrast_min,handle->view_item[view_id].contrast_max);
}
// ---------------------------------------------------------------------------
std::pair<unsigned int,unsigned int> SliceModel::get_contrast_color(void) const
{
return std::make_pair(handle->view_item[view_id].min_color,handle->view_item[view_id].max_color);
}
// ---------------------------------------------------------------------------
void SliceModel::set_contrast_range(float min_v,float max_v)
{
handle->view_item[view_id].contrast_min = min_v;
handle->view_item[view_id].contrast_max = max_v;
}
// ---------------------------------------------------------------------------
void SliceModel::set_contrast_color(unsigned int min_c,unsigned int max_c)
{
handle->view_item[view_id].min_color = min_c;
handle->view_item[view_id].max_color = max_c;
}
// ---------------------------------------------------------------------------
void SliceModel::get_slice(tipl::color_image& show_image,unsigned char cur_dim,
const tipl::value_to_color<float>& v2c,
const SliceModel* overlay,
const tipl::value_to_color<float>& overlay_v2c) const
{
handle->get_slice(view_id,cur_dim, slice_pos[cur_dim],show_image,v2c);
if(overlay && this != overlay)
apply_overlay(show_image,cur_dim,overlay,overlay_v2c);
}
// ---------------------------------------------------------------------------
tipl::const_pointer_image<float, 3> SliceModel::get_source(void) const
{
return handle->view_item[view_id].image_data;
}
// ---------------------------------------------------------------------------
CustomSliceModel::CustomSliceModel(std::shared_ptr<fib_data> new_handle):
SliceModel(new_handle,new_handle->view_item.size())
{
new_handle->view_item.push_back(item());
}
bool CustomSliceModel::initialize(const std::vector<std::string>& files,
bool correct_intensity)
{
terminated = true;
ended = true;
is_diffusion_space = false;
gz_nifti nifti;
// QSDR loaded, use MNI transformation instead
bool has_transform = false;
name = QFileInfo(files[0].c_str()).completeBaseName().toStdString();
if(QFileInfo(files[0].c_str()).suffix() == "bmp" ||
QFileInfo(files[0].c_str()).suffix() == "jpg")
{
QString info_file = QString(files[0].c_str()) + ".info.txt";
if(!QFileInfo(info_file).exists())
{
error_msg = "Cannot find ";
error_msg += info_file.toStdString();
return false;
}
std::ifstream in(info_file.toStdString().c_str());
in >> geometry[0];
in >> geometry[1];
in >> geometry[2];
in >> voxel_size[0];
in >> voxel_size[1];
in >> voxel_size[2];
std::copy(std::istream_iterator<float>(in),
std::istream_iterator<float>(),T.begin());
if(geometry[2] != files.size())
{
error_msg = "Invalid BMP info text: file count does not match.";
return false;
}
unsigned int in_plane_subsample = 1;
unsigned int slice_subsample = 1;
// non isotropic condition
while(voxel_size[2]/voxel_size[0] > 1.5f)
{
++in_plane_subsample;
geometry[0] = geometry[0] >> 1;
geometry[1] = geometry[1] >> 1;
voxel_size[0] *= 2.0;
voxel_size[1] *= 2.0;
T[0] *= 2.0;
T[1] *= 2.0;
T[4] *= 2.0;
T[5] *= 2.0;
T[8] *= 2.0;
T[9] *= 2.0;
}
tipl::geometry<3> geo(geometry);
bool ok = true;
int down_size = (geo[2] > 1 ? QInputDialog::getInt(0,
"DSI Studio",
"Downsampling count (0:no downsampling)",1,0,4,1,&ok) : 0);
if(!ok)
{
error_msg = "Slice loading canceled";
return false;
}
for(int i = 0;i < down_size;++i)
{
geo[0] = geo[0] >> 1;
geo[1] = geo[1] >> 1;
geo[2] = geo[2] >> 1;
voxel_size *= 2.0;
tipl::multiply_constant(T.begin(),T.begin()+3,2.0);
tipl::multiply_constant(T.begin()+4,T.begin()+7,2.0);
tipl::multiply_constant(T.begin()+8,T.begin()+11,2.0);
++in_plane_subsample;
++slice_subsample;
}
try{
source_images = std::move(tipl::image<float, 3>(geo));
}
catch(...)
{
error_msg = "Memory allocation failed. Please increase downsampling count";
return false;
}
begin_prog("loading images");
for(unsigned int i = 0;check_prog(i,geo[2]);++i)
{
tipl::image<short,2> I;
QImage in;
unsigned int file_index = (slice_subsample == 1 ? i : (i << (slice_subsample-1)));
if(file_index >= files.size())
break;
QString filename(files[file_index].c_str());
if(!in.load(filename))
{
error_msg = "Invalid image format: ";
error_msg += files[file_index];
return false;
}
QImage buf = in.convertToFormat(QImage::Format_RGB32).mirrored();
I.resize(tipl::geometry<2>(in.width(),in.height()));
const uchar* ptr = buf.bits();
for(int j = 0;j < I.size();++j,ptr += 4)
I[j] = *ptr;
for(int j = 1;j < in_plane_subsample;++j)
tipl::downsampling(I);
if(I.size() != source_images.plane_size())
{
error_msg = "Invalid BMP image size: ";
error_msg += files[file_index];
return false;
}
std::copy(I.begin(),I.end(),source_images.begin() + i*source_images.plane_size());
}
tipl::io::nifti nii;
nii.set_dim(geo);
nii.set_voxel_size(voxel_size);
nii.set_image_transformation(T.begin());
nii << source_images;
nii.toLPS(source_images);
nii.get_voxel_size(voxel_size);
T.identity();
nii.get_image_transformation(T.begin());
// LPS matrix switched to RAS
T[0] = -T[0];
T[1] = -T[1];
T[4] = -T[4];
T[5] = -T[5];
T[8] = -T[8];
T[9] = -T[9];
invT = tipl::inverse(T);
has_transform = true;
}
else
{
if(files.size() == 1)
{
if(nifti.load_from_file(files[0]))
{
nifti.toLPS(source_images);
nifti.get_voxel_size(voxel_size);
if(handle->is_qsdr)
{
invT.identity();
nifti.get_image_transformation(invT.begin());
invT.inv();
invT *= handle->trans_to_mni;
T = tipl::inverse(invT);
has_transform = true;
}
}
else
{
tipl::io::bruker_2dseq bruker;
if(bruker.load_from_file(files[0].c_str()))
{
bruker.get_voxel_size(voxel_size);
source_images = std::move(bruker.get_image());
QDir d = QFileInfo(files[0].c_str()).dir();
if(d.cdUp() && d.cdUp())
{
QString method_file_name = d.absolutePath()+ "/method";
tipl::io::bruker_info method;
if(method.load_from_file(method_file_name.toStdString().c_str()))
name = method["Method"];
}
}
}
}
else
{
tipl::io::volume volume;
if(volume.load_from_files(files,files.size()))
{
volume.get_voxel_size(voxel_size);
volume >> source_images;
}
}
}
if(source_images.empty())
{
error_msg = "Failed to load image volume.";
return false;
}
// same dimension, no registration required.
if(source_images.geometry() == handle->dim)
{
T.identity();
invT.identity();
is_diffusion_space = true;
has_transform = true;
}
// quality control for t1w
if(correct_intensity)
{
float t = tipl::segmentation::otsu_threshold(source_images);
float snr = tipl::mean(source_images.begin()+source_images.width(),source_images.begin()+2*source_images.width());
// correction for SNR
for(unsigned int i = 0;i < 6 && snr != 0 && t/snr < 10;++i)
{
tipl::filter::gaussian(source_images);
t = tipl::segmentation::otsu_threshold(source_images);
snr = tipl::mean(source_images.begin()+source_images.width(),source_images.begin()+2*source_images.width());
}
// correction for intensity bias
t = tipl::segmentation::otsu_threshold(source_images);
std::vector<float> x,y;
for(unsigned char dim = 0;dim < 3;++dim)
{
x.clear();
y.clear();
for(tipl::pixel_index<3> i(source_images.geometry());i < source_images.size();++i)
if(source_images[i.index()] > t)
{
x.push_back(i[dim]);
y.push_back(source_images[i.index()]);
}
std::pair<double,double> r = tipl::linear_regression(x.begin(),x.end(),y.begin());
for(tipl::pixel_index<3> i(source_images.geometry());i < source_images.size();++i)
source_images[i.index()] -= (float)i[dim]*r.first;
tipl::lower_threshold(source_images,0);
}
}
if(!has_transform)
{
if(handle->dim.depth() < 10) // 2d assume FOV is the same
{
T.identity();
invT.identity();
invT[0] = (float)source_images.width()/(float)handle->dim.width();
invT[5] = (float)source_images.height()/(float)handle->dim.height();
invT[10] = (float)source_images.depth()/(float)handle->dim.depth();
invT[15] = 1.0;
T = tipl::inverse(invT);
}
else
{
from = tipl::make_image(handle->dir.fa[0],handle->dim);
size_t iso = handle->get_name_index("iso");// for DDI
if(handle->view_item.size() != iso)
from = handle->view_item[iso].image_data;
size_t base_nqa = handle->get_name_index("base_nqa");// for DDI
if(handle->view_item.size() != base_nqa)
from = handle->view_item[base_nqa].image_data;
from_vs = handle->vs;
thread.reset(new std::future<void>(
std::async(std::launch::async,[this](){argmin(tipl::reg::rigid_body);})));
}
}
geometry = source_images.geometry();
handle->view_item.back().image_data = tipl::make_image(&*source_images.begin(),source_images.geometry());
handle->view_item.back().set_scale(source_images.begin(),source_images.end());
handle->view_item.back().name = name;
slice_pos[0] = geometry.width() >> 1;
slice_pos[1] = geometry.height() >> 1;
slice_pos[2] = geometry.depth() >> 1;
handle->view_item.back().T = T;
handle->view_item.back().iT = invT;
return true;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::argmin(tipl::reg::reg_type reg_type)
{
terminated = false;
ended = false;
tipl::const_pointer_image<float,3> to = source_images;
tipl::transformation_matrix<double> M;
tipl::reg::two_way_linear_mr(from,from_vs,to,voxel_size,M,reg_type,tipl::reg::mutual_information(),terminated,
std::thread::hardware_concurrency(),&arg_min);
ended = true;
M.save_to_transform(invT.begin());
handle->view_item[view_id].T = T = tipl::inverse(invT);
handle->view_item[view_id].iT = invT;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::update(void)
{
tipl::transformation_matrix<double> M(arg_min,from.geometry(),from_vs,source_images.geometry(),voxel_size);
invT.identity();
M.save_to_transform(invT.begin());
handle->view_item[view_id].T = T = tipl::inverse(invT);
handle->view_item[view_id].iT = invT;
}
// ---------------------------------------------------------------------------
void CustomSliceModel::terminate(void)
{
terminated = true;
if(thread.get())
thread->wait();
ended = true;
}
// ---------------------------------------------------------------------------
extern std::string t1w_template_file_name,t1w_mask_template_file_name;
bool CustomSliceModel::stripskull(void)
{
if(handle->is_human_data)
{
gz_nifti in1,in2;
tipl::image<float,3> It,Iw;
if(!in1.load_from_file(t1w_template_file_name.c_str()) || !in1.toLPS(It))
{
error_msg = "Cannot load T1W template";
return false;
}
if(!in2.load_from_file(t1w_mask_template_file_name.c_str()) || !in2.toLPS(Iw))
{
error_msg = "Cannot load T1W mask";
return false;
}
tipl::vector<3> Itvs;
in1.get_voxel_size(Itvs);
bool terminated = false;
tipl::transformation_matrix<double> T,iT;
tipl::reg::two_way_linear_mr(It,Itvs,source_images,voxel_size,T,
tipl::reg::affine,tipl::reg::mutual_information(),
terminated,std::thread::hardware_concurrency(),0);
iT = T;
iT.inverse();
tipl::image<float,3> J(It.geometry());
tipl::resample_mt(source_images,J,T,tipl::cubic);
J.save_to_file<tipl::io::nifti>("test.nii");
tipl::image<tipl::vector<3>,3> dis;
tipl::reg::cdm(It,J,dis,terminated,2.0f,0.5);
source_images.for_each_mt([&](float& v,const tipl::pixel_index<3>& p){
tipl::vector<3> pos(p);
iT(pos);
if(!dis.geometry().is_valid(pos[0],pos[1],pos[2]))
{
v = 0;
return;
}
tipl::vector<3> d;
if(!tipl::estimate(dis,pos,d))
return;
pos += d;
pos.round();
tipl::pixel_index<3> p2(pos[0],pos[1],pos[2],Iw.geometry());
if(!Iw.geometry().is_valid(p2) || Iw[p2.index()] < 0.05 )
v = 0;
});
return true;
}
else
{
tipl::image<float,3> filter(source_images.geometry());
tipl::resample(from,filter,T,tipl::linear);
tipl::filter::gaussian(filter);
tipl::filter::gaussian(filter);
float m = *std::max_element(source_images.begin(),source_images.end());
source_images *= filter;
tipl::normalize(source_images,m);
return true;
}
}
|
8858bbc7f57b84cdaf17f89dbe7d6537ee9a9abd
|
046c3dc74e8d843382a05b09edfbbc569dbaf161
|
/zdc/MpdZdcDigiScheme.cxx
|
31aa8843f9e16bfcc31f1853a64e2142185a47d2
|
[
"FSFUL"
] |
permissive
|
nburmaso/mpdroot
|
13d84e027b14754f5ff5d8ced7a47587319b97f5
|
f49cc155cf6256cae619032820b3382604527e05
|
refs/heads/master
| 2023-07-15T20:06:59.386155
| 2017-04-03T13:55:17
| 2017-04-03T13:55:17
| 379,908,134
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,551
|
cxx
|
MpdZdcDigiScheme.cxx
|
/*************************************************************************************
*
* Class MpdZdcDigiScheme
*
* Author: Elena Litvinenko
* e-mail: litvin@nf.jinr.ru
* Version: 16-May-2008
*
************************************************************************************/
#include "MpdZdcDigiScheme.h"
#include "TGeoBBox.h"
#include "TGeoManager.h"
#include "TGeoNode.h"
#include <iostream>
using std::cout;
using std::endl;
MpdZdcDigiScheme* MpdZdcDigiScheme::fInstance = 0;
Bool_t MpdZdcDigiScheme::fInitialized = 0;
Int_t MpdZdcDigiScheme::fRefcount = 0;
Bool_t MpdZdcDigiScheme::fYesPsd = 0;
static Int_t kZDC = 1; // // hard-coded basic ZDC detector number
// -------------------------------------------------------------------------
MpdZdcDigiScheme::MpdZdcDigiScheme() : Nx(0),Ny(0),Nz(0)
{
// Nx=0; Ny=0; Nz=0;
Nx_psd=0; Ny_psd=0; Nz_psd=0;
fZdcDigiPar=0;
fZdcPsdDigiPar=0;
}
// -------------------------------------------------------------------------
MpdZdcDigiScheme::~MpdZdcDigiScheme()
{
fRefcount--;
if(!fRefcount){
delete this;
fInstance = NULL;
}
}
// -------------------------------------------------------------------------
MpdZdcDigiScheme* MpdZdcDigiScheme::Instance()
{
if(!fInstance) fInstance = new MpdZdcDigiScheme();
fRefcount++;
return fInstance;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::Init (MpdZdcGeoPar* geoPar, MpdZdcDigiPar* digiPar, Bool_t pAddPsd, Int_t pVerbose)
{
if (!fInitialized){
if ( ! geoPar ) {
cout << "-W- MpdZdcDigiScheme::Init: "
<< "No geometry parameters available!" << endl;
return kFALSE;
}
if ( ! digiPar ) {
cout << "-W- MpdZdcDigiScheme::Init: "
<< "No digitization parameters available!" << endl;
// return kFALSE;
}
fZdcDigiPar = digiPar;
TObjArray* sensNodes = geoPar->GetGeoSensitiveNodes();
if (!sensNodes) {
cout << "-W- MpdZdcDigiScheme::Init: "
<< "No sensitive nodes available!" << endl;
return kFALSE;
}
fPasNodes = geoPar->GetGeoPassiveNodes();
if (!fPasNodes) {
cout << "-W- MpdZdcDigiScheme::Init: "
<< "No passive nodes available!" << endl;
return kFALSE;
}
fInitialized = kTRUE;
AddNodes (sensNodes,kZDC, pAddPsd,pVerbose );
CalcDimensions (kZDC,Nx,Ny,Nz);
if (pVerbose)
cout << endl << "-W- MpdZdcDigiScheme::Init: finished." << endl;
}
return kTRUE;
}
// -------------------------------------------------------------------------
MpdZdcVolInfo_t* MpdZdcDigiScheme::CreateVolInfoElement (FairGeoNode* nod, Int_t pVerbose)
{
if (!nod)
return NULL;
static TString root_name_copy1="";
static Double_t volData[6]={0,0,0,0,0,0};
Int_t i,j;
TString shape_name = nod->getShapePointer()->GetName();
TString root_name = nod->getRootVolume()->GetName();
TString tmp=" ";
TGeoBBox* shape=0;
FairGeoVector pos= nod->getLabTransform()->getTranslation();
for (i=0;i<3;i++)
volData[i]=pos.getValues(i); // [cm]
if (root_name!=root_name_copy1) {
root_name_copy1 = root_name;
shape = (TGeoBBox*) nod->getRootVolume()->GetShape();
if (shape_name.Contains("BOX")) {
volData[3]= shape->GetDX(); // [cm]
volData[4]= shape->GetDY(); // [cm]
volData[5]= shape->GetDZ(); // [cm]
}
else {
if (shape_name.Contains("PGON")) {
volData[3]= nod->getPoint(2)->getZ() /10.; // [cm]
volData[4]= volData[3];
volData[5]= shape->GetDZ(); // [cm]
}
}
}
MpdZdcVolInfo_t *volInfo = new MpdZdcVolInfo_t;
for (i=0;i<6;i++)
volInfo->push_back(volData[i]);
if (pVerbose>1) {
if (pVerbose>2)
tmp = " root: "+root_name + ", shape: " + shape_name;
tmp += "X,Y,Z, Dx,Dy,Dz: ";
cout << tmp <<
volData[0] << "," << volData[1] << "," << volData[2] << ", " <<
volData[3] << "," << volData[4] << "," << volData[5] << endl;
}
return volInfo;
}
// -------------------------------------------------------------------------
MpdZdcVolId_t* MpdZdcDigiScheme::CreateVolElement (FairGeoNode* nod, Int_t nodeNumber,
MpdZdcDigiId_t* right, Int_t pGlobalDetectorNumber, Int_t pVerbose)
{
if (!nod)
return NULL;
FairGeoNode *nod0, *nod1;
TString mother_name, tmp;
if (!fPasNodes)
return NULL;
nod0 = (FairGeoNode*)fPasNodes->At(0);
nod1 = (FairGeoNode*)fPasNodes->At(1);
if ((!nod0)||(!nod1))
return NULL;
mother_name = nod->getMother();
if (mother_name==nod1->GetName()) {
(*right).push_back(nod0->getCopyNo()+pGlobalDetectorNumber-1);
(*right).push_back(nod1->getCopyNo());
(*right).push_back(nodeNumber);
MpdZdcVolId_t* left = new MpdZdcVolId_t;
(*left).push_back(nod0->getCopyNo());
(*left).push_back(nod1->getCopyNo());
(*left).push_back(nod->getMCid());
(*left).push_back(nod->getCopyNo());
if (pVerbose>1) {
tmp = " mother: "+mother_name + ", me: " + (nod->getName()) +" ";
cout << tmp <<
(*left)[0] << "," << (*left)[1]<< "," << (*left)[2] << ","<< (*left)[3] << " : " <<
(*right)[0] << "," << (*right)[1]<< "," << (*right)[2] << endl;
}
return left;
}
else {
cout << "-E- MpdZdcDigiScheme::CreateVolInfoElement: Strange for me node: "
<< nod->GetName() << " Node number:" << nodeNumber << " Mother:" << mother_name << endl;
return NULL;
}
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::AddNodes (TObjArray* sensNodes,Int_t pGlobalDetectorNumber, Bool_t pAddPsd, Int_t pVerbose)
{
Int_t nNodes = sensNodes->GetEntriesFast();
FairGeoNode *nod=0;
Int_t nodeNumber,nodeCopyNo,nodeVolumeId, chanId2=0, chanId1=0;
MpdZdcVolId_t *left1,*left2;
MpdZdcDigiId_t *right1,*right2;
if (pVerbose) {
cout << "-W- MpdZdcDigiScheme::AddNodes: started:"
<< "GlobalDetectorNumber:"<< pGlobalDetectorNumber << " nNodes:" << nNodes << endl;
}
for (nodeNumber=0;nodeNumber<nNodes;nodeNumber++) {
nod = (FairGeoNode*)sensNodes->At(nodeNumber);
if (nod) {
right1 = new MpdZdcDigiId_t;
left1 = CreateVolElement(nod, nodeNumber, right1, pGlobalDetectorNumber, pVerbose);
fVolToDigiIdMap[*left1]=*right1;
left2 = new MpdZdcDigiId_t ((*left1).begin(),(*left1).end());
(*left2)[0]=(*left1)[0]+1;
right2 = new MpdZdcDigiId_t (right1->begin(),right1->end());
(*right2)[0] = (*right1)[0]+1;
fVolToDigiIdMap[*left2]=*right2;
CreateVolCopyElements (left1, right1);
if (pAddPsd) {
MpdZdcVolInfo_t *volInfo1 = CreateVolInfoElement(nod, pVerbose);
if (volInfo1) {
fDigiToVolInfoMap[*right1]=volInfo1;
MpdZdcVolInfo_t *volInfo2 = new MpdZdcVolInfo_t (*volInfo1);
(*volInfo2)[2]=-(*volInfo2)[2]; // Z
fDigiToVolInfoMap[*right2]=volInfo2;
CreateVolInfoCopyElements (right1, volInfo1);
}
}
}
else {
cout << "-W- MpdZdcDigiScheme::AddNodes: "
<< "Node number "<< nodeNumber << " from " << nNodes << " not found!" << endl;
return kFALSE;
}
}
return kTRUE;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::CreateVolCopyElements (MpdZdcVolId_t* left, MpdZdcDigiId_t* right)
{
MpdZdcVolId_t *left1,*left2;
MpdZdcDigiId_t *right1,*right2;
if (!fPasNodes)
return kFALSE;
FairGeoNode *nod1 =(FairGeoNode*) fPasNodes->At(fPasNodes->GetEntries()-2);
if (!nod1)
return kFALSE;
Int_t moduleID,nModules; // {MotherMotherCopyNo, MotherCopyNo, VolumeId, CopyNo},{DetectorID, ModuleID, ChannelID}
TString lm_name = nod1->getName();
TString last_module_number (&(lm_name[lm_name.Last('#')+1]));
nModules = last_module_number.Atoi();
for (moduleID=1; moduleID<nModules; moduleID++) {
left1 = new MpdZdcDigiId_t ((*left).begin(),(*left).end());
(*left1)[1]=(*left)[1]+moduleID;
right1 = new MpdZdcDigiId_t (right->begin(),right->end());
(*right1)[1] = (*right)[1]+moduleID;
left2 = new MpdZdcDigiId_t ((*left1).begin(),(*left1).end());
(*left2)[0]=(*left1)[0]+1;
right2 = new MpdZdcDigiId_t (right1->begin(),right1->end());
(*right2)[0] = (*right1)[0]+1;
fVolToDigiIdMap[*left1]=*right1;
fVolToDigiIdMap[*left2]=*right2;
}
return kTRUE;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::CreateVolInfoCopyElements (MpdZdcDigiId_t* right, MpdZdcVolInfo_t *volInfo )
{
if (!fPasNodes)
return kFALSE;
FairGeoNode *nod1 =(FairGeoNode*)fPasNodes->At(fPasNodes->GetEntries()-2);
if (!nod1)
return kFALSE;
Int_t moduleID,nModules;
TString lm_name = nod1->getName();
TString last_module_number (&(lm_name[lm_name.Last('#')+1]));
nModules = last_module_number.Atoi();
for (moduleID=1; moduleID<nModules; moduleID++) {
nod1 = (FairGeoNode*) fPasNodes->At(fPasNodes->GetEntries()-2 - nModules+moduleID);
FairGeoVector pos= nod1->getLabTransform()->getTranslation();
MpdZdcVolInfo_t *volInfo1 = new MpdZdcVolInfo_t ((*volInfo).begin(),(*volInfo).end());
(*volInfo1)[0]=pos.getValues(0); // X [cm]
(*volInfo1)[1]=pos.getValues(1); // Y [cm]
MpdZdcDigiId_t *right1 = new MpdZdcDigiId_t (right->begin(),right->end());
(*right1)[1] = (*right)[1]+moduleID;
MpdZdcDigiId_t *right2 = new MpdZdcDigiId_t (right1->begin(),right1->end());
(*right2)[0] = (*right1)[0]+1;
MpdZdcVolInfo_t *volInfo2 = new MpdZdcVolInfo_t (*volInfo1);
(*volInfo2)[2]=-(*volInfo2)[2]; // Z [cm]
fDigiToVolInfoMap[*right1]=volInfo1;
fDigiToVolInfoMap[*right2]=volInfo2;
}
return kTRUE;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::InitPsd (MpdZdcPsdGeoPar* geoPar, MpdZdcPsdDigiPar* digiPar, Int_t pVerbose)
{
if (!fYesPsd) {
if (!fInitialized) {
cout << "-W- MpdZdcDigiScheme::InitPsd: "
<< "Init basic ZDC first!" << endl;
return kFALSE;
}
fYesPsd=kTRUE;
if ( ! geoPar ) {
cout << "-W- MpdZdcDigiScheme::InitPsd: "
<< "No geometry parameters available!" << endl;
return kFALSE;
}
if ( ! digiPar ) {
cout << "-W- MpdZdcDigiScheme::InitPsd: "
<< "No digitization parameters available!" << endl;
return kFALSE;
}
fZdcPsdDigiPar = digiPar;
TObjArray* sensNodes;
sensNodes = geoPar->GetGeoSensitiveNodes();
if (!sensNodes) {
cout << "-W- MpdZdcDigiScheme::InitPsd: "
<< "No sensitive nodes available!" << endl;
return kFALSE;
}
AddNodes (sensNodes, kZDC+2, kTRUE, pVerbose); // kZDC+2 - hard-coded global ZDC_PSD detector number
CalcDimensions (kZDC+2,Nx_psd,Ny_psd,Nz_psd);
fYesPsd = kTRUE;
}
return kTRUE;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::GetVolCenterXYZ (MpdZdcDigiId_t* pDigiID, Double_t &x, Double_t &y,Double_t &z)
{
if (!pDigiID)
return kFALSE;
if (fDigiToVolInfoMap.find(*pDigiID)==fDigiToVolInfoMap.end())
return kFALSE;
else {
MpdZdcVolInfo_t* volInfo = fDigiToVolInfoMap[*pDigiID];
if (volInfo) {
x=(*volInfo)[0];
y=(*volInfo)[1];
z=(*volInfo)[2];
return kTRUE;
}
else
return kFALSE;
}
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::GetVolDxDyDz (MpdZdcDigiId_t* pDigiID, Double_t &Dx, Double_t &Dy, Double_t &Dz)
{
if (!pDigiID)
return kFALSE;
if (fDigiToVolInfoMap.find(*pDigiID)==fDigiToVolInfoMap.end())
return kFALSE;
else {
MpdZdcVolInfo_t* volInfo = fDigiToVolInfoMap[*pDigiID];
if (volInfo) {
Dx=(*volInfo)[3];
Dy=(*volInfo)[4];
Dz=(*volInfo)[5];
return kTRUE;
}
else
return kFALSE;
}
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::IsVolumeExist (MpdZdcVolId_t* pVolId)
{
if (!pVolId)
return kFALSE;
else
return (!(fVolToDigiIdMap.find(*pVolId)==fVolToDigiIdMap.end()));
}
// -------------------------------------------------------------------------
MpdZdcDigiId_t MpdZdcDigiScheme::GetDigiId (MpdZdcVolId_t* pVolId)
{
static const MpdZdcDigiId_t not_found (4,-1);
if (IsVolumeExist(pVolId))
return fVolToDigiIdMap[*pVolId];
else
return not_found;
}
// -------------------------------------------------------------------------
Int_t MpdZdcDigiScheme::GetDetectorID (MpdZdcVolId_t* pVolId)
{
MpdZdcDigiId_t digiID = GetDigiId (pVolId);
// return digiID.first;
return digiID[0];
}
// -------------------------------------------------------------------------
Int_t MpdZdcDigiScheme::GetChannelID (MpdZdcVolId_t* pVolId)
{
MpdZdcDigiId_t digiID = GetDigiId (pVolId);
// return digiID.second;
return digiID[2];
}
// -------------------------------------------------------------------------
MpdZdcVolInfo_t* MpdZdcDigiScheme::GetVolInfo(MpdZdcVolId_t* pVolId)
{
if (IsVolumeExist(pVolId)) {
MpdZdcDigiId_t pDigiID = GetDigiId(pVolId);
if (fDigiToVolInfoMap.find(pDigiID)==fDigiToVolInfoMap.end())
return NULL;
else
return fDigiToVolInfoMap[pDigiID];
}
else
return NULL;
}
// -------------------------------------------------------------------------
void MpdZdcDigiScheme::PrintVolume (Int_t volID, Int_t copyNo, Int_t copyNoMother, Int_t copyNoMotherMother)
{
Int_t content[]={copyNoMotherMother,copyNoMother,volID,copyNo};
MpdZdcVolId_t pVolId (content,content+sizeof(content)/sizeof(Int_t));
MpdZdcDigiId_t pDigiID = GetDigiId(&pVolId);
cout << " MpdZdc Volume: " << copyNoMotherMother << "," << copyNoMother<< "," << volID<< "," << copyNo <<
" DigiID: " << pDigiID[0] << "," << pDigiID[1]<< "," << pDigiID[2] ;
MpdZdcVolInfo_t* pVolInfo = GetVolInfo (&pVolId);
if (pVolInfo)
cout << " X,Y,Z [cm]: " << (*pVolInfo)[0]<< "," << (*pVolInfo)[1]<< "," << (*pVolInfo)[2]<<
" Dx,Dy,Dz [cm]: " << (*pVolInfo)[3]<< "," << (*pVolInfo)[4]<< "," << (*pVolInfo)[5] ;
cout << endl;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::CalcDimensions (Int_t pGlobalDetectorNumber, Int_t &nx, Int_t &ny, Int_t &nz)
{
if (fDigiToVolInfoMap.empty())
return kFALSE;
Bool_t result = kFALSE;
std::map<MpdZdcDigiId_t,MpdZdcVolInfo_t*>::iterator it;
std::map<Double_t,Int_t> xmap, ymap, zmap;
Double_t x,y,z;
nx = ny = nz = 0;
for ( it=fDigiToVolInfoMap.begin() ; it != fDigiToVolInfoMap.end(); ++it ) {
// cout << ". ";
// if ((*it).first.first==pGlobalDetectorNumber) {
if ((*it).first[0]==1) {
result = kTRUE;
x = (*((*it).second))[0];
if (xmap.count(x))
xmap[x]= xmap[x]+1;
else
xmap[x]= 1;
y = (*((*it).second))[1];
if (ymap.count(y))
ymap[y]= ymap[y]+1;
else
ymap[y]= 1;
z = (*((*it).second))[2];
if (zmap.count(z))
zmap[z]= zmap[z]+1;
else
zmap[z]= 1;
}
}
nx = xmap.size();
ny = ymap.size();
nz = zmap.size();
return result;
}
// -------------------------------------------------------------------------
void MpdZdcDigiScheme::GetZdcDimensions (Int_t &nx, Int_t &ny, Int_t &nz)
{
nx=Nx; ny=Ny; nz=Nz;
}
// -------------------------------------------------------------------------
void MpdZdcDigiScheme::GetZdcPsdDimensions (Int_t &nx_psd, Int_t &ny_psd, Int_t &nz_psd)
{
nx_psd=Nx_psd; ny_psd=Ny_psd; nz_psd=Nz_psd;
}
// -------------------------------------------------------------------------
MpdZdcDigiId_t MpdZdcDigiScheme::GetDigiIdFromCoords (Double_t x, Double_t y, Double_t z)
{
Int_t content[]={-1,-1,-1,-1};
MpdZdcVolId_t resultmc (content,content+sizeof(content)/sizeof(Int_t));
MpdZdcDigiId_t result (-1,-1);
if (gGeoManager) {
TGeoNode *tgn = gGeoManager->FindNode(x,y,z);
if (tgn) {
resultmc[0] = 1*(z>0)+2*(z<0);
resultmc[1] = tgn->GetMotherVolume()->GetNumber();
resultmc[2] = tgn->GetVolume()->GetNumber();
resultmc[3] = tgn->GetNumber();
if (fVolToDigiIdMap.find(resultmc)!=fVolToDigiIdMap.end())
result = fVolToDigiIdMap[resultmc];
}
}
return result;
}
// -------------------------------------------------------------------------
MpdZdcDigiId_t MpdZdcDigiScheme::GetDigiIdFromVolumeData (Int_t pMcVolumeNumber, Int_t pMcCopyNumber,
Int_t pMotherCopyNumber, Int_t pMotherMotherCopyNumber)
{
Int_t content[]={pMotherMotherCopyNumber,pMotherCopyNumber,pMcVolumeNumber,pMcCopyNumber};
MpdZdcVolId_t pVolId (content,content+sizeof(content)/sizeof(Int_t));
MpdZdcDigiId_t digiID = GetDigiId (&pVolId);
return digiID;
}
// -------------------------------------------------------------------------
void MpdZdcDigiScheme::SplitDigiID (MpdZdcDigiId_t digiID, Int_t &detID, Int_t &modID, Int_t &chanID)
{
detID = digiID[0];
modID = digiID[1];
chanID = digiID[2];
}
// -------------------------------------------------------------------------
void MpdZdcDigiScheme::Print()
{
cout << "*********************************************" << endl;
cout << "*** MpdZdcDigiScheme:" << endl;
cout << " MpdZdc Nx,Ny,Nz: " << Nx << "," << Ny<< "," << Nz<< " YesPsd: " << fYesPsd;
if (fYesPsd)
cout << " MpdZdcPsd Nx_psd,Ny_psd,Nz_psd: " << Nx_psd << "," << Ny_psd<< "," << Nz_psd;
cout << endl;
std::map<MpdZdcVolId_t,MpdZdcDigiId_t>::iterator it;
for ( it=fVolToDigiIdMap.begin() ; it != fVolToDigiIdMap.end(); ++it)
PrintVolume((*it).first[2],(*it).first[3], (*it).first[1], (*it).first[0]);
cout << "*********************************************" << endl;
}
// -------------------------------------------------------------------------
Bool_t MpdZdcDigiScheme::GetDetIdModIdChanId (Int_t pMcVolumeNumber, Int_t pMcCopyNumber, Int_t pMotherCopyNumber, Int_t pMotherMotherCopyNumber, Int_t &pDetId, Int_t &pChanId, Int_t &pModId)
{
Int_t content[]={pMotherMotherCopyNumber,pMotherCopyNumber,pMcVolumeNumber,pMcCopyNumber};
MpdZdcVolId_t pVolId (content,content+sizeof(content)/sizeof(Int_t));
MpdZdcDigiId_t digiID = GetDigiId (&pVolId);
pDetId = digiID[0];
pModId = digiID[1];
pChanId = digiID[2];
return kTRUE;
}
// -------------------------------------------------------------------------
ClassImp(MpdZdcDigiScheme)
|
7eeb04454f2d18835a15c6f763cba75ef57239e3
|
22070e9023fddefd63f0c0218df3b6cf6c98b2cd
|
/d04/ex03/Cure.cpp
|
0ac3bac1be0cb87138e40ef7e2511e0f1bb30b4f
|
[] |
no_license
|
vpopovyc/piscine-cpp
|
f6ff5f9e41a14defa2c17f1dfcc83fe0073571bf
|
ecaf0ca8da1c645daa59f46b16cd5c72d0f029be
|
refs/heads/master
| 2020-03-11T04:54:12.224844
| 2018-04-16T18:29:49
| 2018-04-16T18:29:49
| 129,788,101
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,438
|
cpp
|
Cure.cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cure.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vpopovyc <vpopovyc@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/26 15:56:16 by vpopovyc #+# #+# */
/* Updated: 2017/06/26 16:15:29 by vpopovyc ### ########.fr */
/* */
/* ************************************************************************** */
#include "Cure.hpp"
Cure::Cure(void) : AMateria("cure") {
}
Cure::~Cure(void){
std::cout << "~ Cure materia dissapeared ~" << std::endl;
}
Cure::Cure(const Cure & copy) : AMateria(copy) {
}
Cure& Cure::operator=(const Cure& rvalue)
{
return (static_cast<Cure&>(AMateria::operator=(rvalue)));
}
void Cure::use(ICharacter & target) {
std::cout << "* heals " << target.get_name() << "’s wounds *" << std::endl;
eval_materia();
}
Cure* Cure::clone(void) const
{
return new Cure(*this);
}
|
6cdd7069529db80ff597a889e89b77de33590ba8
|
976004c9f4426106d7ca59db25755d4d574b8025
|
/algorithms/hilbert_maps/dsgd/regrs/hm_dsgd_regr_doubly.h
|
87fb251cb285accc8233f96b71d15f9a4ae401e3
|
[] |
no_license
|
peterzxli/cvpp
|
18a90c23baaaa07a32b2aafdb25d6ae78a1768c0
|
3b73cfce99dc4b5908cd6cb7898ce5ef1e336dce
|
refs/heads/master
| 2022-12-05T07:23:20.488638
| 2020-08-11T20:08:10
| 2020-08-11T20:08:10
| 286,062,971
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,771
|
h
|
hm_dsgd_regr_doubly.h
|
#ifndef HM_DSGD_REGRESSOR_DOUBLY_H
#define HM_DSGD_REGRESSOR_DOUBLY_H
#include "./hm_dsgd_regr_base.h"
namespace cvpp
{
class HMregrDoubly : public HMregrBase
{
protected:
public:
HMregrDoubly() : HMregrBase()
{
}
int ridx( const int& i ) const
{
return r * n + i * f;
}
Matd kernel( const Matd& X , const int& ri ) const
{
randomise( ridx(ri) );
Matd Z = MatXXd( d , ff ).setRandn( 0 , sqrt( 2.0 * ls ) );
return feat->calc( X * Z ) / sqrt( ff );
}
const void train()
{
Timer timer;
double step = step0 / ( 1.0 + step1 );
forLOOPi( iters )
{
int bidx = ( i * b ) % t;
int widx = ( i * f ) % n;
int ii = std::min( i , nf );
Xbt = Xtr.r( bidx , b );
Matd mf = query( Xbt , ii );
Matd phi = kernel( Xbt , i % nf );
Matd max = mf.maxCols();
Matd softmax = ( mf - max ).exp();
softmax /= softmax.sumCols();
Matd K = ( phi.t() * phi ) / b;
Matd E = softmax - trainY.r( bidx , b );
wgt.r( widx , f ) += - step * ( ( K + I ).bslash( ( phi.t() * E ) / b ) );
if( reg > 1e-6 )
wgt.ru( ii * f ) *= ( 1 - step * reg );
disp( "*****************************************************************" ,
i , iters , widx , widx + f , n , bidx , bidx + b , t , timer.tick() );
}
}
Matd query( const Matd& X , int iters = -1 ) const
{
if( iters == -1 ) iters = nf;
Matd mf = MatZEROSd( X.r() , k );
forLOOPj( iters ) mf += kernel( X , j % nf ) * wgt.r( ( j * f ) % n , f ) ;
return mf;
}
};
}
#endif
|
b0607cafc30858764c460d01984e49d080396c4e
|
b22c189f38b8da715e70b76be3d9c0f3bb921f63
|
/DATA STRUCTURES AND ALGORITHMS/count_numbers.cpp
|
bf6641c74d6afaed0e946db6c0b6fef4d332cb7a
|
[] |
no_license
|
Bikubisw/Coding
|
108f1048bc54bbd526f2f3abea21bd17bb8e7975
|
274c50caab15f10663a83ad352fc5ddb04b9e236
|
refs/heads/master
| 2023-04-20T11:09:32.555814
| 2021-05-22T20:29:45
| 2021-05-22T20:29:45
| 280,332,695
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 213
|
cpp
|
count_numbers.cpp
|
#include <iostream>
using namespace std;
int count(int n){
if(n==0){
return 0;
}
int smallans=count(n/10);
return 1+smallans;
}
int main(){
int n;
cin>>n;
int ans=count(n);
cout<<ans<<endl;
return 0;
}
|
971327602e5598685cd8c4ce828a661a1972b700
|
c3f9cee452ef09d34b1a166bc4700cd06432bd4b
|
/Src/DevAssistCore/Include/FileRepository.h
|
03e0f32bcbe6a8738d2aa6b41382f0b0036a7984
|
[] |
no_license
|
divineaugustine/QuickAssist
|
d8f62d31e779020181184573499e7c56a0b1cdf5
|
b88614d62f23ba5cab1254007b3bb99257706b93
|
refs/heads/master
| 2021-01-20T06:57:04.965227
| 2015-08-07T08:06:50
| 2015-08-07T08:06:50
| 36,303,639
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,126
|
h
|
FileRepository.h
|
#pragma once
#include <Core\Repository.h>
#include <map>
#include <vector>
class FileInfoImpl;
class DirectoryInfoImpl;
// Folder information will be stored after removing the configurable path
class FileRepository : public RepositoryBase
{
public:
DirectoryInfo* AddFolder( const std::wstring& strFolder_i );
void AddFile( const std::wstring& strFile_i, DirectoryInfo* pDirInfo );
bool Serialize( SerialStrategyBase* pSerialStrategy );
bool Deserialize( SerialStrategyBase* pSerialStrategy );
bool WriteToFile( const std::wstring& strDestFile_i );
bool ReadFromFile( const std::wstring& strDestFile_i );
virtual std::shared_ptr<FileIterator> CreateFileIterator();
FileInfo* GetFile( const std::wstring& FileName_i );
void ResetContents();
FileRepository();
~FileRepository();
private:
FileRepository(const FileRepository& src);
FileRepository& operator=(const FileRepository& src);
void ClearAll();
private:
// std::map<std::wstring,std::vector<unsigned int>*> mFileRep;
std::map<std::wstring,FileInfoImpl*> mFileRep;
std::vector<DirectoryInfoImpl*> mFolderRep;
unsigned int mnFolderCounter;
};
|
e3d31d6c9a8c1e05d2fbb4a2b1715cfcd3ff7409
|
c4d51d07bfa867a2c5f1c0ffb93a375ee9bf3409
|
/src/layer/InnerProduct_param.h
|
cadd57cae41d50ea9c56c3f1c57d613365dbd8f7
|
[] |
no_license
|
ganyuhuoguang/ncnn-tool
|
c7a56307ac8f662b08744527bca61b1ff813a664
|
5be6968a68437cc624b07e7a7784ceef519975cd
|
refs/heads/master
| 2023-01-04T06:29:38.488822
| 2020-10-15T07:03:38
| 2020-10-15T07:03:38
| 261,683,959
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 998
|
h
|
InnerProduct_param.h
|
/*
* InnerProduct_param.h
*
* Created on: Jun 17, 2019
* Author: doyle
*/
#ifndef LAYER_INNERPRODUCT_PARAM_H_
#define LAYER_INNERPRODUCT_PARAM_H_
namespace tmnet
{
class FcParam
{
public:
FcParam();
~FcParam();
unsigned int num_output;
unsigned int bias_term;
unsigned int data_size;
unsigned long long uiWeightAddr;
unsigned long long uiBiasAddr;
//register
unsigned long long uiRegInDataSrcAddr; //R/W
unsigned long long uiRegWDataSrcAddr; //R/W
unsigned int uiRegInDataClassesLength; //R/W
unsigned int uiRegWDataClassesLength; //R/W
unsigned long long uiRegOutDataDstAddr; //R/W
unsigned int uiRegFcStart; //R/W
unsigned int uiRegFcFinish; //R
unsigned int uiRegOutData; //R
unsigned long long uiRegBiasSrcAddr; //R/W
unsigned int uiRegOutputNumber; //R/W
};
}
#endif /* LAYER_INNERPRODUCT_PARAM_H_ */
|
128894b7342d6fdac152ea59c0e2becb43a42ee6
|
3b41b207a3090f5b06230dfa83bc31ee59f6abf4
|
/src/SkipList.cpp
|
a4d874aa0e364ffb4ce876c3d44de1a802997fe8
|
[] |
no_license
|
brookiehcookie/spraylistMidterm
|
8907505aa85d93752a789a11dae8f0e7c8a13668
|
f8a881ee549be5480050a6c51e10c0584c3f9887
|
refs/heads/master
| 2021-04-26T22:50:33.106678
| 2018-04-24T03:10:12
| 2018-04-24T03:10:12
| 124,153,924
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,304
|
cpp
|
SkipList.cpp
|
#include <iostream>
#include <vector>
#include <cmath>
#include <atomic>
#include <climits>
#include <ctime>
#include <cstdlib>
#include <string>
#include <random>
#include <functional>
// for performance testing
#include <iomanip>
#include <chrono>
#include <pthread.h>
// Really quick down-and dirty boolean
#define bool int
#define true (1)
#define false (0)
using namespace std;
#define MAX_LEVEL 12
const int LEVELS_TO_DESCEND = 1;
/**************************************************/
/**
Simulate Java's AtomicMarkableReference
This uses the least significant bit of a pointer
as the mark. This creates a restriction on the kinds
of pointers you can use, but most of the time
it should be fine.
References:
http://www.cnblogs.com/zxh1210603696/p/3721460.html
https://stackoverflow.com/questions/40247249/what-is-the-c-11-atomic-library-equivalent-of-javas-atomicmarkablereferencet
*/
template <class T>
class AtomicMarkableReference {
private:
std::atomic<T> ref;
const uintptr_t UNMARKED = 0;
const uintptr_t MARKED = 1;
public:
AtomicMarkableReference(T p, bool mark);
AtomicMarkableReference(const AtomicMarkableReference &a);
operator = (const AtomicMarkableReference &a);
T getRef() const;
bool isMarked() const;
T get(bool &b) const;
bool compareAndSet(T expectedValue, T newValue, bool expectedMark, bool newMark);
void set(T newValue, bool newMark);
bool attemptMark(T expectedValue, bool newMark);
};
template <class T>
AtomicMarkableReference<T>::AtomicMarkableReference(T p, bool mark) {
this->ref.store((T) ((uintptr_t) p | (uintptr_t) mark));
}
template <class T>
AtomicMarkableReference<T>::AtomicMarkableReference(const AtomicMarkableReference &a) {
this->ref.store(a.ref.load());
}
template <class T>
AtomicMarkableReference<T>::operator = (const AtomicMarkableReference &a) {
if (*this != a) {
this->ref.store(a.ref.load());
return *this;
}
}
template <class T>
T AtomicMarkableReference<T>::getRef() const {
T p = this->ref.load();
return (bool) ((uintptr_t) p & MARKED) ? (T)((uintptr_t)(p) & ~MARKED) : p;
}
template <class T>
bool AtomicMarkableReference<T>::isMarked() const {
T p = this->ref.load();
return (bool) ((uintptr_t) p & MARKED);
}
template <class T>
T AtomicMarkableReference<T>::get(bool &b) const {
T p = this->ref.load();
b = (bool) ((uintptr_t) p & MARKED);
return b ? (T) ((uintptr_t)(p) & ~MARKED) : p;
}
template <class T>
bool AtomicMarkableReference<T>::compareAndSet(T expectedValue, T newValue, bool expectedMark, bool newMark) {
T p = this->ref.load();
bool b = (bool)((uintptr_t) p & MARKED);
if (b == expectedMark) {
expectedValue = (T)((uintptr_t) expectedValue | (uintptr_t) b);
return this->ref.compare_exchange_strong(expectedValue, (T) ((uintptr_t) newValue | (uintptr_t) newMark));
}
return false;
}
template <class T>
void AtomicMarkableReference<T>::set(T newValue, bool newMark) {
newValue = (T) ((uintptr_t) newValue | (uintptr_t) newMark);
this->ref.exchange(newValue);
}
template <class T>
bool AtomicMarkableReference<T>::attemptMark(T expectedValue, bool newMark) {
T newValue = (T) ((uintptr_t) expectedValue | (uintptr_t) newMark);
expectedValue = isMarked() ? (T) ((uintptr_t) expectedValue | MARKED) : expectedValue;
return this->ref.compare_exchange_strong(expectedValue, newValue);
}
/**************************************************/
template <typename T>
class SkipListNode {
public:
T value;
int key;
int topLevel;
vector<AtomicMarkableReference<SkipListNode<T>*>*> next;
int flag = 0;
SkipListNode(int _key);
SkipListNode(T x, int height);
~SkipListNode();
char print() {
if (flag == 1) {
cout << "HEAD";
return '\0';
}
if (flag == 2) {
cout << "TAIL";
return '\0';
}
/*if (value != NULL)
cout << *value;
else
cout << "null";*/
cout << value;
return '\0';
}
};
/**
SkipListNode constructor for sentinel nodes
//SkipListNode constructor adapted from skipListNodeCreate
*/
template <typename T>
SkipListNode<T>::SkipListNode(int _key) {
//value = NULL;
key = _key;
//next = new vector<AtomicMarkableReference<SkipListNode<T>*>>();
//next.reserve(MAX_LEVEL + 1);
//next = new AtomicMarkableReference<SkipListNode<T>>[MAX_LEVEL + 1];
for (int i = 0; i < MAX_LEVEL + 1; i++)
next.push_back(new AtomicMarkableReference<SkipListNode<T>*>(NULL, false));
topLevel = MAX_LEVEL;
}
/**
SkipListNode constructor for ordinary nodes
*/
template <typename T>
SkipListNode<T>::SkipListNode(T x, int height) {
value = x;
key = std::hash<T>{}(x);
//cout << "created node with value " << value << " and key " << key << " with height " << height << endl;
for (int i = 0; i < height + 1; i++)
next.push_back(new AtomicMarkableReference<SkipListNode<T>*>(NULL, false));
topLevel = height;
}
/**
SkipListNode deconstructor adapted from skipListNodeDestroy
*/
template <typename T>
SkipListNode<T>::~SkipListNode() {
// TODO: memory leaks here WRT vector?
}
/**************************************************/
template <typename T>
class SkipList {
public:
// The number of elements in the SkipList
int size;
// The head node of the SkipList (data is not meaningufl)
// The height of the head node is the height of the skip list.
SkipListNode<T> *head = NULL;
SkipListNode<T> *tail = NULL;
static int getMaxHeight(int size);
static int generateRandomHeight(int maxHeight);
SkipList();
SkipList(int height);
~SkipList();
void init(int height);
int height();
bool find(T x, SkipListNode<T> *preds[], SkipListNode<T> *succs[]);
bool add(T x);
bool addH(T x, int height);
bool contains(T x);
bool remove(T x);
void print();
};
template <typename T>
int SkipList<T>::getMaxHeight(int size) {
if (size == 0)
return 1;
return 1 + log(size) / log(2);
}
/**
Generate a random max height for a node
50% chance of 1
25% chance of 2
12.5% chance of 3
etc, with a given cap
*/
template <typename T>
int SkipList<T>::generateRandomHeight(int maxHeight) {
int h = 1;
while (rand() % 2 == 0 && h < maxHeight)
h++;
if (h == maxHeight) h--;
return h;
}
/**
Constructor for SkipList
Adapted from skipLsitCreate
*/
template <typename T>
SkipList<T>::SkipList() {
this->init(MAX_LEVEL);
}
/**
Constructor for SkipList given specific height
Adapted from skipLsitCreateH
*/
template <typename T>
SkipList<T>::SkipList(int height) {
this->init(height);
}
/**
Initialize a SkipList with head node of given height
*/
template <typename T>
void SkipList<T>::init(int height) {
size = 0;
head = new SkipListNode<T>(height + 1);
//head->value = NULL;
head->flag = 1;
head->key = INT_MIN;
tail = new SkipListNode<T>(height + 1);
//tail->value = NULL;
tail->flag = 2;
tail->key = INT_MAX;
for (int level = 0; level < head->next.size(); level++)
head->next.at(level)->set(tail, false);
}
/**
Deconstructor for SkipList
*/
template <typename T>
SkipList<T>::~SkipList () {
// TODO: memory leaks with head and tail
//delete head;
//delete tail;
// probably also need to free all the other nodes
}
/**
Get height of SkipList, which is defined to be
the height of the head node
*/
template <typename T>
int SkipList<T>::height() {
return head->topLevel;
}
/**
The find algorithm
*/
template <typename T>
bool SkipList<T>::find(T x, SkipListNode<T> *preds[], SkipListNode<T> *succs[]) {
int bottomLevel = 0;
int key = std::hash<T>{}(x);
bool marked[] = {false};
bool snip;
SkipListNode<T> *pred = NULL;
SkipListNode<T> *curr = NULL;
SkipListNode<T> *succ = NULL;
// retry
bool retry;
while (true) {
retry = false;
pred = head;
for (int level = MAX_LEVEL - 1; level >= bottomLevel; level--) {
curr = pred->next.at(level)->getRef();
while (true) {
succ = curr->next.at(level)->get(*marked);
while (marked[0]) {
snip = pred->next.at(level)->compareAndSet(curr, succ, false, false);
if (!snip) {
retry = true;
break;
}
curr = pred->next.at(level)->getRef();
succ = curr->next.at(level)->get(*marked);
}
if (retry) break;
if (curr->key < key) {
pred = curr; curr = succ;
} else {
break;
}
}
if (retry) break;
preds[level] = pred;
succs[level] = curr;
}
if (retry) continue;
return curr->key == key;
}
}
/**
Add data to the SkipList
Adapted from skipListInsert
*/
template <typename T>
bool SkipList<T>::add(T x) {
return this->addH(x, SkipList<T>::generateRandomHeight(this->height()));
}
/**
Add data to the SkipList in new node with given height
Adapted from skipListInsertH
*/
template <typename T>
bool SkipList<T>::addH(T x, int height) {
int topLevel = height;
int bottomLevel = 0;
SkipListNode<T> *preds[MAX_LEVEL + 1];
SkipListNode<T> *succs[MAX_LEVEL + 1];
while (true) {
bool found = find(x, preds, succs);
if (found) {
return false;
} else {
SkipListNode<T> *newNode = new SkipListNode<T>(x, topLevel);
for (int level = bottomLevel; level <= topLevel; level++) {
newNode->next.at(level)->set(succs[level], false);
}
SkipListNode<T> *pred = preds[bottomLevel];
SkipListNode<T> *succ = succs[bottomLevel];
newNode->next.at(bottomLevel)->set(succ, false);
if (!pred->next.at(bottomLevel)->compareAndSet(succ, newNode, false, false)) {
continue;
}
for (int level = bottomLevel+1; level <= topLevel; level++) {
while (true) {
pred = preds[level];
succ = succs[level];
if (pred->next.at(level)->compareAndSet(succ, newNode, false, false))
break;
find(x, preds, succs);
}
}
return true;
}
}
}
/**
Return whether or not the given data exists in the SkipList
Adapted from skipListContains
*/
template <typename T>
bool SkipList<T>::contains(T x) {
int bottomLevel = 0;
int key = std::hash<T>{}(x);
bool marked[] = {false};
SkipListNode<T> *pred = head;
SkipListNode<T> *curr = NULL;
SkipListNode<T> *succ = NULL;
for (int level = MAX_LEVEL; level >= bottomLevel; level--) {
curr = pred->next.at(level)->getRef();
while (true) {
succ = curr->next.at(level)->get(*marked);
while (marked[0]) {
curr = pred->next.at(level)->getRef();
succ = curr->next.at(level)->get(*marked);
}
if (curr->key < key) {
pred = curr;
curr = succ;
} else {
break;
}
}
}
return curr->key == key;
}
/**
Remove given data from the SkipList
Does not throw an error if given data does not exist
Adapted from skipListDelete
*/
template <typename T>
bool SkipList<T>::remove(T x) {
int bottomLevel = 0;
SkipListNode<T> *preds[MAX_LEVEL + 1];
SkipListNode<T> *succs[MAX_LEVEL + 1];
SkipListNode<T> *succ;
while (true) {
bool found = find(x, preds, succs);
if (!found) {
return false;
} else {
SkipListNode<T> *nodeToRemove = succs[bottomLevel];
for (int level = nodeToRemove->topLevel; level >= bottomLevel+1; level--) {
bool marked[] = {false};
succ = nodeToRemove->next.at(level)->get(*marked);
while (!marked[0]) {
nodeToRemove->next.at(level)->attemptMark(succ, true);
succ = nodeToRemove->next.at(level)->get(*marked);
}
}
bool marked[] = {false};
succ = nodeToRemove->next.at(bottomLevel)->get(*marked);
while (true) {
bool iMarkedIt = nodeToRemove->next.at(bottomLevel)->compareAndSet(succ, succ, false, true);
succ = succs[bottomLevel]->next.at(bottomLevel)->get(*marked);
if (iMarkedIt) {
find(x, preds, succs);
return true;
}
else if (marked[0]) return false;
}
}
}
}
/**
Adapted from skipListPrint
*/
template <typename T>
void SkipList<T>::print() {
int i;
SkipListNode<T> *nodey = head;
SkipListNode<T> *nodeyNext;
while (nodey != NULL) {
cout << nodey->print();
for (i = 0; i < nodey->topLevel; i++) {
cout << "\t";
nodeyNext = nodey->next.at(i)->getRef();
if (nodeyNext != NULL) {
cout << '(' << nodeyNext->print() << ')';
} else {
cout << "NULL";
}
}
cout << endl;
nodey = nodey->next.at(0)->getRef();
}
}
/**************************************************/
template <typename T>
class SprayList : public SkipList<T> {
public:
T spray(int beginHeight, int walkLength, int descendAmount);
};
/**
An implementation of the spray algorithm
*/
template <typename T>
T SprayList<T>::spray(int beginHeight, int walkLength, int descendAmount) {
SkipListNode<T> *node = this->head;
SkipListNode<T> *next;
int level = beginHeight;
int jumps;
// Simulate a random walk
// Continue until we bottom-out of the skip list
while (level >= 0) {
// Decide on some random number of jumps
jumps = rand() % (walkLength + 1);
// Make the jumps so long as we don't hit the tail
for (; jumps >= 0; jumps--) {
next = node->next.at(level)->getRef();
if (next != NULL && next != this->tail) {
node = next;
}
}
// Descend
level -= descendAmount;
}
return node->value;
}
/**************************************************/
/**
Skip List Testing
In this section of code, we define functions that test
the capabilities of the SkipList<T> class. This was used
to verify that our implementation of a current skip list
was functioning properly.
*/
#define THREADS_ADD 12
#define THREADS_REMOVE 12
#define NUMS_PER_THREAD 5000
typedef struct thread_data {
int thread_id;
SkipList<int> *skippy;
} thread_data;
void *skipListAddThread(void *threadarg) {
thread_data *my_data = (thread_data *) threadarg;
SkipList<int> *skippy = my_data->skippy;
// Generate nums from 0 to NUMS_PER_THREAD
int nums[NUMS_PER_THREAD];
for (int i = 0; i < NUMS_PER_THREAD; i++)
nums[i] = i*THREADS_ADD + my_data->thread_id + 1;
// Scramble
int temp, j;
for (int i = 0; i < NUMS_PER_THREAD; i++) {
j = rand() % NUMS_PER_THREAD;
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
for (int i = 0; i < NUMS_PER_THREAD; i++) {
//cout << "add " << nums[i] << endl;
skippy->add(nums[i]);
cout << '#';
}
pthread_exit(NULL);
}
void *skipListRemoveThread(void *threadarg) {
thread_data *my_data = (thread_data *) threadarg;
SkipList<int> *skippy = my_data->skippy;
// Generate nums from 0 to NUMS_PER_THREAD
int nums[NUMS_PER_THREAD];
for (int i = 0; i < NUMS_PER_THREAD; i++)
nums[i] = i + my_data->thread_id*NUMS_PER_THREAD + 1;
// Scramble
int temp, j;
for (int i = 0; i < NUMS_PER_THREAD; i++) {
j = rand() % NUMS_PER_THREAD;
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
bool isRemoved[NUMS_PER_THREAD];
for (int i = 0; i < NUMS_PER_THREAD; i++)
isRemoved[i] = false;
int i = 0;
int count = 0;
while (count < NUMS_PER_THREAD) {
while (isRemoved[i]) i = ++i % NUMS_PER_THREAD;
if (skippy->remove(nums[i])) {
isRemoved[i] = true;
count++;
cout << ' ';
}
i++;
}
pthread_exit(NULL);
}
/**
Test the SkipList class by creating some adding and removing
threads. THREADS_ADD will
*/
void testSkipList() {
srand(time(NULL));
SkipList<int> *skippy = new SkipList<int>();
pthread_t threads_add[THREADS_ADD];
thread_data threadarg_add[THREADS_ADD];
pthread_t threads_rem[THREADS_REMOVE];
thread_data threadarg_rem[THREADS_REMOVE];
int rc;
// Start add threads
for (int i = 0; i < THREADS_ADD; i++) {
threadarg_add[i].thread_id = i;
threadarg_add[i].skippy = skippy;
rc = pthread_create(&threads_add[i], NULL, skipListAddThread, (void*) &threadarg_add[i]);
if (rc) {
cout << "Unable to create thread " << rc << endl;
exit(1);
}
}
// Start remove threads
for (int i = 0; i < THREADS_REMOVE; i++) {
threadarg_rem[i].thread_id = i;
threadarg_rem[i].skippy = skippy;
rc = pthread_create(&threads_rem[i], NULL, skipListRemoveThread, (void*) &threadarg_rem[i]);
if (rc) {
cout << "Unable to create thread " << rc << endl;
exit(1);
}
}
for (int i = 0; i < THREADS_ADD; i++) {
pthread_join(threads_add[i], NULL);
}
//cout << "All add threads complete" << endl;
for (int i = 0; i < THREADS_REMOVE; i++) {
pthread_join(threads_rem[i], NULL);
}
cout << endl;
skippy->print();
}
/**************************************************/
/*
SprayList performance testing
*/
#define SPRAYLIST_THREADS_ADD 16
#define SPRAYLIST_THREADS_REMOVE 16
#define SPRAYLIST_NUMS_PER_THREAD 12500
typedef struct thread_data2 {
int thread_id;
long result = 0;
SprayList<int> *skippy;
} thread_data2;
void *sprayListAddThread(void *threadarg) {
thread_data2 *my_data = (thread_data2 *) threadarg;
SprayList<int> *skippy = my_data->skippy;
// Generate nums from 0 to SPRAYLIST_NUMS_PER_THREAD
int nums[SPRAYLIST_NUMS_PER_THREAD];
for (int i = 0; i < SPRAYLIST_NUMS_PER_THREAD; i++)
nums[i] = i*SPRAYLIST_THREADS_ADD + my_data->thread_id + 1;
// Scramble
int temp, j;
for (int i = 0; i < SPRAYLIST_NUMS_PER_THREAD; i++) {
j = rand() % SPRAYLIST_NUMS_PER_THREAD;
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
long sum = 0;
for (int i = 0; i < SPRAYLIST_NUMS_PER_THREAD; i++) {
//cout << "add " << nums[i] << endl;
skippy->add(nums[i]);
sum += nums[i];
//cout << '#';
}
my_data->result = sum;
pthread_exit(NULL);
}
void *sprayListRemoveThread(void *threadarg) {
thread_data2 *my_data = (thread_data2 *) threadarg;
SprayList<int> *skippy = my_data->skippy;
int sum = 0;
for (int i = 0; i < SPRAYLIST_NUMS_PER_THREAD; i++) {
int v;
do {
v = skippy->spray(3, 2, 1);
} while (!skippy->remove(v));
//cout << ' ';
sum += v;
}
my_data->result = sum;
pthread_exit(NULL);
}
void testSprayPerformance() {
srand(time(NULL));
SprayList<int> *skippy = new SprayList<int>();
pthread_t threads_add[SPRAYLIST_THREADS_ADD];
thread_data2 threadarg_add[SPRAYLIST_THREADS_ADD];
pthread_t threads_rem[SPRAYLIST_THREADS_REMOVE];
thread_data2 threadarg_rem[SPRAYLIST_THREADS_REMOVE];
// START TIMER
std::clock_t c_start = std::clock();
auto t_start = std::chrono::high_resolution_clock::now();
int rc;
// Start add threads
for (int i = 0; i < SPRAYLIST_THREADS_ADD; i++) {
threadarg_add[i].thread_id = i;
threadarg_add[i].skippy = skippy;
threadarg_add[i].result = 0;
rc = pthread_create(&threads_add[i], NULL, sprayListAddThread, (void*) &threadarg_add[i]);
if (rc) {
cout << "Unable to create thread " << rc << endl;
exit(1);
}
}
// Start remove threads
for (int i = 0; i < SPRAYLIST_THREADS_REMOVE; i++) {
threadarg_rem[i].thread_id = i;
threadarg_rem[i].skippy = skippy;
threadarg_rem[i].result = 0;
rc = pthread_create(&threads_rem[i], NULL, sprayListRemoveThread, (void*) &threadarg_rem[i]);
if (rc) {
cout << "Unable to create thread " << rc << endl;
exit(1);
}
}
for (int i = 0; i < THREADS_ADD; i++) {
pthread_join(threads_add[i], NULL);
}
//cout << "All add threads complete" << endl;
for (int i = 0; i < THREADS_REMOVE; i++) {
pthread_join(threads_rem[i], NULL);
}
// STOP TIMER
std::clock_t c_end = std::clock();
auto t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed << std::setprecision(5) << "CPU time used: "
<< 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC << " ms\n"
<< "Wall clock time passed: "
<< std::chrono::duration<double, std::milli>(t_end-t_start).count()
<< " ms\n";
// Get the sum of each remove thread's sum
long sumAdd = 0;
for (int i = 0; i < SPRAYLIST_THREADS_REMOVE; i++) {
sumAdd += threadarg_add[i].result;
}
long sumRem = 0;
for (int i = 0; i < SPRAYLIST_THREADS_REMOVE; i++) {
sumRem += threadarg_rem[i].result;
}
// sumAdd and sumRem are the sums of all the numbers that the threads
// added or removed. If both are the same, then we know we added/removed
// the same numbers
cout << "added: " << sumAdd << endl;
cout << "removed: " << sumRem << endl;
}
/**************************************************/
#define NUM 20
void testSpray() {
int i, v;
int counts[NUM] = {0};
SprayList<int> *skippy = new SprayList<int>();
for (i = 0; i < NUM; i++) {
skippy->add(i);
}
skippy->print();
//cout << skippy->spray(skippy->height(), 1, 1);
for (i = 0; i < 100000; i++) {
v = skippy->spray(3, 2, 1);
//cout << "->" << v << endl;
counts[v]++;
}
cout << "counts:" << endl;
for (i = 0; i < NUM; i++) {
if (counts[i] > 0)
cout << " " << i << ":\t" << counts[i] << endl;
}
}
void testSpray2() {
}
/**************************************************/
int main(void) {
srand(time(NULL));
testSprayPerformance();
return 0;
}
|
117eb1cc6dab076aa877288127fe67b6ff4e9ba6
|
b265687ec069907072794a6fe745e50fdef327e8
|
/project3/Rupee.c++
|
6d6cc70c510ff9feed8949cf973073b41ab33c44
|
[] |
no_license
|
JayhawkZombie/EECS672
|
02756f8e48f20dd28314fdd04613725dbc02f96a
|
3e25ea9507a1039a1b3ec9059b7144de7cf6aabb
|
refs/heads/master
| 2018-01-08T04:20:30.923699
| 2015-11-25T06:07:46
| 2015-11-25T06:07:46
| 43,176,269
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,619
|
Rupee.c++
|
#include <iostream>
#include <math.h>
#include "Rupee.h"
#include "ShaderIF.h"
#include "ModelViewWithPhongLighting.h"
typedef float vec3[3];
/*
| P1 - points[0]
| P2 - points[1]
| P3 - points[2]
| P4 - points[3]
| T - points[4]
| B - points[5]
| V1 - points[6]
| V2 - points[7]
*/
GLuint Rupee::indexList[12][3] = {
{4, 1, 6} /* S1 */, {1, 0, 6} /* S2 */,
{0, 5, 6} /* S3 */, {5, 3, 6} /* S4 */,
{2, 3, 6} /* S5 */, {4, 2, 6} /* S6 */,
{4, 1, 7} /* S7 */, {1, 0, 7} /* S8 */,
{0, 5, 7} /* S9 */, {5, 3, 7} /* S10 */,
{2, 3, 7} /* S11 */, {4, 2, 7} /* S12 */
};
vec3 Rupee::ka = { 0.1745, 0.01175, 0.01175};
vec3 Rupee::kd = { 0.61424, 0.04136, 0.04136};
vec3 Rupee::ks = { 0.727811, 0.626959, 0.626959};
float Rupee::m = 76.8;
Rupee::Rupee(float P1[3], float P2[3], float P3[3], float P4[3], float c[]) :
displayRupeeEdges(false), displayRupeeFill(true)
{
points[0] = cryph::AffPoint(P1);
points[1] = cryph::AffPoint(P2);
points[2] = cryph::AffPoint(P3);
points[3] = cryph::AffPoint(P4);
colors[0] = c[0];
colors[1] = c[1];
colors[2] = c[2];
//The height and normals will be determined later
defineRupee();
}
Rupee::~Rupee()
{
glDeleteBuffers(12, ebo);
glDeleteBuffers(1, vbo);
glDeleteVertexArrays(1, vao);
}
void Rupee::defineRupee()
{
//Alright, there's a lot of work to do
//First, let's get the center point on the plane
cryph::AffPoint c1 = 0.5 * (points[1] + points[2]);
cryph::AffPoint c2 = 0.5 * (points[0] + points[3]);
cryph::AffPoint centerOfPlane = 0.5 * (c1 + c2);
upVectorParallelToPlane = cryph::AffVector(points[1] - points[0]);
upVectorParallelToPlane.normalize();
//Now we need a vector parallel to the plane to get the Top and Bottom points
cryph::AffVector v1(points[3] - points[0]);
cryph::AffVector v2(points[1] - points[0]);
//we also now need a vector perpendicular to the plane
upVectorPerpToPlane = v1.cross(v2);
upVectorPerpToPlane.normalize();
//What is the distance between the two points on each side of the rupee?
double distanceBetweenTopPoints = c1.distanceTo(c2);
height = distanceBetweenTopPoints / 2;
//Now we can get the Top and Bottom points of the rupee
points[4] = c1 + height * upVectorParallelToPlane;
points[5] = c2 - height * upVectorParallelToPlane;
//Now how thick is the rupee?
thickness = height / 2; //We'll see how it looks - may tweak later
//Now we can get the two points jutting out of the rupee
points[6] = centerOfPlane + thickness * upVectorPerpToPlane;
points[7] = centerOfPlane - thickness * upVectorPerpToPlane;
//std::cerr << "Thickness: " << thickness;
//Let's get xmin, xmax, etc...
xmin = xmax = ymin = ymax = zmin = zmax = 0;
for (int i = 0; i < 12; i++)
{
if (points[i].x < xmin)
xmin = points[i].x;
if (points[i].x > xmax)
xmax = points[i].x;
if (points[i].y < ymin)
ymin = points[i].y;
if (points[i].y > ymax)
ymax = points[i].y;
if (points[i].z < zmin)
zmin = points[i].z;
if (points[i].z > zmax)
zmax = points[i].z;
}
zmax *= 1.2;
//Alright...Now we have all 8 points, but now we need to compute 12 vectors!
//Let's get started...
//First face (top of rupee, top left hand corner) = (top - V1) cross (P2 - V1)
v1 = cryph::AffVector(points[4] - points[6]);
v2 = cryph::AffVector(points[1] - points[6]);
normals[0] = v1.cross(v2); normals[0].normalize();
//Second face - directly below first on the same side
v1 = cryph::AffVector(points[1] - points[6]);
v2 = cryph::AffVector(points[0] - points[6]);
normals[1] = v1.cross(v2); normals[1].normalize();
//Third face - bottom left corner of the front face
v1 = cryph::AffVector(points[0] - points[6]);
v2 = cryph::AffVector(points[5] - points[6]);
normals[2] = v1.cross(v2); normals[2].normalize();
//Fourth face - bottom right corner of the front face
v1 = cryph::AffVector(points[5] - points[6]);
v2 = cryph::AffVector(points[3] - points[6]);
normals[3] = v1.cross(v2); normals[3].normalize();
//Fifth face - middle of the right side of the front face
v1 = cryph::AffVector(points[3] - points[6]);
v2 = cryph::AffVector(points[2] - points[6]);
normals[4] = v1.cross(v2); normals[4].normalize();
//Sixth face - top right corner of the front face
v1 = cryph::AffVector(points[2] - points[6]);
v2 = cryph::AffVector(points[4] - points[6]);
normals[5] = v1.cross(v2); normals[5].normalize();
//Seventh face - directly BEHIND face 1 = (P2 - V2) cross (T - V2)
v1 = cryph::AffVector(points[1] - points[7]);
v2 = cryph::AffVector(points[4] - points[7]);
normals[6] = v2.cross(v1); normals[6].normalize();
//Eighth face - directly behind face 2 = (P1 - V2) cross (P2 - V2)
v1 = cryph::AffVector(points[0] - points[7]);
v2 = cryph::AffVector(points[1] - points[7]);
normals[7] = v2.cross(v1); normals[7].normalize();
//Ninth face - directly behind face 3 = (B - V2) cross (P1 - V2)
v1 = cryph::AffVector(points[5] - points[7]);
v2 = cryph::AffVector(points[0] - points[7]);
normals[8] = v2.cross(v1); normals[8].normalize();
//Tenth face - directly behind face 4 = (P4 - V2) cross (B - V2)
v1 = cryph::AffVector(points[3] - points[7]);
v2 = cryph::AffVector(points[5] - points[7]);
normals[9] = v2.cross(v1); normals[9].normalize();
//Eleventh face - directly behind face 5 = (P3 - V2) cross (P4 - V2)
v1 = cryph::AffVector(points[2] - points[7]);
v2 = cryph::AffVector(points[3] - points[7]);
normals[10] = v2.cross(v1); normals[10].normalize();
//Face 12 - directly behind face 6 = (T - V2) cross (P3 - V2)
v1 = cryph::AffVector(points[5] - points[7]);
v2 = cryph::AffVector(points[2] - points[7]);
normals[11] = v2.cross(v1); normals[11].normalize();
vec3 verts[] = {
{points[0].x, points[0].y, points[0].z}, {points[1].x, points[1].y, points[1].z}, {points[2].x, points[2].y, points[2].z},
{points[3].x, points[3].y, points[3].z}, {points[4].x, points[4].y, points[4].z}, {points[5].x, points[5].y, points[5].z},
{points[6].x, points[6].y, points[6].z}, {points[7].x, points[7].y, points[7].z}
};
//Generate the vao and bind
glGenVertexArrays(1, vao);
glBindVertexArray(vao[0]);
//We have 6 vertices, so tell that to OpenGL
glGenBuffers(1, vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(vec3), verts, GL_STATIC_DRAW);
glVertexAttribPointer(pvaLoc_mcPosition, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(pvaLoc_mcPosition);
glGenBuffers(12, ebo);
for (int i = 0; i < 12; i++)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[i]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * sizeof(GLuint), indexList[i], GL_STATIC_DRAW);
}
//Disable the pva for normals - we will set them manually
glDisableVertexAttribArray(pvaLoc_mcNormal);
}
void Rupee::getMCBoundingBox(double* xyzLimits) const
{
xyzLimits[0] = xmin;
xyzLimits[1] = xmax;
xyzLimits[2] = ymin;
xyzLimits[3] = ymax;
xyzLimits[4] = zmin;
xyzLimits[5] = zmax;
}
void Rupee::handleCommand(unsigned char key, double ldsX, double ldsY)
{
if (key == 'b')
displayRupeeFill = !displayRupeeFill;
else if (key == 'B')
displayRupeeEdges = !displayRupeeEdges;
else
this->ModelView::handleCommand(key, ldsX, ldsY);
}
void Rupee::renderRupee(float* color)
{
glBindVertexArray(vao[0]);
glUniform3fv(ppuLoc_kd, 1, color);
// The 12 faces that are drawn with glDrawElements
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[0].dx, normals[0].dy, normals[0].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[0]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[1].dx, normals[1].dy, normals[1].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[1]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[2].dx, normals[2].dy, normals[2].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[2]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[3].dx, normals[3].dy, normals[3].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[3]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[4].dx, normals[4].dy, normals[4].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[4]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[5].dx, normals[5].dy, normals[5].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[5]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[6].dx, normals[6].dy, normals[6].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[6]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[7].dx, normals[7].dy, normals[7].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[7]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[8].dx, normals[8].dy, normals[8].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[8]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[9].dx, normals[9].dy, normals[9].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[9]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[10].dx, normals[10].dy, normals[10].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[10]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
//Front 1
glVertexAttrib3f(pvaLoc_mcNormal, normals[11].dx, normals[11].dy, normals[11].dz);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[11]);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, NULL);
}
void Rupee::render()
{
GLint pgm;
glGetIntegerv(GL_CURRENT_PROGRAM, &pgm);
glUseProgram(shaderProgram);
cryph::Matrix4x4 mc_ec, ec_lds;
getMatrices(mc_ec, ec_lds);
float mat[16];
glUniformMatrix4fv(ppuLoc_mc_ec, 1, false, mc_ec.extractColMajor(mat));
glUniformMatrix4fv(ppuLoc_ec_lds, 1, false, ec_lds.extractColMajor(mat));
ModelViewWithPhongLighting::sendToGPU(Rupee::ka, Rupee::kd, Rupee::ks, Rupee::m);
float black[] = { 0.0, 0.0, 0.0 };
float bColor[] = { 1.0, 0.0, 1.0 };
bColor[0] = colors[0];
bColor[1] = colors[1];
bColor[2] = colors[2];
if (displayRupeeFill)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
renderRupee(bColor);
}
if (displayRupeeEdges)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
renderRupee(black);
}
glUseProgram(pgm);
}
/*
| P1 - points[0]
| P2 - points[1]
| P2 - points[2]
| P2 - points[3]
| T - points[4]
| B - points[5]
| V1 - points[6]
| V2 - points[7]
*/
|
|
607fa4cb128bfb053745bce6bafd9e359aa9e850
|
f65d6a432273e26a146dad4fdaef268b2e4c2ca9
|
/WinPCK/SIMD.cpp
|
8033711c9abbb2b13fda48c63a38fbe9b338e535
|
[] |
no_license
|
wsy5555621/winpck
|
6940431e8d2f9189d3199f4e5eaba24f4f9f14b2
|
dcc6147ce06e5376d1a1775bee30f92afc17a996
|
refs/heads/master
| 2021-01-20T21:35:40.163020
| 2017-07-05T16:20:30
| 2017-07-05T16:20:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,711
|
cpp
|
SIMD.cpp
|
/*
SIMD class to detect presence of SIMD version 1.4.0
Copyright (c) 2010 Wong Shao Voon
1.1.0 - Contains the 3DNow, 3DNow+ and MMX+ detection bug fix by Leonardo Tazzini
1.2.0 - Added AMD's SSE4a and SSE5
1.3.0 - Use 2 unsigned shorts to store SIMD info, instead of 1 boolean for each SIMD type.
1.4.0 - Added the detection of Intel AES instructions
The Code Project Open License (CPOL)
http://www.codeproject.com/info/cpol10.aspx
*/
//#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "SIMD.h"
#include <intrin.h>
#define EDX_MMX_bit 0x800000 // 23 bit
#define EDX_SSE_bit 0x2000000 // 25 bit
#define EDX_SSE2_bit 0x4000000 // 26 bit
#define EDX_3DnowExt_bit 0x40000000 // 30 bit
#define EDX_3Dnow_bit 0x80000000 // 31 bit
#define EDX_MMXplus_bit 0x400000 // 22 bit
#define ECX_SSE3_bit 0x1 // 0 bit
#define ECX_SSSE3_bit 0x200 // 9 bit
#define ECX_SSE41_bit 0x80000 // 19 bit
#define ECX_SSE42_bit 0x100000 // 20 bit
#define ECX_SSE4A_bit 0x40 // 6 bit
#define ECX_SSE5_bit 0x800 // 11 bit
#define ECX_AES_bit 0x2000000 // 25 bit
#define ECX_AVX_bit 0x10000000 // 28 bit
// My own SIMD bitmask
#define INTEL_MMX 0x0001
#define INTEL_SSE 0x0002
#define INTEL_SSE2 0x0004
#define INTEL_SSE3 0x0008
#define INTEL_SSSE3 0x0010
#define INTEL_SSE41 0x0020
#define INTEL_SSE42 0x0040
#define INTEL_AES 0x0080
#define INTEL_AVX 0x0100
#define AMD_MMXPLUS 0x0001
#define AMD_3DNOW 0x0002
#define AMD_3DNOWEXT 0x0004
#define AMD_SSE4A 0x0008
#define AMD_SSE5 0x0010
SIMD::SIMD()
{
m_nIntelSIMDs = 0;
m_nAMD_SIMDs = 0;
InitParams();
}
void SIMD::InitParams()
{
int CPUInfo[4];
int CPUInfoExt[4];
DWORD dwECX=0;
DWORD dwEDX=0;
__cpuid(CPUInfo, 0);
if( CPUInfo[0] >= 1 )
{
__cpuid(CPUInfo, 1);
dwECX = CPUInfo[2];
dwEDX = CPUInfo[3];
}
__cpuid(CPUInfo, 0x80000000);
if( CPUInfo[0] >= 0x80000001 )
__cpuid(CPUInfoExt, 0x80000001);
if( EDX_MMX_bit & dwEDX )
m_nIntelSIMDs |= INTEL_MMX;
if( EDX_SSE_bit & dwEDX )
m_nIntelSIMDs |= INTEL_SSE;
if( EDX_SSE2_bit & dwEDX )
m_nIntelSIMDs |= INTEL_SSE2;
if( ECX_SSE3_bit & dwECX )
m_nIntelSIMDs |= INTEL_SSE3;
if( ECX_SSSE3_bit & dwECX )
m_nIntelSIMDs |= INTEL_SSSE3;
if( ECX_SSE41_bit & dwECX )
m_nIntelSIMDs |= INTEL_SSE41;
if( ECX_SSE42_bit & dwECX )
m_nIntelSIMDs |= INTEL_SSE42;
if( ECX_AES_bit & dwECX )
m_nIntelSIMDs |= INTEL_AES;
if( ECX_AVX_bit & dwECX )
m_nIntelSIMDs |= INTEL_AVX;
if( EDX_3DnowExt_bit & CPUInfoExt[3] )
m_nAMD_SIMDs |= AMD_3DNOWEXT;
if( EDX_3Dnow_bit & CPUInfoExt[3] )
m_nAMD_SIMDs |= AMD_3DNOW;
if( EDX_MMXplus_bit & CPUInfoExt[3] )
m_nAMD_SIMDs |= AMD_MMXPLUS;
if( ECX_SSE4A_bit & CPUInfoExt[2] )
m_nAMD_SIMDs |= AMD_SSE4A;
if( ECX_SSE5_bit & CPUInfoExt[2] )
m_nAMD_SIMDs |= AMD_SSE5;
}
// intel SIMD
bool SIMD::HasMMX() {return m_nIntelSIMDs & INTEL_MMX;}
bool SIMD::HasSSE() {return m_nIntelSIMDs & INTEL_SSE;}
bool SIMD::HasSSE2() {return m_nIntelSIMDs & INTEL_SSE2;}
bool SIMD::HasSSE3() {return m_nIntelSIMDs & INTEL_SSE3;}
bool SIMD::HasSSSE3() {return m_nIntelSIMDs & INTEL_SSSE3;}
bool SIMD::HasSSE41() {return m_nIntelSIMDs & INTEL_SSE41;}
bool SIMD::HasSSE42() {return m_nIntelSIMDs & INTEL_SSE42;}
bool SIMD::HasAES() {return m_nIntelSIMDs & INTEL_AES;}
bool SIMD::HasAVX() {return m_nIntelSIMDs & INTEL_AVX;}
// AMD SIMD
bool SIMD::HasMMXplus() {return m_nAMD_SIMDs & AMD_MMXPLUS;}
bool SIMD::Has3Dnow() {return m_nAMD_SIMDs & AMD_3DNOW;}
bool SIMD::Has3DnowExt(){return m_nAMD_SIMDs & AMD_3DNOWEXT;}
bool SIMD::HasSSE4a() {return m_nAMD_SIMDs & AMD_SSE4A;}
bool SIMD::HasSSE5() {return m_nAMD_SIMDs & AMD_SSE5;}
|
e9cf11699c230a8572ed745b3ec4b09582dcd1b5
|
e6062564a0f0b2bca8d2aca24dc9d5c9071adcac
|
/InterviewBit/Backtracking/combination-sum.cpp
|
84670a976fee12a324e903ac5c92796d9cec0866
|
[] |
no_license
|
iShubhamRana/DSA-Prep
|
22e29b85a8ee7dc278c0d89c62dcb33f29b99699
|
611d1a3fb824cce2fab051194bd5f7d0eee83f05
|
refs/heads/main
| 2023-06-25T06:59:45.599109
| 2021-07-27T18:30:18
| 2021-07-27T18:30:18
| 418,046,414
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 763
|
cpp
|
combination-sum.cpp
|
void solve(vector<int> &A, int idx, int target, vector<int> op, vector<vector<int>> &res)
{
if (target == 0)
{
res.push_back(op);
return;
}
for (int i = idx; i < A.size(); ++i)
{
if (target - A[i] >= 0)
{
// choose, explore, unchoose
op.push_back(A[i]);
solve(A, i, target - A[i], op, res);
op.pop_back();
// skip duplicates
while (i + 1 < A.size() && A[i + 1] == A[i])
++i;
}
else
break;
}
}
vector<vector<int>> Solution::combinationSum(vector<int> &A, int B)
{
sort(A.begin(), A.end());
vector<vector<int>> res;
vector<int> op;
solve(A, 0, B, op, res);
return res;
}
|
bc18ec9da3eba3af9eebaf616197f6b10a659642
|
a39627eaa1188495f498ce22f133f1686de80ac3
|
/modules/LeptonModule.h
|
24aa82edbd6c0f25ae5678a2e820cc70ce173d2c
|
[] |
no_license
|
sgnoohc/WVZBabyMaker
|
2229e486e49a6fa6f464e8b1cbfdcde915354afc
|
7f7e86acb56aa0d403e11b55ef644cf1ea62b16d
|
refs/heads/master
| 2020-05-05T01:31:33.879060
| 2019-10-15T22:14:50
| 2019-10-15T22:14:50
| 179,605,588
| 0
| 1
| null | 2019-07-13T16:56:21
| 2019-04-05T02:03:53
|
C++
|
UTF-8
|
C++
| false
| false
| 482
|
h
|
LeptonModule.h
|
#ifndef LeptonModule_h
#define LeptonModule_h
#include "rooutil.h"
#include "wvzBabyMaker.h"
namespace wvzModule
{
//__________________________________________________________________
// Lepton module
class LeptonModule: public RooUtil::Module
{
public:
wvzBabyMaker* babymaker;
LeptonModule(wvzBabyMaker* parent) { babymaker = parent; }
virtual void AddOutput();
virtual void FillOutput();
};
}
#endif
|
93a3397546ae8abe5beedd112e18ac4d1f8f4bbf
|
01c286c750aa34f8bed760d3919e5a58539f4a8e
|
/Codeforces/611A.cpp
|
26b9622fbbfeda09fa76873a448e0c6f958e1cd5
|
[
"MIT"
] |
permissive
|
Alipashaimani/Competitive-programming
|
17686418664fb32a3f736bb4d57317dc6657b4a4
|
5d55567b71ea61e69a6450cda7323c41956d3cb9
|
refs/heads/master
| 2023-04-19T03:21:22.172090
| 2021-05-06T15:30:25
| 2021-05-06T15:30:25
| 241,510,661
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
cpp
|
611A.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int a;
string s;
cin >> a >> s >> s ;
if (s == "week") {
if (a == 6 || a == 5)
cout << "53";
else
cout << "52";
return 0;
}
if (a <= 29)
cout << "12";
if (a == 30)
cout << "11";
if (a == 31)
cout << "7";
return 0;
}
|
830eb85389aeb608cbfc0d4dae3bf1e0ae0e0ae9
|
c956580fc7663b05e66d10a4f4893f7f7ce59319
|
/Array using Pointers.cpp
|
c7b71c2769430a5ec212f933066798bd00df3ef1
|
[] |
no_license
|
prash1105/amateur.stuffs
|
f2758a9e17ed89026ee1df6b760cf6ae0b100d6e
|
b620de699d86f0b44e6f5681f4c93c37ae9db7e9
|
refs/heads/main
| 2023-03-09T04:26:59.489318
| 2021-02-25T16:21:10
| 2021-02-25T16:21:10
| 337,317,931
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 290
|
cpp
|
Array using Pointers.cpp
|
#include <iostream>
using namespace std;
int main()
{
int data[5];
cout << "Enter any 5 numbers:\n";
for(int i = 0; i < 5; ++i)
cin >> data[i];
cout << "\nYou entered: ";
for(int i = 0; i < 5; ++i)
cout << endl << *(data + i);
return 0;
}
|
44bbb0aa1b69466eefc9190a48bc070bf866995d
|
8a4440b4f798a40d17d0e43a133a46f3c067af16
|
/playground/main.cpp
|
ac8de1ea2e390974ac729d3dab980e7412a8a6f4
|
[
"MIT"
] |
permissive
|
ExpLife0011/mango-library
|
006d6ce4d95b5fa41cf970571e3b70fa5e09d154
|
bad086e42b8d383bcd5c1b67f9ebdc18cf1bc50e
|
refs/heads/master
| 2020-12-27T11:59:25.680844
| 2020-02-03T05:44:49
| 2020-02-03T05:44:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 810
|
cpp
|
main.cpp
|
#include "unit_tests.h"
#include <misc/logger.h>
#include <epic/process.h>
#include <epic/memory_scanner.h>
#include <epic/shellcode.h>
int main() {
mango::logger.set_channels(mango::basic_colored_logging());
run_unit_tests();
try {
using namespace mango;
const auto process(Process::current());
logger.success("Attached to process!");
static constexpr auto bytes = shw::absjmp<false>(0x69);
for (const auto result : memscn::find(process, { bytes.data(), bytes.size() }, memscn::range_all, memscn::code_filter)) {
logger.success("0x", std::hex, std::uppercase, result);
}
} catch (const std::exception & e) {
mango::logger.error(e.what());
}
std::system("pause");
return 0;
}
|
38ecd48cee3c72cbeaac6c4d458cd3755d9a166c
|
345b886009b4aa3c06ad8ddd1012e684321f39c6
|
/Gobang/game/server/Room.hpp
|
30cd85ca9d23eb9828fe6a23db32656910ab5e5f
|
[] |
no_license
|
doubtfisher/project
|
94e4d873de6b33f835d0d7bf75c5c122ef663241
|
bd73dbdf2a237984c388d52c0660edcac52461c3
|
refs/heads/master
| 2022-01-13T00:27:15.830656
| 2019-06-22T12:27:05
| 2019-06-22T12:27:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,833
|
hpp
|
Room.hpp
|
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define SIZE 5
#define BLACK 'X'//黑子
#define WHITE 'O'//白子
class Room
{
public:
Room()
{}
Room(uint32_t &id1,uint32_t &id2)
:one(id1)
,two(id2)
{
piece[0]='X';
piece[1]='O';
memset(board,' ',sizeof(board));//初始化棋盘
result='N';//结果默认是继续
current=one;
pthread_mutex_init(&lock,NULL);
}
void Board(string &_board)
{
for(auto i = 0;i< SIZE;i++)
{
for(auto j = 0;j<SIZE;j++)
{
_board.push_back(board[i][j]);
}
}
}
char Piece(uint32_t &id)
{
int pos =0;
if(id == one)
{
pos = 0;
}
else
{
pos = 1;
}
return piece[pos];
}
bool IsMyTurn(uint32_t &id)
{
return id ==current ? true : false;
}
void Step(uint32_t &id,int &x,int &y)
{
if(current == id)
{
int pos = (id == one ? 0 : 1);
board[x][y] = piece[pos];
current = (id == one ? two : one);
result=Judge();
}
}
char GameResult(uint32_t &id)
{
return result;
}
char Judge()
{
int row = SIZE;
int col = SIZE;
for(auto i = 0;i < row;i++)//行
{
if(board[i][0]!=' '&& \
board[i][0] == board[i][1]&& \
board[i][1] == board[i][2]&& \
board[i][2] == board[i][3]&& \
board[i][3] == board[i][4])
{
return board[i][0];
}
}
for(auto i = 0;i < col;i++)//列
{
if(board[0][i]!=' '&& \
board[0][i] == board[1][i]&& \
board[1][i] == board[2][i]&& \
board[2][i] == board[3][i]&& \
board[3][i] == board[4][i])
{
return board[0][i];
}
}
//正对角线
if(board[0][0]!=' '&& \
board[0][0] == board[1][1]&& \
board[1][1] == board[2][2]&& \
board[2][2] == board[3][3]&& \
board[3][3] == board[4][4])
{
return board[0][0];
}
//反对角线
if(board[0][4]!=' '&& \
board[0][4] == board[1][3]&& \
board[1][3] == board[2][2]&& \
board[2][2] == board[3][1]&& \
board[3][1] == board[4][0])
{
return board[0][4];
}
//判断棋盘是否已满
for(auto i =0;i < row ;i++)
{
for(auto j =0;j < col;j++)
{
if(board[i][j] == ' ')
return 'N';
}
}
return 'E';
}
~Room()
{
pthread_mutex_destroy(&lock);
}
private:
uint32_t one;//指定one用户拿的是黑子'X'
uint32_t two;//指定two用户拿的是白子'O'
char piece[2];//规定0号下标对应one的棋子,1号下标对应two的棋子
uint32_t current;//当前该谁走
char board[SIZE][SIZE];//定义棋盘
char result;// X(one用户赢), O(two用户赢), E(平局),N(继续)
pthread_mutex_t lock;//定义一把锁
};
|
c24b40079f9f21d5bd35275dfc6bdf533f173d5b
|
8fbdb182b4fcf59fc1f9db8532ee0ff0b3458415
|
/reason/src/App.re
|
c2e8284406b4883297a358af4eb2642dd5bf67eb
|
[] |
no_license
|
StormShynn/sql-formatter-1
|
bd5f4fc7e77c72936aa554cce58233242e493995
|
e8065c29af8c8fa4af7318a46b01205f6389e6c9
|
refs/heads/master
| 2023-03-19T06:59:13.944625
| 2018-10-21T14:24:21
| 2018-10-21T14:24:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,044
|
re
|
App.re
|
open Tea.App;
open Tea.Html;
type model = {
input: string,
output: string,
spaces: int
};
let init = {
input: "",
output: "",
spaces: 2
};
[@bs.deriving { accessors: accessors }]
type msg =
| Input(string)
| Spaces(string)
| Select;
let update = model =>
fun
| Input(v) => { ...model, input: v, output: SqlFormatter.format(v, model.spaces) }
| Spaces(v) => { ...model, spaces: int_of_string(v), output: SqlFormatter.format(model.input, int_of_string(v)) }
| Select => {
ignore([%raw "document.getElementById(\"sql-output\").select()"]);
model
};
let view = model =>
div(
[class'("container")],
[
div(
[class'("form-inline mb-3")],
[
label([for'("sql-spaces"), class'("h4 mr-3")], [text("Spaces")]),
input'(
[
id("sql-spaces"),
class'("form-control"),
type'("number"),
value(string_of_int(model.spaces)),
onInput(v => Spaces(v))
],
[]
)
]
),
div(
[class'("form-group")],
[
label([for'("sql-input"), class'("d-flex h4 mb-3")], [text("Input")]),
textarea(
[
id("sql-input"),
class'("form-control code"),
placeholder("Enter SQL"),
Vdom.prop("rows", "9"),
onInput(v => Input(v))
],
[text(model.input)]
)
]
),
div(
[class'("form-group")],
[
label([for'("sql-output"), class'("d-flex h4 mb-3")], [text("Output")]),
textarea(
[
id("sql-output"),
class'("form-control code"),
Vdom.prop("rows", "20"),
Vdom.prop("readOnly", "true"),
onClick(Select),
onFocus(Select)
],
[text(model.output)]
)
]
)
]
);
let main = beginnerProgram({ model: init, update, view });
|
55aac9cf73d412db871adcc1efd92484802f961a
|
d231d1291e3f413d957f76caa585d2641f1e3369
|
/cl_dll/nvg.cpp
|
4233c36ebfaa10ba96d32d73758155eef55ac53b
|
[] |
no_license
|
Avatarchik/cs16-client
|
6c5eae5957e26f287ae58783770b0ca957bc4513
|
5ce19ced913aedf857a19f45c6a9c8483d499e28
|
refs/heads/master
| 2021-01-17T11:25:27.490685
| 2016-01-07T21:22:13
| 2016-01-07T21:23:35
| 49,260,886
| 1
| 0
| null | 2016-01-08T08:47:48
| 2016-01-08T08:47:48
| null |
UTF-8
|
C++
| false
| false
| 1,337
|
cpp
|
nvg.cpp
|
/*
nvg.cpp - Night Vision Googles
Copyright (C) 2015 a1batross
*/
#include "hud.h"
#include "cl_util.h"
#include "parsemsg.h"
#include "r_efx.h"
#include "dlight.h"
DECLARE_MESSAGE(m_NVG, NVGToggle)
DECLARE_COMMAND(m_NVG, NVGAdjustDown)
DECLARE_COMMAND(m_NVG, NVGAdjustUp)
int CHudNVG::Init()
{
HOOK_MESSAGE(NVGToggle)
HOOK_COMMAND("+nvgadjust", NVGAdjustUp);
HOOK_COMMAND("-nvgadjust", NVGAdjustDown);
gHUD.AddHudElem(this);
m_iFlags = HUD_ACTIVE;
m_iEnable = 0;
m_iAlpha = 110; // 220 is max, 30 is min
}
int CHudNVG::Draw(float flTime)
{
if ( !m_iEnable || gEngfuncs.IsSpectateOnly() )
{
return 1;
}
gEngfuncs.pfnFillRGBABlend(0, 0, ScreenWidth, ScreenHeight, 50, 225, 50, m_iAlpha);
// draw a dynamic light on player's origin
dlight_t *dl = gEngfuncs.pEfxAPI->CL_AllocDlight ( 0 );
VectorCopy ( gHUD.m_vecOrigin, dl->origin );
dl->radius = gEngfuncs.pfnRandomFloat( 750, 800 );
dl->die = flTime + 0.1;
dl->color.r = 50;
dl->color.g = 255;
dl->color.b = 50;
return 1;
}
int CHudNVG::MsgFunc_NVGToggle(const char *pszName, int iSize, void *pbuf)
{
BEGIN_READ(pbuf, iSize);
m_iEnable = READ_BYTE();
return 1;
}
void CHudNVG::UserCmd_NVGAdjustDown()
{
m_iAlpha += 20;
if( m_iAlpha > 220 ) m_iAlpha = 220;
}
void CHudNVG::UserCmd_NVGAdjustUp()
{
m_iAlpha -= 20;
if( m_iAlpha < 30 ) m_iAlpha = 30;
}
|
5e1b61b22d375374cdc55d8df22e6b3f0e7a1e0e
|
30283b61e7f931af82a8f18fbc7144e29fcfa365
|
/slidingWindow.cpp
|
16faf897b585309fc1ae446470b25271315df0f2
|
[] |
no_license
|
rohit236c/Competitive-programming-CPP
|
fca6385ba9d991807c855750d114b7bbf25439a8
|
c7e5bb9f5a3b988f440b8f5f6325b596e2395a7f
|
refs/heads/master
| 2020-05-30T11:11:51.029906
| 2019-11-26T04:10:49
| 2019-11-26T04:10:49
| 189,693,026
| 0
| 0
| null | 2019-09-04T12:23:42
| 2019-06-01T05:11:43
|
C++
|
UTF-8
|
C++
| false
| false
| 751
|
cpp
|
slidingWindow.cpp
|
/*
author of this code is rohit sharma
*/
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[100];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
int k;
cin >> k;
deque<int>d(k);
int i;
for (i = 0; i < k; i++) {
while (!d.empty() && arr[i] > arr[d.back()]) {
d.pop_back();
}
d.push_back(i);
}
for (; i < n; i++) {
cout << arr[d.front()] << " ";
//remove the elements that are not part of window...
while (!d.empty() && i - k >= d.front()) {
d.pop_front();
}
// remove the elements that are not useful in the window....
while (!d.empty() && arr[i] > arr[d.front()]) {
d.pop_back();
}
//add the new elements...
d.push_back(i);
}
cout << arr[d.front()];
return 0;
}
|
55e017b1115e47a16c1292b7933815c46cc1dde0
|
417cce62473f7c248cf5260226b2a8cc97b66dd2
|
/Trampa.h
|
3e5462c06ad205b3249678daf35a97aaf749986d
|
[] |
no_license
|
AlvaroBenito/TrabajoInformatica
|
b0c7caeedb5d7400f1df2e84a098da02455c1f13
|
d7604940f9c2d0b2ef1d18533242c47314205bd6
|
refs/heads/master
| 2020-03-15T13:57:38.546658
| 2018-06-12T12:13:26
| 2018-06-12T12:13:26
| 132,179,341
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 165
|
h
|
Trampa.h
|
#pragma once
#include "Plano.h"
class Trampa : public Plano
{
public:
Trampa();
Trampa(float coordx, float coordz );
~Trampa();
void dibuja();
};
|
f3ab82d7c270e00653e867414c8bcd5fde85fbae
|
7a831a6bd4fa7a401f0b015d8c73d0290e03ec8b
|
/038.1v1_risiko.cpp
|
d327d2b23b1e2c7d7270df5ce5da019a35cca3db
|
[] |
no_license
|
CawaAlreadyTaken/UniTN_exercises
|
63f9826c41e07e24cd6924a56eb93962573d3fa3
|
784969a7c472cc03afc79378fbd2cfa83be1ba22
|
refs/heads/master
| 2023-02-10T04:41:05.475086
| 2020-12-27T13:22:06
| 2020-12-27T13:22:06
| 300,202,808
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 311
|
cpp
|
038.1v1_risiko.cpp
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(time(NULL));
int def = random() % 6 + 1;
int att = random() % 6 + 1;
if (att > def) {
cout << "Attacker won, " << att << "-" << def << endl;
} else {
cout << "Defender won, " << def << "-" << att << endl;
}
return 0;
}
|
f109a3a30d220a55670102d2f824d087c16c6357
|
8ca9069b8ee82f967791f4650d3e8cc16e1504f8
|
/app/tests/testmarkstorage.h
|
7e44f014bd8635d6600b353bef65a9906955fd6d
|
[] |
no_license
|
a-pavlov/fantlab
|
de52871add375684521015b6b6741d1f00c89b3a
|
9b7928c9f9e3af38c55efdc298231183cd9382bb
|
refs/heads/master
| 2022-12-03T08:05:54.159611
| 2022-01-13T16:40:00
| 2022-01-13T16:40:00
| 120,786,968
| 1
| 0
| null | 2022-11-16T09:32:25
| 2018-02-08T16:31:02
|
C++
|
UTF-8
|
C++
| false
| false
| 408
|
h
|
testmarkstorage.h
|
#ifndef TESTMARKSTORAGE_H
#define TESTMARKSTORAGE_H
#include <QObject>
class TestMarkStorage : public QObject
{
Q_OBJECT
public:
explicit TestMarkStorage(QObject *parent = nullptr);
signals:
private slots:
void testStorageInit();
void testStorageGetters();
void testStorageArbitraryInput();
void testAddUser();
void testSetWorkMultipleTimes();
};
#endif // TESTMARKSTORAGE_H
|
06c579a1a0cbb641a3ba45a1d4bd483e61253a2f
|
27b7840f01a36d2e10486d153d514dbac2eb28ed
|
/src/midimanager.cpp
|
99fc49ba993b6c0037af57c033ec35f6e9b72ec9
|
[
"MIT"
] |
permissive
|
jfceja/MidiInter
|
f425bc374317adf37df2892477cfe8c312ead30f
|
077c3148cd4c8e99b3832dbe713664d6327898ce
|
refs/heads/master
| 2021-04-12T08:57:06.919749
| 2018-01-30T01:07:45
| 2018-01-30T01:07:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,447
|
cpp
|
midimanager.cpp
|
#include "midimanager.h"
MidiManager::MidiManager()
{
}
mSong song;
//QVector<int>noteVec = QVector<int>();
//960 seems to be a standard tpqn for recording midi
int MidiManager::TPQN = 960;
QByteArray MidiManager::ReadMidi(QFile &file)
{
QDataStream in(&file);
QByteArray array;
qint8 test;
in>> test;
QString s = QString::number(test);
array.append(s);
for (int var = 0; var < file.size(); ++var)
{
in >> test;
array.append(test);
}
return array;
}
mSong MidiManager::Deserialize(QByteArray &array)
{
//One extra byte at pos 0 of array for some reason, 0 based indexing cancels it out
int ticksPerQuarterNote,framesPerSecondSMTPE,deltaTimeSMTPE;
int format = array.at(10);
int trackChunks = array.at(12); // no one needs more than 127 tracks anyways, technically this is var length
bool divistionFormat = (array.at(13) >> 7);
if (divistionFormat)
{
deltaTimeSMTPE = array.at(13) & 127;
framesPerSecondSMTPE = ~(array.at(14))+1;
ticksPerQuarterNote = 0;
}
else
{
deltaTimeSMTPE = 0;
framesPerSecondSMTPE = 0;
ticksPerQuarterNote = ((uchar)(array.at(13)) << 8) | (uchar)array.at(14);
}
double tpqnScale = TPQN / ticksPerQuarterNote; // Enforce 960 TPQN
int currentPos = 15;
// was (if format is 0), only TPQN supported for now though
if (true) {
//Runs for amount of tracks in a song
for (int var = 0; var < trackChunks; ++var) {
mTrack *track = new mTrack;
track->trackName = "";
track->instrumentName ="";
currentPos += 4; //should put on first byte of Length
track->length = ((uchar)(array.at(currentPos)) << 24 |
(uchar)(array.at(currentPos+1)) << 16 |
(uchar)(array.at(currentPos+2)) << 8 |
(uchar)(array.at(currentPos+3)));
currentPos += 4; //should put on first byte after length
uchar lastStatus,lastChannel;
//Runs for amount of bytes in a track, each iteration is a new event
for (int pos = currentPos; pos < track->length + currentPos; ++pos) {
bool eventCanAdd = false;
//A delta tima(variable length 1 - 4 bytes) always comes before an event
//Because of variable length, bit 7(last MSB) is used to denote that it is last byte
//in the series if it is 0.
//NOTE* bit 7n must be 1 if it is not last byte, does not signify a larger value though
int deltaTime;
if (array.at(pos) >> 7 == 0)
{
deltaTime =array.at(pos);
pos++;
}
else if (array.at(pos+1) >> 7 == 0)
{
deltaTime = (uchar)(array.at(pos) ^ 128) << 7;
deltaTime = ((uchar)deltaTime | ((uchar)array.at(pos+1)));
pos+=2;
}
else if (array.at(pos+2) >> 7 == 0)
{
deltaTime = ((uchar)(array.at(pos) ^ 128) << 14 |
(uchar)(array.at(pos+1)) << 7 |
(uchar)(array.at(pos+2)));
pos+=3;
}
else if ((uchar)array.at(pos+3) >> 7 == 0)
{
deltaTime = ((uchar)(array.at(pos)^ 128) << 21 |
(uchar)(array.at(pos+1)) << 14 |
(uchar)(array.at(pos+2)) << 7 |
(uchar)(array.at(pos+3)));
pos+=4;
}
deltaTime*=tpqnScale;
track->totalDT += deltaTime;
//Running status
if (((uchar)array.at(pos) & 128) != 128) {
eventCanAdd = true;
uchar dataByte1 = (uchar)array.at(pos);
uchar channel = lastChannel;
uchar status = lastStatus;
uchar dataByte2 = (uchar)array.at(++pos);
if (dataByte2 == 0) {
// event.noteOn = false;
status = 0x80 | channel;
}
DWORD nvnt =( dataByte2 << 16 |
dataByte1 << 8 |
status);
track->listOfNotes.append(deltaTime);
track->listOfNotes.append(0);
track->listOfNotes.append(nvnt);
}
//No need to run if running status
if (!eventCanAdd) {
//Normal event
if (((uchar)array.at(pos) >>4) != 15) {
uchar status = (uchar)array.at(pos);
uchar channel = (uchar)array.at(pos) & 15;
uchar dataByte1 = (uchar)array.at(++pos);
uchar dataByte2 = (uchar)array.at(++pos);
DWORD nvnt =( dataByte2 << 16 |
dataByte1 << 8 |
status);
eventCanAdd = true;
track->listOfNotes.append(deltaTime);
track->listOfNotes.append(0);
track->listOfNotes.append(nvnt);
lastChannel = channel;
lastStatus = status;
}
//Meta event
else if (((uchar)array.at(pos) >> 4) == 15) {
switch ((uchar)array.at(++pos)) {
//Track name
case 3: {
int len = (uchar)array.at(++pos);
QString name;
name.resize(len);
for (int var = 0; var < len; ++var) {
name[var] = (uchar)array.at(++pos);
}
track->trackName = name;
break;
}
//Instrument name
case 4:{
int len = (uchar)array.at(++pos);
QString name;
name.resize(len);
for (int var = 0; var < len; ++var) {
name[var] = (uchar)array.at(++pos);
}
track->instrumentName = name;
break;
}
//Time signature
case 88:
{
int len = (uchar)array.at(++pos);
for (int var = 0; var < len; ++var) {
pos++;
//unhandled for now, wtf does the data mean
}
break;
}
//Key Signature
case 89:
{
int len = (uchar)array.at(++pos);
for (int var = 0; var < len; ++var) {
pos++;
//unhandled for now, wtf does the data mean
}
break;
}
//Tempo in microseconds per quarter note
case 81:
{
qDebug() << "tempo set unhandled";
int len = (uchar)array.at(++pos);
for (int var = 0; var < len; ++var) {
pos++;
//unhandled for now, wtf does the data mean
}
break;
}
//End of track
case 47:
pos = track->length + currentPos;
break;
case 33:
pos++;
break;
default:
qDebug() << "Meta event unhandled: " << (uchar)array.at(pos);
break;
}
}
}
}
qDebug() << "TPQN: " << track->totalDT << " LENGTH: " << track->listOfNotes.length();
song.tracks.append(track);
}
}
else if (song.format == 1) {
//Not supported
}
emit notifyTrackViewChanged(&song);
return song;
}
//There are a few cases where this fails, no idea why
//Can be made way simpler
void MidiManager::updateMidiAdd(int note,int veloc, int start, int length,mTrack *track){
int vLen = track->listOfNotes.length();
qDebug() << vLen;
int vPos = 0;
int newDT = 0;
int runs = 0;
uchar status = 0x90;
uchar velocity = veloc;
int elapsedDT = 0;
bool lastNote = false;
QVector<int> newVec;
if ( vLen > 0) {
//runs twice - once for note start and another for note end
for (int rep = 0; rep < 2; ++rep) {
if (rep ==1) {
//Housekeeping to get ready for next iteration
start = start + length;
velocity= 0;
lastNote = false;
}
//Start by getting the DT that elapsed before the Start value is hit
//If I go over Start value, Determine whether Start is before or after current DT.
//If I never go over, that means I placed value far right of all other notes.
for (int i = vPos; i <= vLen; i+=3) {
if(i == vLen){
lastNote = true;
newDT = std::abs(elapsedDT - start);
break;
}
elapsedDT += track->listOfNotes.at(i);
if (elapsedDT >= start) {
vPos = i;
newDT = std::abs(elapsedDT - start);
break;
}
else if(i+ 3 == vLen ){
lastNote = true;
vPos = i+3;
newDT = std::abs(elapsedDT - start);
break;
}
}
//Now reconstruct the original Vector one by one, putting in the new note start and end
//where appropriate. Must determine whether new value comes before or after the current 'i' pos.
// Also must adjust the DT of the next event if I put a new value BEFORE an existing one.
if(runs > vLen){
runs = vLen;
}
for (int i = runs; i <= vLen; i+=3) {
// qDebug() << "VPOS " << vPos;
if (!lastNote && i == vLen) {
break; //gtfo
}
if (vPos == i) {
runs = i+3;
DWORD nvnt =( velocity << 16 |
note << 8 |
status);
if (lastNote) {
qDebug() << "LastNote Hit";
newVec.append(newDT);
newVec.append(0);
newVec.append(nvnt);
if(rep == 0){
break;
}
}
else{
if(newDT == 0){
// Notice that a note on needs to be after, and vise versa.
if(rep == 0){
newVec.append(track->listOfNotes.at(i));
newVec.append(track->listOfNotes.at(i+1));
newVec.append(track->listOfNotes.at(i+2));
newVec.append(0);
newVec.append(0);
newVec.append(nvnt);
}
else{
newVec.append(track->listOfNotes.at(i));
newVec.append(0);
newVec.append(nvnt);
newVec.append(0);
newVec.append(track->listOfNotes.at(i+1));
newVec.append(track->listOfNotes.at(i+2));
}
}
else{
newVec.append(track->listOfNotes.at(i)-newDT);
newVec.append(0);
newVec.append(nvnt);
newVec.append(newDT);
newVec.append(track->listOfNotes.at(i+1));
newVec.append(track->listOfNotes.at(i+2));
}
if(rep == 0){
vPos +=3;
break;
}
}
}
// Add existing events as normal
else{
newVec.append(track->listOfNotes.at(i));
newVec.append(track->listOfNotes.at(i+1));
newVec.append(track->listOfNotes.at(i+2));
}
}
}
}
else
{
DWORD nvnt =( velocity << 16 |
note << 8 |
status);
newVec.append(start);
newVec.append(0);
newVec.append(nvnt);
nvnt =(0 << 16 |
note << 8 |
0x90);
newVec.append(length);
newVec.append(0);
newVec.append(nvnt);
}
track->listOfNotes = newVec;
}
DWORD MidiManager::statusDWORD(uchar db1, uchar db2, uchar status)
{
DWORD nvnt =( db2 << 16 |
db1 << 8 |
status);
return nvnt;
}
void MidiManager::updateMidiDelete(int start, int length, int note, mTrack *track)
{
QVector<int> newVec;
int vLen = track->listOfNotes.length();
int DT = 0;
int rep = 0;
for (int pos = 0; pos < vLen; pos+=3)
{
uchar nte = track->listOfNotes.at(pos+2) >> 8;
DT += track->listOfNotes.at(pos);
if (DT == start && note == nte)
{
if (pos+3 <vLen)
{
track->listOfNotes[pos+3] += track->listOfNotes[pos];
}
if (rep == 0) {
start = start + length;
}
rep++;
continue;
}
else
{
newVec.append(track->listOfNotes.at(pos));
newVec.append(track->listOfNotes.at(pos+1));
newVec.append(track->listOfNotes.at(pos+2));
}
}
track->listOfNotes = newVec;
}
//Great resource http://cs.fit.edu/~ryan/cse4051/projects/midi/midi.html#mff0
//http://www.mobilefish.com/tutorials/midi/midi_quickguide_specification.html
|
173f2280afc815193e1be63902e8595ac3634042
|
965782a74d4cd1a1eb7969288658416bc201c3f9
|
/main.cpp
|
88ddc2121e4766f6700416890fbddeff2554052f
|
[] |
no_license
|
claudiomarpda/file_client
|
044a74a3b1a5d99447963e78b6c3e86cbfd2a9b2
|
9b2b16376379493bc64703fac49ae56adb2b4e19
|
refs/heads/master
| 2021-08-16T06:12:48.154040
| 2017-11-19T02:07:23
| 2017-11-19T04:17:35
| 111,256,702
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,004
|
cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include "lib/netry/include/NetStream.h"
#include "include/FileHandler.h"
using namespace netry;
using namespace std;
int main() {
Socket socket("0.0.0.0", 5000);
NetStream stream(socket);
vector<string> fileNames;
// 01
// Receive the number of files
int numberOfFiles = stoi(stream.readString());
// 02
// Receive the names of the files
for (int i = 0; i < numberOfFiles; i++) {
fileNames.push_back(stream.readString());
}
// Show file names
for (int i = 0; i < fileNames.size(); i++) {
cout << i + 1 << " " << fileNames[i] << endl;
}
// 03
// Message before sending the file number
cout << stream.readString();
// Get file number from user
int option;
cin >> option;
// 04
// Send the file number
stream.writeInt(option - 1);
// 05
// Receive file confirmation
cout << stream.readString();
string fileName = stream.readString();
cout << fileName << endl;
// 06
// Receive the file size
int fileSize = stream.readInt();
cout << endl << "File size: " << fileSize << " bytes" << endl;
cout << "Downloading..." << endl;
string condition;
const size_t kBufferSize = 1024;
char buffer[kBufferSize];
FILE *pFile = FileHandler::openOutputFile(fileName);
int totalBytesReceived = 0;
// 07
condition = stream.readString();
while (condition == "_continue") {
// TODO: implement protocol for confirmation of bytes received by the client
// 08
stream.readBytes(buffer);
totalBytesReceived += fwrite(buffer, sizeof(unsigned char), kBufferSize, pFile);
// 07
condition = stream.readString();
}
cout << "Download completed " << endl;
cout << "Bytes: " << totalBytesReceived << endl;
// Sleeps some time so we can test several clients connected
// sleep(20);
fclose(pFile);
socket.close();
return 0;
}
|
4db2946edea6456464bbd970240edf994900d744
|
68fe1482474dd38717726f85574078b58e0fe284
|
/src/functions.cpp
|
bd549e7a4d2b6a99b58841356ba2c6bdfd177979
|
[
"MIT"
] |
permissive
|
dskart/ROBO_fast_slam
|
0ee34bf84bc25957594a4c1b28b9c315a77bfbf4
|
cde36b06288981b189baa463719bb2605ab28794
|
refs/heads/master
| 2020-04-11T04:18:30.432751
| 2019-01-03T12:02:05
| 2019-01-03T12:02:05
| 161,508,133
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,209
|
cpp
|
functions.cpp
|
#include "functions.hpp"
MatrixXd CalcInput(const float &time)
{
double v;
double yawrate;
if(time <= 3.0)
{
v = 0.0;
yawrate = 0.0;
}
else
{
v = 0.5; // m/s
yawrate = 0.1; // rad/s
}
MatrixXd u(2,1);
u << v, yawrate;
return u;
}
std::array<MatrixXd,2> Observation(MatrixXd &x_true, MatrixXd &xd, const MatrixXd &u, const MatrixXd &RFID)
{
MatrixXd Qsim(2,2);
MatrixXd Rsim(2,2);
Qsim << 0.09, 0,
0, 0.0121847;
Rsim << 0.25, 0,
0, 0.03046174;
// rand normal distrubition generator
std::random_device rd{};
std::mt19937 gen{rd()};
std::normal_distribution<double> normal;
// calc true state
x_true = MotionModel(x_true, u);
//add noise to range observation
std::vector<MatrixXd> z_vec;
for(int i = 0; i < RFID.rows(); ++i)
{
double dx = RFID(i,0) - x_true(0,0);
double dy = RFID(i, 1) - x_true(1, 0);
double d = sqrt(dx * dx + dy * dy);
double angle = Pi2Pi(atan2(dy, dx) - x_true(2,0));
if(d <= MAX_RANGE)
{
double dn = d + normal(gen) * Qsim(0,0); // add noise
double anglen = angle + normal(gen) * Qsim(1,1); // add noise
MatrixXd zi(3,1);
zi << dn,
Pi2Pi(anglen),
i;
z_vec.push_back(zi);
}
}
MatrixXd z(3,z_vec.size());
for(size_t i = 0; i < z_vec.size(); ++i)
{
z(0,i) = z_vec[i](0);
z(1,i) = z_vec[i](1);
z(2,i) = z_vec[i](2);
}
//add noise to input
double ud1 = u(0,0) + normal(gen) * Rsim(0,0);
double ud2 = u(1,0) + normal(gen) * Rsim(1,1) + OFFSET_YAWRATE_NOISE;
MatrixXd ud(2,1);
ud << ud1, ud2;
xd = MotionModel(xd, ud);
std::array<MatrixXd,2> out = {z,ud};
return out;
}
MatrixXd MotionModel(const MatrixXd &x, const MatrixXd &u)
{
MatrixXd F(3,3);
F << 1.0, 0, 0,
0, 1.0, 0,
0, 0, 1.0;
MatrixXd B(3,2);
B << DT * cos(x(2, 0)), 0,
DT * sin(x(2, 0)), 0,
0.0 , DT;
MatrixXd v(2,1);
v << u(0), u(0);
MatrixXd mm(3,1);
mm << 2, 2, 2;
MatrixXd x_new = F * x + B * v ;
x_new(2,0) = Pi2Pi(x_new(2,0));
return x_new;
}
double Pi2Pi(const double &angle)
{
return fmod(angle + M_PI,2 * M_PI) - M_PI;
}
|
7c4fbdb508e0bdd8f4a2186845e6be3b90454ed6
|
d6f710a94efbf6a4fc764e87aa0410b68d6d2e34
|
/Tree/BinarySearchTree.cpp
|
4512f3df4183cf250cdb464019e9b90700bb7d6d
|
[] |
no_license
|
Xiang3999/DataStructNotes
|
e80d9f2ca0fb8e4bb93ff008cb22d0c3b50eb6bf
|
d19422186e1565bf801cb85b7451364195c073e0
|
refs/heads/main
| 2023-02-09T22:02:40.682853
| 2020-12-29T05:53:26
| 2020-12-29T05:53:26
| 304,252,773
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,066
|
cpp
|
BinarySearchTree.cpp
|
#include <iostream>
#include <stack>
using namespace std;
int MAX = -32767;
class BinarySearchTree {
private:
int data;
BinarySearchTree* lchild;
BinarySearchTree* rchild;
public:
//查找最小值
BinarySearchTree* FindMin(BinarySearchTree* BST) {
BinarySearchTree* cur = BST;
//搜索树为空时,返回NULL
if (cur == NULL) {
return NULL;
}
while (cur) {
//左子树为空时,返回该节点
if (cur->lchild == NULL) {
return cur;
}
else {//否则在左子树里找最小值
cur = cur->lchild;
}
}
}
//查找最大值
BinarySearchTree* FindMax(BinarySearchTree* BST) {
BinarySearchTree* cur = BST;
//搜索树为空时,返回NULL
if (cur == NULL) {
return NULL;
}
while (cur) {
//右子树为空时,返回该节点
if (cur->rchild == NULL) {
return cur;
}
else {//否则在左子树里找最小值
cur = cur->rchild;
}
}
}
//按值查找结点
BinarySearchTree* Find(BinarySearchTree* BST, int data) {
BinarySearchTree* cur = BST;
//搜索树为空,返回NULL
if (cur == NULL) {
return NULL;
}
while (cur) {
//根节点值与data相等,返回根节点
if (cur->data == data) {
return cur;
}
else if (cur->data < data) {
//比data小,则在左子树里寻找
cur = cur->lchild;
}
else {//否则在右子树里寻找
cur = cur->rchild;
}
}
}
//插入函数
BinarySearchTree* Insert(BinarySearchTree* BST, int data) {
//搜索树为空,则构建根节点
if (!BST) {
BST = new BinarySearchTree;
BST->data = data;
BST->lchild = NULL;
BST->rchild = NULL;
}
else {
//若data小于根节点的值,则插入到左子树
if (data < BST->data) {
BST->lchild = BST->Insert(BST->lchild, data);
}
else if (data > BST->data) {
//若data小于根节点的值,则插入到左子树
BST->rchild = BST->Insert(BST->rchild, data);
}
}
return BST;
}
//二叉搜索树的构造,利用data数组构造二叉搜索树
BinarySearchTree* Create(int* data, int size) {
BinarySearchTree* bst = NULL;
for (int i = 0; i < size; i++) {
bst = this->Insert(bst, data[i]);
}
return bst;
}
//递归前序遍历
void PreorderTraversal(BinarySearchTree* T) {
if (T == NULL) {
return;
}
cout << T->data << " "; //访问根节点并输出
T->PreorderTraversal(T->lchild); //递归前序遍历左子树
T->PreorderTraversal(T->rchild); //递归前序遍历右子树
}
//递归中序遍历
void InorderTraversal(BinarySearchTree* T) {
if (T == NULL) {
return;
}
T->InorderTraversal(T->lchild); //递归中序遍历左子树
cout << T->data << " "; //访问根节点并输出
T->InorderTraversal(T->rchild); //递归中序遍历左子树
}
//递归后序遍历
void PostorderTraversal(BinarySearchTree* T) {
if (T == NULL) {
return;
}
T->PostorderTraversal(T->lchild); //递归后序遍历左子树
T->PostorderTraversal(T->rchild); //递归后序遍历右子树
cout << T->data << " "; //访问并打印根节点
}
//删除操作
BinarySearchTree* Delete(BinarySearchTree* BST, int data) {
if (!BST) {//树空时,直接返回NULL
return BST;
}
else if (data < BST->data) {
//data小于根节点时,到左子树去删除data
BST->lchild = this->Delete(BST->lchild, data);
}
else if (data > BST->data) {
//data大于根节点时,到右子树去删除data
BST->rchild = this->Delete(BST->rchild, data);
}
else {//data等于根节点时
if (BST->lchild && BST->rchild) {
//左右子树都不空时,用右子树的最小来代替根节点
BinarySearchTree* tmp = this->FindMin(BST->rchild);
BST->data = tmp->data;
//删除右子树的最小结点
BST->rchild = this->Delete(BST->rchild, tmp->data);
}
else {//当左右子树都为空或者有一个空时
BinarySearchTree* tmp = BST;
if (!BST->lchild) {//左子树为空时
BST = BST->rchild;
}
else if (!BST->rchild) {//右子树为空时
BST = BST->lchild;
}
delete tmp;
}
}
return BST;
}
int getdata(BinarySearchTree* BST) {
return BST->data;
}
//删除最小值
BinarySearchTree* DeleteMin(BinarySearchTree* BST) {
BinarySearchTree* cur = BST; //当前结点
BinarySearchTree* parent = BST; //当前结点的父节点
if (cur == NULL) {
return BST;
}
//当前结点的左子树非空则一直循环
while (cur->lchild != NULL) {
parent = cur; //保存当前结点父节点
cur = cur->lchild; //把当前结点指向左子树
}
if (cur == BST) {//当前结点为根结点,即只有右子树
BST = BST->rchild;
}
else {
if (cur->rchild == NULL) {//右子树为空,即为叶子节点
parent->lchild = NULL; //父节点左子树置空
delete cur;
}
else {//右子树非空
parent->lchild = cur->rchild; //把当前结点右子树放到父节点的左子树上
delete cur;
}
}
return BST;
}
//删除最大值
BinarySearchTree* DeleteMax(BinarySearchTree* BST) {
BinarySearchTree* cur = BST; //当前结点
BinarySearchTree* parent = BST; //当前结点的父节点
if (cur == NULL) {
return BST;
}
//当前结点右子树非空则一直循环
while (cur->rchild != NULL) {
parent = cur; //保存当前结点父节点
cur = cur->rchild; //把当前结点指向右子树
}
if (cur == BST) {//当前结点为根结点,即只有左子树
BST = BST->lchild;
}
else {
if (cur->lchild == NULL) {//左子树为空,即为叶子节点
parent->rchild = NULL; //父节点右子树置空
delete cur;
}
else {//左子树非空
parent->rchild = cur->lchild; //把当前结点左子树放到父节点的右子树上
delete cur;
}
}
return BST;
}
};
int main()
{
int size;
cout << "请输入结点个数:" << endl;
cin >> size;
int* data;
data = new int[size];
cout << "请输入每个结点的值:" << endl;
for (int i = 0; i < size; i++) {
cin >> data[i];
}
BinarySearchTree* bst;
bst = new BinarySearchTree;
bst = bst->Create(data, size);
cout << "前序遍历(递归):" << endl;
bst->PreorderTraversal(bst);
cout << endl;
cout << "中序遍历(递归):" << endl;
bst->InorderTraversal(bst);
cout << endl;
cout << "后序遍历(递归):" << endl;
bst->PostorderTraversal(bst);
cout << endl;
BinarySearchTree* bst_max;
bst_max = bst->FindMax(bst);
cout << "二叉搜索树的最大值为:" << endl;
cout << bst_max->getdata(bst_max);
cout << endl;
cout << "删除最大值后:" << endl;
bst = bst->DeleteMax(bst);
cout << "前序遍历(递归):" << endl;
bst->PreorderTraversal(bst);
cout << endl;
cout << "中序遍历(递归):" << endl;
bst->InorderTraversal(bst);
cout << endl;
cout << "后序遍历(递归):" << endl;
bst->PostorderTraversal(bst);
cout << endl;
cout << "二叉搜索树的最小值为:" << endl;
BinarySearchTree* bst_min;
bst_min = bst->FindMin(bst);
cout << bst_min->getdata(bst_min);
cout << endl;
cout << "删除最小值后:" << endl;
bst = bst->DeleteMin(bst);
cout << "前序遍历(递归):" << endl;
bst->PreorderTraversal(bst);
cout << endl;
cout << "中序遍历(递归):" << endl;
bst->InorderTraversal(bst);
cout << endl;
cout << "后序遍历(递归):" << endl;
bst->PostorderTraversal(bst);
cout << endl;
int num;
cout << "请输入要删除的结点:" << endl;
cin >> num;
bst = bst->Delete(bst, num);
cout << "删除之后:" << endl;
cout << "前序遍历(递归):" << endl;
bst->PreorderTraversal(bst);
cout << endl;
cout << "中序遍历(递归):" << endl;
bst->InorderTraversal(bst);
cout << endl;
cout << "后序遍历(递归):" << endl;
bst->PostorderTraversal(bst);
cout << endl;
return 0;
}
|
a004ab29c9daf873f636f4e4473a79edb4441857
|
6ef65d97674f36349caa419682d911f6f311009f
|
/visionSys/include/can_interface.h
|
62aed800ceb5e5bb259a4f76d5f33f2b176cc3be
|
[] |
no_license
|
lifani/CppCode
|
43e0227cad07bcca51bd42482f1b211395b409df
|
c7c12b68c35558367f24c72a7b0d85e649624aa1
|
refs/heads/master
| 2020-05-02T20:07:43.933227
| 2014-03-19T06:08:32
| 2014-03-19T06:08:32
| 8,262,105
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 702
|
h
|
can_interface.h
|
#ifndef __CAN_INTERFACE__
#define __CAN_INTERFACE__
#include <vector>
using namespace std;
typedef struct _filter_param
{
unsigned short m_usCanId;
unsigned short m_usCmdCode;
} Filter_param;
class Packet;
class can_interface
{
public :
virtual ~can_interface()
{
}
virtual Packet* Read() = 0;
virtual int Write(const char* ptr, unsigned int len, unsigned short can_id = 0, unsigned short cmd_code = 0) = 0;
virtual bool Init() = 0;
virtual bool SetFilter(vector<Filter_param> &rFilterParam) = 0;
virtual void SetKey(unsigned char key) = 0;
virtual void SetProtocal( bool bIsOldProtocal ) = 0;
};
extern "C" can_interface* CreateCanInterface(const char* can_name);
#endif
|
c9669767bbfff7dd32d9ec39bd46e855210678aa
|
96dcef865aa53f835ec151e5f66d158569916469
|
/paddle/operators/math/detail/lstm_kernel.h
|
fed8f9c4ca48905ad4c524ba400e8c7bb2f7fbd1
|
[
"Apache-2.0"
] |
permissive
|
typhoonzero/Paddle
|
ae7708d8db35c0858c92f3d39f22b556a88adf4d
|
45a8c2759b8b8d6b59386a706ee37df6c258abc7
|
refs/heads/develop
| 2021-04-06T00:44:51.697475
| 2018-02-08T09:09:18
| 2018-02-08T09:09:18
| 83,394,080
| 1
| 1
|
Apache-2.0
| 2018-10-12T11:08:12
| 2017-02-28T05:40:12
|
C++
|
UTF-8
|
C++
| false
| false
| 6,368
|
h
|
lstm_kernel.h
|
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "paddle/operators/math/detail/activation_functions.h"
#include "paddle/platform/hostdevice.h"
#include <type_traits>
namespace paddle {
namespace operators {
namespace math {
namespace detail {
namespace forward {
template <class T>
class lstm {
public:
HOSTDEVICE void operator()(T &value_in, T &value_ig, T &value_fg, T &value_og,
T &prev_state, T &state, T &state_atv, T &output,
T &checkI, T &checkF, T &checkO,
ActivationType active_node,
ActivationType active_gate,
ActivationType active_state) {
value_in = activation(value_in, active_node);
value_ig = activation(value_ig + prev_state * checkI, active_gate);
value_fg = activation(value_fg + prev_state * checkF, active_gate);
state = value_in * value_ig + prev_state * value_fg;
value_og = activation(value_og + state * checkO, active_gate);
state_atv = activation(state, active_state);
output = value_og * state_atv;
}
#ifndef __NVCC__
#ifndef __AVX__ // If not compiled with AVX instructs. Disable AVX by default
static const bool avx = false;
#else
// Only float support AVX optimization
static const bool avx = std::is_same<T, float>::value;
HOSTDEVICE void operator()(__m256 &value_in, __m256 &value_ig,
__m256 &value_fg, __m256 &value_og,
__m256 &prev_state, __m256 &state,
__m256 &state_atv, __m256 &output, __m256 &checkI,
__m256 &checkF, __m256 &checkO,
ActivationType active_node,
ActivationType active_gate,
ActivationType active_state) {
value_in = activation(value_in, active_node);
value_ig =
activation(_mm256_add_ps(value_ig, _mm256_mul_ps(prev_state, checkI)),
active_gate);
value_fg =
activation(_mm256_add_ps(value_fg, _mm256_mul_ps(prev_state, checkF)),
active_gate);
state = _mm256_add_ps(_mm256_mul_ps(value_in, value_ig),
_mm256_mul_ps(prev_state, value_fg));
value_og = activation(_mm256_add_ps(value_og, _mm256_mul_ps(state, checkO)),
active_gate);
state_atv = activation(state, active_state);
output = _mm256_mul_ps(value_og, state_atv);
}
#endif
#endif
};
} // namespace forward
namespace backward {
template <class T>
class lstm {
public:
HOSTDEVICE void operator()(T &value_in, T &value_ig, T &value_fg, T &value_og,
T &grad_in, T &grad_ig, T &grad_fg, T &grad_og,
T &prev_state, T &prev_state_grad, T &state,
T &state_grad, T &state_atv, T &output_grad,
T &checkI, T &checkF, T &checkO, T &checkIGrad,
T &checkFGrad, T &checkOGrad,
ActivationType active_node,
ActivationType active_gate,
ActivationType active_state) {
grad_og = activation(output_grad * state_atv, value_og, active_gate);
state_grad += activation(output_grad * value_og, state_atv, active_state) +
grad_og * checkO;
grad_in = activation(state_grad * value_ig, value_in, active_node);
grad_ig = activation(state_grad * value_in, value_ig, active_gate);
grad_fg = activation(state_grad * prev_state, value_fg, active_gate);
prev_state_grad =
grad_ig * checkI + grad_fg * checkF + state_grad * value_fg;
checkIGrad = grad_ig * prev_state;
checkFGrad = grad_fg * prev_state;
checkOGrad = grad_og * state;
}
#ifndef __NVCC__
#ifndef __AVX__ // If not compiled with AVX instructs. Disable AVX by default
static const bool avx = false;
#else
// Only float support AVX optimization
static const bool avx = std::is_same<T, float>::value;
HOSTDEVICE void operator()(
__m256 &value_in, __m256 &value_ig, __m256 &value_fg, __m256 &value_og,
__m256 &grad_in, __m256 &grad_ig, __m256 &grad_fg, __m256 &grad_og,
__m256 &prev_state, __m256 &prev_state_grad, __m256 &state,
__m256 &state_grad, __m256 &state_atv, __m256 &output_grad,
__m256 &checkI, __m256 &checkF, __m256 &checkO, __m256 &checkIGrad,
__m256 &checkFGrad, __m256 &checkOGrad, ActivationType active_node,
ActivationType active_gate, ActivationType active_state) {
grad_og = activation(_mm256_mul_ps(output_grad, state_atv), value_og,
active_gate);
state_grad = _mm256_add_ps(activation(_mm256_mul_ps(output_grad, value_og),
state_atv, active_state),
state_grad);
state_grad = _mm256_add_ps(_mm256_mul_ps(grad_og, checkO), state_grad);
grad_in =
activation(_mm256_mul_ps(state_grad, value_ig), value_in, active_node);
grad_ig =
activation(_mm256_mul_ps(state_grad, value_in), value_ig, active_gate);
grad_fg = activation(_mm256_mul_ps(state_grad, prev_state), value_fg,
active_gate);
prev_state_grad = _mm256_add_ps(_mm256_mul_ps(grad_ig, checkI),
_mm256_mul_ps(grad_fg, checkF));
prev_state_grad =
_mm256_add_ps(_mm256_mul_ps(state_grad, value_fg), prev_state_grad);
checkIGrad = _mm256_mul_ps(grad_ig, prev_state);
checkFGrad = _mm256_mul_ps(grad_fg, prev_state);
checkOGrad = _mm256_mul_ps(grad_og, state);
}
#endif
#endif
};
} // namespace backward
} // namespace detail
} // namespace math
} // namespace operators
} // namespace paddle
|
a0b0eed762d9608638fe700c2adada3a4d6b0ecf
|
ccf0d38f0e4e53ba7acddc01fd66c42e248a263c
|
/org/chartacaeli/caa/CAAVSOP87A_Neptune_jni.cxx
|
c54204ece0aacc600fd4dcedb0fac0570a6ab467
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
otabuzzman/chartacaeli-app
|
28b89c0f4ebb95d92a5a45d18755a0b1bdf6d206
|
881b4cf280a80b3ff7e4ff80f55aafa73607071b
|
refs/heads/master
| 2023-05-10T19:33:30.697791
| 2023-05-05T20:42:59
| 2023-05-05T20:42:59
| 49,746,695
| 2
| 0
|
MIT
| 2020-11-09T13:31:44
| 2016-01-15T21:45:11
|
Java
|
UTF-8
|
C++
| false
| false
| 2,067
|
cxx
|
CAAVSOP87A_Neptune_jni.cxx
|
// created by cxxwrap -- DO NOT EDIT
#include "jni.h"
#include "AAVSOP87A_NEP.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m0(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->X((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m1(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->X_DASH((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m2(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->Y((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m3(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->Y_DASH((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m4(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->Z((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jdouble JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1m5(JNIEnv* __env, jclass, jlong __imp, jdouble JD)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
double __retval = __obj->Z_DASH((double)JD);
return (jdouble) __retval;
}
JNIEXPORT jlong JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1cdefault(JNIEnv* __env, jobject)
{
CAAVSOP87A_Neptune* __obj = new CAAVSOP87A_Neptune();
return (jlong) __obj;
}
JNIEXPORT void JNICALL Java_org_chartacaeli_caa_CAAVSOP87A_1Neptune__1_1d(JNIEnv* __env, jobject, jlong __imp)
{
CAAVSOP87A_Neptune* __obj = (CAAVSOP87A_Neptune*) __imp;
delete __obj;
}
#ifdef __cplusplus
}
#endif
|
69d144ed50f48cb3055bca832826a5e4c021488a
|
960d6f70d83484d2b531d79002b5cc7fa8ad8063
|
/src/202.cpp
|
529abc13838cb16d7409faa50bc61ecf2b57caef
|
[] |
no_license
|
lintcoder/leetcode
|
688ce547331f377b68512135dd1033780f080e2b
|
384f316b5e713c0e15943cb4de6cf91ab0ff5881
|
refs/heads/master
| 2023-07-19T18:49:12.858631
| 2023-07-07T13:01:01
| 2023-07-07T13:01:01
| 74,862,636
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 496
|
cpp
|
202.cpp
|
bool isHappy(int n) {
set<int> st;
int sum = 0;
while (true)
{
sum = 0;
while (n != 0)
{
sum += (n % 10) * (n % 10);
n /= 10;
}
if (sum == 1)
break;
if (st.find(sum) == st.end())
{
st.insert(sum);
n = sum;
}
else
break;
}
return sum == 1;
}
|
a954f27d565a710fc1aae3312156306cead9794a
|
ec00df8410c9c8894f5127a4019be28c3c732542
|
/LightChaserAnim/katana_source_code/plugin_apis/include/FnScenegraphIterator/FnScenegraphIterator.h
|
dc8dc165fd13049ebb31d646eda0244cf7484de5
|
[] |
no_license
|
tws0002/aWorkingSource
|
580964ef39a7e5106d75136cfcd23814deecf0fd
|
188c081d261c11faa11766be41def34b7e01ee5e
|
refs/heads/master
| 2021-05-11T18:23:19.427869
| 2018-01-03T03:17:57
| 2018-01-03T03:17:57
| 117,823,716
| 1
| 0
| null | 2018-01-17T10:51:59
| 2018-01-17T10:51:59
| null |
UTF-8
|
C++
| false
| false
| 5,870
|
h
|
FnScenegraphIterator.h
|
// Copyright (c) 2012 The Foundry Visionmongers Ltd. All Rights Reserved.
#ifndef FnScenegraphIterator_H
#define FnScenegraphIterator_H
#include <string>
#include <FnPluginSystem/FnPluginSystem.h>
#include <FnAttribute/FnAttribute.h>
#include <FnScenegraphIterator/suite/FnScenegraphIteratorSuite.h>
namespace Foundry
{
namespace Katana
{
/**
* \defgroup SI Scenegraph Iterator (SI) API
* @{
*
*@brief API that allows to iterate through the locations and attributes on a Scenegraph.
*
* This API allows to iterate through the locations on a scenegraph and query
* their attributes. This is an auxiliary API that can be used when implementing,
* for example, a connection of Katana to a Renderer. In this specific case the
* renderer will have at some point to discover which locations and attributes
* exist on the Katana scene being rendered.
*
* Given the lazy initialization nature of Katana the scenegraph locations and
* attributes will be procedurally generated under the hood as the iterators
* go through the scene. Whenever a FnScenegraphIterator is instantiated Katana
* will generate its corresponding location if needed on that moment.
*
*/
/**
* @brief The Scenegraph Iterator that 'points' at a location in a scenegraph.
*
* Each instance of this class will be conceptually pointing at a specific
* location of the scenegraph. It presents methods that return other iterators
* that point at child, sibling, parent and other arbitraty locations on the
* scenegraph. The location pointed by the instance is referred here as "current
* location".
*/
class FnScenegraphIterator
{
public:
FnScenegraphIterator(FnSgIteratorHandle handle);
FnScenegraphIterator();
~FnScenegraphIterator();
FnScenegraphIterator(const FnScenegraphIterator& rhs);
FnScenegraphIterator& operator=(const FnScenegraphIterator& rhs);
/**
* @brief Returns true if this Scenegraph Iterator is valid.
*/
bool isValid() const {return _handle != 0x0;}
/**
* @brief Returns the name of the current Location. (ex: "pony" in "/root/world/geo/pony")
*/
std::string getName() const;
/**
* @brief Returns the full path name of the current Location. (ex: "/root/world/geo/pony")
*/
std::string getFullName() const;
/**
* @brief Returns the type of the current Location. (ex: "subdmesh" or "group")
*/
std::string getType() const;
/**
* @brief Returns an iterator that poins at the first child of the current location.
*/
FnScenegraphIterator getFirstChild(bool evict=false) const;
/**
* @brief Returns an iterator that poins at the next sibling of the current location.
*/
FnScenegraphIterator getNextSibling(bool evict=false) const;
/**
* @brief Returns an iterator that poins at the parent of the current location.
*/
FnScenegraphIterator getParent() const;
/**
* @brief Returns an iterator that poins at the root location of the scenegraph where
* the current locations lives.
*/
FnScenegraphIterator getRoot() const;
/**
* @return a list of immediate potential child names
*/
FnAttribute::StringAttribute getPotentialChildren() const;
/**
* @brief Returns an iterator which is child of the current one
*
* Returns an iterator that poins at the a child location of the current one
* with the specified name.
*
* @param name: the name of the child location
*/
FnScenegraphIterator getChildByName(const std::string &name, bool evict=false) const;
/**
* @brief Returns an iterator pointint at a specified location.
*
* Returns an iterator that poins at a location on the scenegraph where the
* current location lives specified by the forward slash-separated
* scenegraph path.
*
* @param name: the forward slash-separated path of the location
*/
FnScenegraphIterator getByPath(const std::string &path, bool evict=false) const;
/**
* @brief Get a specific attribute from the location pointed by the iterator.
*
* Returns an existing Attribute from the current Location if no location is
* specified. If there isn't any Attribute with the given name on the given
* Location then an invalid FnAttribute is returned (which can be checked
* with the function FnAttribute::isValid()).
*
* @param name The name of the attribute - can be a child of a GroupAttribute
* (ex: "geometry.point.P")
* @param global If false then the global attributes (inherited from parent
* Locations) will be ignored. In this case if the requested
* Attribute is global, then an invalid attribute is returned.
*
*/
FnAttribute::Attribute getAttribute(const std::string &name, bool global=false) const;
/**
* @brief Return the names of all the attributes on the location pointed by
* the iterator.
*
* @return A valid StringAttribute
*/
FnAttribute::StringAttribute getAttributeNames() const;
/**
* @return a GroupAttribute that represents the global transform for this
* location.
*/
FnAttribute::GroupAttribute getGlobalXFormGroup() const;
///@cond FN_INTERNAL_DEV
static FnPlugStatus setHost(FnPluginHost *host);
static FnSgIteratorHostSuite_v2 *_suite;
FnSgIteratorHandle getHandle() const
{
return _handle;
}
static FnScenegraphIterator getIteratorFromFile(
const std::string & opTreeFileName);
protected:
void acceptHandle(const FnScenegraphIterator &rhs);
private:
FnSgIteratorHandle _handle;
///@endcond
};
/// @}
} // namespace Katana
} // namespace Foundry
namespace FnKat = Foundry::Katana;
#endif // FnScenegraphIteratorSuite_H
|
c6ee8a9871511b4b8687f740753c85d0761a4e58
|
26d0a3e00d1e26765262ef51a94801d333034b28
|
/Framework/TTHbbAnalysis/TTHbbToolManager/Root/OfflineTRFFakes.cxx
|
4fd402e63def04f319fb08d40eff3ca45f07a5b3
|
[] |
no_license
|
sen-sourav/common-framework
|
f0d4a61ccda53dfca4adf649c93a579de3df8619
|
474383ba7f30d19a2836e19d8bc028b7d1f83f9a
|
refs/heads/master
| 2020-04-01T06:24:09.210670
| 2019-06-06T17:37:47
| 2019-06-06T17:37:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,341
|
cxx
|
OfflineTRFFakes.cxx
|
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "TTHbbToolManager/OfflineTRFFakes.h"
namespace TTHbb{
//___________________________________________________________________________
OfflineTRFFakes::OfflineTRFFakes(std::string name)
: ToolBase(false)
{
m_name = name;
}
//___________________________________________________________________________
OfflineTRFFakes::~OfflineTRFFakes()
{
}
//___________________________________________________________________________
void OfflineTRFFakes::initialise()
{
//--- Get info from config file
auto * config = TTHbb::GlobalConfiguration::get();
m_btagWPs = TTHbb::util::vectoriseString((*config)("MVAVariables.bTagWPs"));
m_parametrizations = TTHbb::util::vectoriseString((*config)("TRFFakes.parametrization"));
m_extrapRegions = TTHbb::util::vectoriseString((*config)("TRFFakes.regionExtrap"));
m_bTagHypotheses = TTHbb::util::vectoriseString((*config)("TRFFakes.bTagHypothesis"));
m_effmapPath = (*config)("TRFFakes.DataPath");
//--- Loop on parametrizations and extrapolation regions
for (auto param : m_parametrizations){
for (auto extrRegion : m_extrapRegions){
std::string config_id = Form("r%s_p%s", param.c_str(), extrRegion.c_str());
m_mapOfTRFFakes.insert(std::make_pair(config_id, std::make_shared<TRFFakesTool>()));
(m_mapOfTRFFakes[config_id])->setBtaggingWPs(m_btagWPs);
(m_mapOfTRFFakes[config_id])->setEffParam(param);
(m_mapOfTRFFakes[config_id])->setExtrapolatingRegion(extrRegion);
(m_mapOfTRFFakes[config_id])->setBTaggingHypotheses(m_bTagHypotheses);
(m_mapOfTRFFakes[config_id])->setEffMap(m_effmapPath);
(m_mapOfTRFFakes[config_id])->initialise();
}
}
}
//___________________________________________________________________________
void OfflineTRFFakes::apply(TTHbb::Event* event)
{
//--- Loop over instances
for (auto& trf : m_mapOfTRFFakes){
trf.second->apply(event);
}
}
//___________________________________________________________________________
void OfflineTRFFakes::finalise()
{
for (auto& trf : m_mapOfTRFFakes){
trf.second.reset();
}
m_mapOfTRFFakes.clear();
}
}
|
877dfb04510bc8d3a1d9b06cd3a7301b002293f5
|
5962264e9fe45cb42e71ea04a1c371886ace8989
|
/src/Point3D.h
|
8b02927aa3f68799ad568697da39519c626761e2
|
[] |
no_license
|
adickin/Simple-Ray-Tracer
|
7c53b0c75dd5b1c695818059cd52f55b5e750eb0
|
92d0bc42721a64c479b0e8d662765b62d89dec6a
|
refs/heads/master
| 2021-01-10T21:43:26.609641
| 2013-08-19T02:26:35
| 2013-08-19T02:26:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 656
|
h
|
Point3D.h
|
#ifndef POINT3D_H
#define POINT3D_H
/*
***************************************************************
*
* Represents a point in a 3D setting. Has functions to
* get and set the location of the point.
*
***************************************************************
*/
class Point3D
{
public:
Point3D();
Point3D(double x, double y, double z);
bool operator==(const Point3D &rhs);
Point3D operator-(const Point3D& rhs);
~Point3D();
double x() const;
double y() const;
double z() const;
void setX(double x);
void setY(double y);
void setZ(double z);
private:
double x_;
double y_;
double z_;
};
#endif
|
f1b1f17b52aa5fa139f141a1bfb6665bad863f46
|
78ed6000cb9f44cf6c748491bb9cd4637449a94c
|
/Utopian.cpp
|
340dc1b649816f6535ae36484c919e6c49ee9a4b
|
[
"MIT"
] |
permissive
|
kaushalvivek/programming-practice
|
d6593203fb8720b5becc74cd75043409f8bd5c46
|
23cb71b7c9a5144926ce472294d8f4113bcc5086
|
refs/heads/master
| 2022-04-03T17:22:37.774932
| 2020-02-17T16:19:30
| 2020-02-17T16:19:30
| 167,866,366
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 360
|
cpp
|
Utopian.cpp
|
#include <iostream>
using namespace std;
int main () {
long long int t,n,i = 1;
cin >> t;
while (t--) {
cin >> n;
while (1) {
if (n == 0) break;
n--;
i*=2;
if (n == 0) break;
n--;
i+=1;
}
cout << i << endl;
i = 1;
}
return 0;
}
|
3419ffaa8eb10155fc964490fb3f4f99b619db1d
|
47dbe359a17f1c4dca2693fb88b4f597c10306bf
|
/src/q0171.h
|
df45e4e2c69e6b779624a0655c9bea9744cfbbe1
|
[
"MIT"
] |
permissive
|
SeanWuLearner/leetcode
|
e253959b3d24d2ea9bb5e148f591ce99c83721a2
|
bafa93906fd586b6b6af929de1197d4f7347199d
|
refs/heads/master
| 2022-05-08T02:09:21.883279
| 2022-04-18T06:35:27
| 2022-04-18T06:35:27
| 192,561,135
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 761
|
h
|
q0171.h
|
/* Solution 1: left to right */
class Solution1 {
public:
int titleToNumber(string columnTitle) {
int res = 0;
for(auto &&c : columnTitle){
res *= 26;
res += c-'A'+1;
}
return res;
}
};
/* Solution 2: right to left */
class Solution {
public:
int titleToNumber(string columnTitle) {
int res = 0;
int base = 1;
for(auto it=columnTitle.rbegin(); it!=columnTitle.rend() ; it++){
auto c = *it;
res += (c-'A'+1) * base;
base *= 26;
}
return res;
}
};
TEST(Solution, Test1){
Solution s;
EXPECT_EQ(s.titleToNumber("A"), 1);
EXPECT_EQ(s.titleToNumber("AB"), 28);
EXPECT_EQ(s.titleToNumber("ZY"), 701);
}
|
298d364ca61b405831be2446a8aa856d1302f143
|
f4a1d188da99a79c392044d5a791dcfd233d9238
|
/22.11.2017/WordsArr.cpp
|
7d678d62d482ce1f4b68e24e1cb963dbebbbcb84
|
[] |
no_license
|
DanikSchastny/Homework
|
585303ee3310b01f16f3226bf0f30b8abbc09802
|
390489cec7e3a4f9749f40558724d6b9319dc15f
|
refs/heads/master
| 2021-04-25T13:19:13.204224
| 2018-01-15T05:08:50
| 2018-01-15T05:08:50
| 109,680,512
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,063
|
cpp
|
WordsArr.cpp
|
#include<iostream>
#define N 256
void displayWordsArray(char arr[][N], int count);
bool checkForSymb(char a);
void creatingWordArray(char words[][N], char arr[], int &count);
using namespace std;
int main()
{
int count = 0;
char words[N][N];
char str[256];
cout << "Enter your substring:" << endl;
cin.getline(str, 256);
creatingWordArray(words, str, count);
displayWordsArray(words, count);
system("pause");
return 0;
}
bool checkForSymb(char a)
{
if (a >= 'A' && a <= 'Z' || a >= 'a' && a <= 'z')
return true;
else
return false;
}
void creatingWordArray(char words[][N], char arr[], int &count)
{
int i = 0;
int j = 0;
int l = 0;
while (arr[i])
{
if (checkForSymb(arr[i]))
{
words[count][l] = arr[i];
++l;
}
else
{
l = 0;
++count;
}
}
}
void displayWordsArray(char arr[][N], int count)
{
int j = 0;
for (int i = 0; i < count; ++i)
{
while (arr[count][j])
{
cout << arr[count][j];
++j;
}
j = 0;
cout << endl;
}
}
|
e89f03a78051fe6a8c3adf4b646516aa82325b53
|
707269ea858b5ff1378809990b97dfa259b44197
|
/lab4/main1.cpp
|
1a80eaf27bbd4c32b35fb46af103245b532791c5
|
[] |
no_license
|
prosperevergreen/OOP-6303
|
d45f50ecf25dc9971be6c7c8b01fe10a58c8486f
|
eeba57cfb36358be7bfc181b0488462fb87ee7c6
|
refs/heads/master
| 2020-03-10T13:48:12.643043
| 2018-05-10T23:28:25
| 2018-05-10T23:28:25
| 129,408,807
| 0
| 0
| null | 2018-04-13T13:51:06
| 2018-04-13T13:51:05
| null |
UTF-8
|
C++
| false
| false
| 3,419
|
cpp
|
main1.cpp
|
#include <assert.h>
#include <algorithm>
#include <stdexcept>
#include <cstddef>
namespace stepik
{
template <class Type>
struct node
{
Type value;
node* next;
node* prev;
node(const Type& value, node<Type>* next, node<Type>* prev)
: value(value), next(next), prev(prev)
{
}
};
template <class Type>
class list
{
public:
typedef Type value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
list()
: m_head(nullptr), m_tail(nullptr)
{
}
void push_back(const value_type& value)
{
//resize(size() + 1);
//at(size() - 1) = value;
// implement this
if (empty())
{
node<Type>* tmp = new node<Type>(value,nullptr,nullptr);
m_head = tmp;
m_tail = tmp;
}
else
{
node<Type>* tmp = new node<Type>(value,nullptr,m_tail);
m_tail->next = tmp;
m_tail = tmp;
}
}
void push_front(const value_type& value)
{
if (empty())
{
node<Type>* tmp = new node<Type>(value,nullptr,nullptr);
m_head = tmp;
m_tail = tmp;
}
else
{
node<Type>* tmp = new node<Type>(value,m_head,nullptr);
m_head->prev = tmp;
m_head = tmp;
}
// implement this
}
reference front()
{
return m_head->value;
// implement this
}
const_reference front() const
{
return m_head->value;
// implement this
}
reference back()
{
return m_tail->value;
// implement this
}
const_reference back() const
{
return m_tail->value;
// implement this
}
void pop_front()
{
// implement this
if(!empty())
{
if(m_head->next)
{
m_head = m_head->next;
delete m_head->prev;
m_head->prev = nullptr;
}
else
{
m_tail = nullptr;
delete m_head;
m_head = nullptr;
}
}
}
void pop_back()
{
// implement this
if(!empty())
{
if(m_head->next)
{
m_tail = m_tail->prev;
delete m_tail->next;
m_tail->next = nullptr;
}
else
{
m_head = nullptr;
delete m_tail;
m_tail = nullptr;
}
}
}
void clear()
{
// implement this
node<Type>* tmp;
while(m_head != nullptr)
{
tmp = m_head -> next;
delete m_head;
m_head = tmp;
}
}
bool empty() const
{
// implement this
if (m_head == nullptr)
{
return true;
}
else
{
return false;
}
}
size_t size() const
{
// implement this
if (empty()){return 0;}
else
{
size_t kol = 0;
node<Type>* pre = m_head;
while(pre != nullptr)
{
pre = pre->next;
kol++;
}
return kol;
}
}
private:
//your private functions
node<Type>* m_head;
node<Type>* m_tail;
};
}// namespace stepik
|
ac4ac33ef30cc19e0dc3bcbf80f627c444d31efd
|
96c56ebeb52898f7a16275244662a0c5e460fbd4
|
/FoofLevelEditor (C++)/FoofLevelEditor/HazardousObject.h
|
f6c89b8c1b012a27843415dd7ccc38fc9d8e3d18
|
[] |
no_license
|
JIoffe/Flame-Broiled-Fury-BETA
|
2bcd25caaa8e6985fd22eb4c42a7a297b89318a1
|
0c4582a221f30a6d74f346a03c6c56a40753969d
|
refs/heads/master
| 2021-01-02T08:19:39.667221
| 2014-08-12T17:34:01
| 2014-08-12T17:34:01
| 22,886,301
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 199
|
h
|
HazardousObject.h
|
#pragma once
#include <string>
#include <cstdio>
#include "ExtendedObject.h"
struct HazardousObject : public ExtendedObject{
int Damage; //How much damage is done to the player?
int SpriteID;
};
|
b56edc8a7c67225e0c744c51954c04775c3b894b
|
4c2bddbcf17c40c477fd45ba8167480b62b5c471
|
/bubble.cpp
|
d2139efcd67dd05e577aacdd9249bd160a50c7cc
|
[] |
no_license
|
camilocorreaUdeA/funciones_cpp
|
b71556354ef5a1fc8bb1c3f168acfa598c9d9473
|
753424abc08ca591d45e1f57fb0348b37e040c77
|
refs/heads/main
| 2023-04-23T11:39:35.966033
| 2021-05-11T22:15:12
| 2021-05-11T22:15:12
| 366,525,207
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
cpp
|
bubble.cpp
|
void bubbleSort(int arr[], int n){
int var_aux = 0;
bool cambios = 0;
do{
cambios = 0;
for(int i=0; i<n-1; ++i){
if(arr[i] > arr[i+1]){
var_aux = arr[i];
arr[i] = arr[i+1];
arr[i+1] = var_aux;
cambios = 1;
}
}
}while(cambios);
}
|
c26a3648995208576dd107c8726e002dd2918e1a
|
664da94bf51c8fce8d915add639ba557fffc79d7
|
/Strings/Count And Say.cpp
|
b46181b1ab9e634f681916ce542c69841ad3e0b9
|
[] |
no_license
|
hackifme1/InterviewBit
|
471f2bb6d88538fbb0f0c8edd519bfa0518c98f0
|
f744b3f5d4aebd4a8d9738685bde49a94dabf038
|
refs/heads/main
| 2023-06-28T08:43:07.382810
| 2021-07-30T06:35:13
| 2021-07-30T06:35:13
| 371,326,433
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,154
|
cpp
|
Count And Say.cpp
|
// By Chandramani Kumar
// Keep moving and must be simple bro!!!!!
// Espérons le meilleur mais préparez-vous au pire 😎
/* Problem Statement :
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as one 1 or 11.
11 is read off as two 1s or 21.
21 is read off as one 2, then one 1 or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Example:
if n = 2,
the sequence is 11.
*/
Cpp code :
string Solution::countAndSay(int A) {
if (A == 0)
return "";
if (A == 1)
return "1";
string res = "1";
string str;
for (int i = 1; i < A; i++)
{
int len = res.size();
for (int j = 0; j < len; j++)
{
int cnt = 1;
while ((j + 1 < len) && (res[j] == res[j + 1]))
{
cnt++;
j++;
}
str += to_string(cnt) + res[j];
}
res = str;
str = "";
}
return res;
}
|
60599e914ea71dfe11be7c3b78d7903ecfd87379
|
fe6bd32b61622dab879a4b62824bd6a4b9a39eac
|
/finrecipes/all_cc_progs/term_structure_class_ho_lee_price_bond_option.cc
|
7f7cb7338e9ccecc37dde2bd5263fade971159ce
|
[] |
no_license
|
cheerzzh/Financial-Numerical-Recipes-in-CPP
|
d14aecf473b5183054072dd640d8e67655bcb7db
|
03c38451dc5b094b058393a5a3460cd550b2ed2b
|
refs/heads/master
| 2020-04-01T22:49:59.259140
| 2014-06-17T15:15:14
| 2014-06-17T15:15:14
| 19,804,081
| 8
| 12
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,020
|
cc
|
term_structure_class_ho_lee_price_bond_option.cc
|
#include "fin_recipes.h"
class time_contingent_cash_flows{
public:
vector<double> times;
vector<double> cash_flows;
time_contingent_cash_flows(const vector<double>& in_times, const vector<double>& in_cflows){
times=in_times; cash_flows=in_cflows;
};
int no_cflows(){ return times.size(); };
};
vector<time_contingent_cash_flows>
build_time_series_of_bond_time_contingent_cash_flows(const vector<double>& initial_times,
const vector<double>& initial_cflows){
vector<time_contingent_cash_flows> vec_cf;
vector<double> times = initial_times;
vector<double> cflows = initial_cflows;
while (times.size()>0){
vec_cf.push_back(time_contingent_cash_flows(times,cflows));
vector<double> tmp_times;
vector<double> tmp_cflows;
for (int i=0;i<times.size();++i){
if (times[i]-1.0>=0.0) {
tmp_times.push_back(times[i]-1);
tmp_cflows.push_back(cflows[i]);
};
};
times = tmp_times; cflows = tmp_cflows;
};
return vec_cf;
};
double price_european_call_option_on_bond_using_ho_lee(term_structure_class* initial, const double& delta, const double& pi,
const vector<double>& underlying_bond_cflow_times,
const vector<double>& underlying_bond_cflows,
const double& K, const double& time_to_maturity){
int T = int(time_to_maturity+0.0001);
vector<vector<term_structure_class_ho_lee> > hl_tree
= term_structure_ho_lee_build_term_structure_tree(initial,T+1,delta,pi);
vector<time_contingent_cash_flows> vec_cf
= build_time_series_of_bond_time_contingent_cash_flows(underlying_bond_cflow_times, underlying_bond_cflows);
vector<double> values(T+1);
for (int i=0;i<=T;++i){
values[i]=max(0.0,bonds_price(vec_cf[T+1].times, vec_cf[T+1].cash_flows, hl_tree[T+1][i]) - K);
};
for (int t=T;t>=0;--t){
vector<double> values_this(t+1);
for (int i=0;i<=t;++i){ values_this[i]=(pi*values[i+1]+(1.0-pi)*values[i])*hl_tree[t][i].d(1); };
values=values_this;
};
return values[0];
};
|
acee18f2b4d9ad7f87155300da854ce6eaf48b4d
|
f2b47b588239e413b957a12ec2d7ca2fff13fe95
|
/Logica_programacao/while/ex_9.cpp
|
e22843dcc30a6e5d20253922b429365641160bbe
|
[] |
no_license
|
SFV-CORE/ETEC1
|
1011bc58c43dabf4dbec2b405d5ca46eeabeafba
|
96de944586d2c9620a638a5303ccfc60945ba54f
|
refs/heads/master
| 2023-02-26T11:08:33.722711
| 2021-02-01T21:24:09
| 2021-02-01T21:24:09
| 297,482,352
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 306
|
cpp
|
ex_9.cpp
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
float n1,n2;
printf("Digite o primeiro:");
scanf("%f",&n1);
printf("Digite o utimo: ");
scanf("%f",&n2);
if(n1>n2)
{
while(n1>=n2)
{
printf("%f",n1);
n1=n1-1;
}
}
else
{
while(n2<=n1)
{
printf("%.f\n",n2);
n2++;
}
}
}
|
997d1d1c626ace35480016cab90afa29dadbf43b
|
04e13fb481d80ed3b678eb33894de8d39a68ef88
|
/MathF.h
|
660b2a5f8f51f485c3084bdaa6164dd917c1aaed
|
[] |
no_license
|
swordjoinmagic/Study-Notes-For-Direct3D11
|
4e938dfc29b633f06feb55f9cfef8ebe8bc96c16
|
db51ecd6f1daea500c8de20ab77cad50cf8a9972
|
refs/heads/master
| 2020-09-05T04:49:43.847672
| 2020-02-07T09:02:09
| 2020-02-07T09:02:09
| 219,986,193
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 129
|
h
|
MathF.h
|
#pragma once
class MathF {
public:
static const float PI;
static const float Deg2Rad;
static float Radians(float angle);
};
|
0eb37cbfd0e3b18528fa9dbb667b7d22eddabb30
|
f9f3e379f73ef398a9c6bde2b74eb1730eb7b98e
|
/src/parser/TriggerEvent.hpp
|
0f212be12f949b41e074a15e2c293c8e313e3f17
|
[
"Unlicense"
] |
permissive
|
rlucca/aslan
|
a461f139fcb6823b743653c41a0747e906290b38
|
1f283c22fb72f717c590cf11482ac97c171f8518
|
refs/heads/master
| 2016-09-05T13:48:31.023626
| 2015-02-06T00:59:38
| 2015-02-06T00:59:38
| 24,392,920
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 436
|
hpp
|
TriggerEvent.hpp
|
#pragma once
class Trigger : public Symbol
{
public:
Trigger(unsigned line, char *lex);
virtual ~Trigger();
virtual unsigned char triggerType() = 0;
};
class AdditionTrigger : public Trigger
{
public:
AdditionTrigger(unsigned line, char *lex);
virtual unsigned char triggerType();
};
class DeletionTrigger : public Trigger
{
public:
DeletionTrigger(unsigned line, char *lex);
virtual unsigned char triggerType();
};
|
7f5a9e680a4877ccd3148c4ca6614e70cf1d3059
|
a4d8cb480cbdb196e79ce482f5f9221fc74855e2
|
/2011/201102/20110205_asio_ftp_act.cpp
|
d76576374047c2020965e2454c914e2294f98190
|
[] |
no_license
|
bonly/exercise
|
96cd21e5aa65e2f4c8ba18adda63c28a5634c033
|
dccf193a401c386719b8dcd7440d1f3bb74cb693
|
refs/heads/master
| 2020-05-06T13:51:29.957349
| 2018-02-10T16:14:52
| 2018-02-10T16:14:52
| 3,512,855
| 1
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 3,759
|
cpp
|
20110205_asio_ftp_act.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <cstdio>
#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/thread.hpp>
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::pair;
using namespace boost::asio;
using boost::asio::ip::tcp;
using boost::system::error_code;
using boost::system::system_error;
using boost::thread;
struct callable
{
private:
string _hostname;
string _port;
public:
callable(const string& hostname, const string& port) : _hostname(hostname), _port(port)
{
}
void operator()()
{
io_service ios;
ip::tcp::resolver resolver(ios);
ip::tcp::resolver::query query(_hostname, _port);
ip::tcp::resolver::iterator it = resolver.resolve(query);
ip::tcp::endpoint ep = *it;
tcp::acceptor server(ios, ep);
tcp::socket client(ios);
server.accept(client);
cout << "main(): client accepted from " << client.remote_endpoint().address() << endl;
const int BUFLEN = 8192;
vector<char> buf(BUFLEN);
error_code error;
int len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
}
};
int main()
{
try
{
io_service ios;
ip::tcp::resolver resolver(ios);
ip::tcp::resolver::query query("183.60.126.26", "21"); ///ftp
ip::tcp::resolver::iterator it = resolver.resolve(query);
ip::tcp::endpoint endpoint = *it;
ip::tcp::socket client(ios);
client.connect(endpoint);
const int BUFLEN = 1024;
vector<char> buf(BUFLEN);
error_code error;
int len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
string request = "USER bonly\r\n"; ///
cout << request;
client.send(buffer(request, request.size()));
len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
request = "PASS 111111\r\n"; ///
cout << request;
client.send(buffer(request, request.size()));
len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
request = "PORT 0,0,0,0,195,80\r\n"; /// 195×256+80=50000
cout << request;
client.send(buffer(request, request.size()));
len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
callable call("0.0.0.0", "50000"); ///
thread th(call);
request = "RETR test.txt\r\n"; ///
cout << request;
client.send(buffer(request, request.size()));
len = client.receive(buffer(buf, BUFLEN), 0, error);
cout.write(buf.data(), len);
cout << endl;
th.join();
}
catch (system_error& exc)
{
cout << "main(): exc.what()=" << exc.what() << endl;
}
return EXIT_SUCCESS;
}
|
8e0c1add2359f077b364c3f7859cad4c788e2ac4
|
02eaeecc510492a7bc5d9f6b7d09b29d6053a15b
|
/test/typelist/size_test.cpp
|
2ca2fcb59b7e11189256a3ebcfb397bcbe4041e0
|
[
"MIT"
] |
permissive
|
matrixjoeq/candy
|
a5160e3dbbb76ce0674580222abab0e837039254
|
53fe18d8b68d2f131c8e1c8f76c7d9b7f752bbdc
|
refs/heads/master
| 2020-07-09T14:28:40.908162
| 2020-02-11T08:58:18
| 2020-02-11T08:58:18
| 203,995,650
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 452
|
cpp
|
size_test.cpp
|
#include <type_traits>
#include "typelist/size.hpp"
namespace candy {
namespace test {
namespace {
struct FirstType;
struct SecondType;
using EmptyTL = Typelist<>;
using FirstTL = Typelist<FirstType>;
using SecondTL = Typelist<FirstType, SecondType>;
static_assert(Size<EmptyTL>::value == 0, "");
static_assert(Size<FirstTL>::value == 1, "");
static_assert(Size<SecondTL>::value == 2, "");
} // namespace
} // namespace test
} // namespace candy
|
6e8e6a2e9778e7c5f57c6eae6cc43cda0a42b4ef
|
aab8466fa27520c20f8d7e760b6d6b3a6a0aaaf1
|
/include/vo.h
|
5d77f65b322c722b4a3068996c1020300a4a95a5
|
[] |
no_license
|
YimengZhu/Kitti-Stereo-VO
|
e75bfc7f2b36660f55490a63a6858a5abfb6b7d0
|
582af7a46436fea7bce971e5632e4241a5442d89
|
refs/heads/master
| 2020-12-11T19:07:25.341236
| 2020-01-19T18:04:48
| 2020-01-19T18:04:48
| 233,933,554
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,078
|
h
|
vo.h
|
#ifndef VISUALODOMETRY_H
#define VISUALODOMETRY_H
#include "g2o_types.h"
#include "config.h"
#include <memory>
#include "map.h"
#include "ORBextractor.h"
#include <vector>
#include <math.h>
#include <opencv2/core/core.hpp>
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <sophus/se3.h>
#include <sophus/so3.h>
using namespace Sophus;
using namespace cv;
class VisualOdometry{
public:
typedef shared_ptr<VisualOdometry> Ptr;
enum VOState{
INITIALIZING = -1,
OK = 0,
LOST
};
VOState state_;
SLAMMap::Ptr map_;
Frame::Ptr ref_, curr_;
vector<Point3f> pts_3d_ref_;
ORBextractor *ORBextractorLeft_, *ORBextractorRight_;
vector<cv::KeyPoint> keypoints_curr_left_, keypoints_curr_right_;
Mat descriptors_curr_left_, descriptors_curr_right_, descriptors_ref_left_;
vector<DMatch> feature_matches_;
SE3 T_c_r_estimated_;
int num_inliers_, num_lost_;
int mnScaleLevels;
float mfScaleFactor, mfLogScaleFactor;
vector <float> mvScaleFactors, mvInvScaleFactors, mvLevelSigma2, mvInvLevelSigma2;
float match_ratio_;
int max_num_lost_, min_inliers_;
double key_frame_min_rot_, key_frame_min_trans_;
float mbf_, mb_;
vector<float> mvuRight_, mvDepth_;
VisualOdometry();
~VisualOdometry();
bool addFrame(Frame::Ptr frame);
protected:
void extractORB_left(const Mat& imageleft);
void extractORB_right(const Mat& imageright);
void extractKeyPoints(const Mat& left, const Mat& right);
void computeStereoMatches();
void featureMatching();
void setRef3DPoints();
void poseEstimationPnP();
void addKeyFrame();
bool checkEstimatedPose();
bool checkKeyFrame();
};
#endif
|
a1ef16f80d7ffa0da8b23c79d67516678164fd8a
|
3ad67e6008041614513fb344c8a13d2f84f17270
|
/Лабораторная работа №15/ферзи/8fersp.cpp
|
5dd77feac91de815c8e7f93b9e395f60d0f66504
|
[] |
no_license
|
Polina-Eremeeva29/Labs_PSTU
|
975d3db3bd49e57a1338aee362cbb913fdaa5e49
|
81d3ba720cc5e99d2a9f3ce341a5d812bf0f3d17
|
refs/heads/master
| 2022-11-10T17:11:22.069314
| 2020-06-23T10:55:28
| 2020-06-23T10:55:28
| 256,132,666
| 2
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,321
|
cpp
|
8fersp.cpp
|
#include <iostream>
using namespace std;
int board[8][8];
int rcount = 0;// кол-во решений
//отображение доски
void Board() {
int k = 1;
while (k < 9) {
cout << k << "-ый шаг:" << endl;
for (int i = 0; i < k; i++) {
for (int j = 0; j < 8; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
cout << "-------------------" << endl;
k++;
}
}
//совпадение с ходами других ферзей
bool setQueen(int a, int b)
{
for (int i = 0; i < a; i++) {
if (board[i][b]) return false;//Проверка совпадений по горизонтали и вертикали
}
for (int i = 1; i <= a && b - i >= 0; i++) {
if (board[a - i][b - i]) return false;//Проверка главной диагонали
}
for (int i = 1; i <= a && b + i < 8; i++) {
if (board[a - i][b + i]) return false;//Проверка побочной диагонали
}
return true;
}
void Queen(int a) {
int k = 0;
if (a == 8) {
Board();
++rcount;
}
if (rcount==1)
{
return;
}
for (int i = 0; i < 8; i++) {
if (setQueen(a, i)) {
board[a][i] = 1;
Queen(a + 1);
board[a][i] = 0;
}
}
}
int main()
{
setlocale(LC_ALL, "ru");
Queen(0);
return 0;
}
|
41bd582577cb9e43eb6443b7b280c6610d9ed1c1
|
ace20ae898aadf18c4ef8a2355b528422fc27bb5
|
/codeforces/924C.cpp
|
a77efdabdd5c6e14bb485383f996a777e11e3b18
|
[] |
no_license
|
pidddgy/competitive-programming
|
19fd79e7888789c68bf93afa3e63812587cbb0fe
|
ec86287a0a70f7f43a13cbe26f5aa9c5b02f66cc
|
refs/heads/master
| 2022-01-28T07:01:07.376581
| 2022-01-17T21:37:06
| 2022-01-17T21:37:06
| 139,354,420
| 0
| 3
| null | 2021-04-06T16:56:29
| 2018-07-01T19:03:53
|
C++
|
UTF-8
|
C++
| false
| false
| 857
|
cpp
|
924C.cpp
|
// https://codeforces.com/contest/924/problem/C
#include <bits/stdc++.h>
using namespace std;
#define watch(x) cerr << (#x) << " is " << (x) << endl;
#define endl '\n'
#define cerr if(false) cerr
#define int long long
const int maxn = 100500;
// prefix max
int pma[maxn], a[maxn], marks[maxn];
signed main() {
ios::sync_with_stdio(0);
cin.sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
int ma = 0;
for(int i = 1; i <= n; i++) {
cin >> a[i];
ma = max(ma, a[i]);
pma[i] = ma;
}
for(int i = n; i >= 1; i--) {
marks[i] = max(marks[i+1]-1, pma[i]+1);
}
for(int i = 1; i <= n; i++) {
cerr << marks[i] << " ";
}
cerr << endl;
int ans = 0;
for(int i = 1; i <= n; i++) {
ans += marks[i]-a[i]-1;
}
cerr << endl;
cout << ans << endl;
}
|
b90c6af59d364030de006c8a03f9a95c64da1137
|
0ba1f2b10ed584443725e71429134cf440a57e83
|
/Linked Lists/remove_nth_node_from_end.cpp
|
aee157396a071d7bed1cd42a5811d149949479a1
|
[] |
no_license
|
harpreets152/interviewbit-problems
|
7e793e6c8aa4afe90729465de8151e620ddcc917
|
2396cdce92b2d2df376aefdb961a1c2e2f255240
|
refs/heads/master
| 2020-03-17T10:20:33.124157
| 2018-06-17T06:35:22
| 2018-06-17T06:35:22
| 133,508,946
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 861
|
cpp
|
remove_nth_node_from_end.cpp
|
/*
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
If n is greater than the size of the list, remove the first node of the list.
Try doing it using constant additional space.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::removeNthFromEnd(ListNode* A, int n) {
ListNode *head=A,*curr=A;
int i=1;
while(head && i<=n){
i++;
head=head->next;
}
if(!head) return curr->next;
while(head->next!=NULL){
curr=curr->next;
head=head->next;
}
curr->next=curr->next->next;
return A;
}
|
d9f781e957064554d7dbafef982ad95ef5a92a21
|
4e1b3ebb3d45fe22865a14cb4c3309e7c0f545de
|
/C++/LinkedList/linkedlist2.cpp
|
666a786c7edb2e8eeda83ded88f7ded6eab0fc08
|
[] |
no_license
|
smansur2/MyCode
|
0bfead522d03f87842b9f46fcc6c5e41eaf7f258
|
155b705df027bc44d5e4ea7546df6b818e6bbbb4
|
refs/heads/master
| 2021-08-23T07:01:31.077216
| 2017-12-04T01:56:48
| 2017-12-04T01:56:48
| 104,818,067
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,476
|
cpp
|
linkedlist2.cpp
|
class LinkedList2{
private:
class Node{
public:
int v;
Node* next;
Node():next(nullptr){}
Node(int x, Node* n):v(x),next(n){}
}
Node* head;
Node* tail(){
Node* p = head;
for(;p-next!=nullptr;p=p->next)
;
tail = p;
}
public:
LinkedList2():{
head=tail=nullptr;
}
~LinkedList2():{
Node* p = head;
Node* temp = head;
for(;p->next!=nullptr;p=temp){
delete p;
temp = temp->next;
}
}
void addFirst(int x){
if(head==nullptr){
head=tail=new Node(x,nullptr);
return;
}
Node* temp = new Node(x,head);
head = temp;
}
void addEnd(int x){
if(head==nullptr){
head=tail=new Node(x,nullptr);
return;
}
tail->next = new Node(x,nullptr);
}
void removeFront(){
if(head->next==nullptr){
delete head;
head = tail = nullptr;
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
void removeBack(){
if(head->next==nullptr){
delete head;
head = tail = nullptr;
return;
}
Node* temp = head;
for(;temp->next!=tail;temp=temp->next)
;
temp->next = nullptr;
delete tail;
tail = temp;
}
void insertAfter(Node* p, int v){
if(p->next==nullptr){
addEnd(v);
return;
}
p->next= new Node(v,p->next);
}
}
|
ddc352cdb2dd65b5fb2f8ed94c20fccc2c9eb365
|
7992378d4d8746fef5d6c8490a1851f489ac4373
|
/homework2/output.cc
|
7a584aceb63d1b57e17d96c0f88073341d63c1b4
|
[] |
no_license
|
moeheart/PublicCourse
|
40e13eb6e9dfd29f3d3598643e091932eb05c5d8
|
cb7542784570786d09621f3f9885ffe139dbbb62
|
refs/heads/master
| 2021-04-05T23:48:36.851942
| 2018-03-31T08:03:51
| 2018-03-31T08:03:51
| 124,726,600
| 0
| 0
| null | 2018-03-11T05:35:29
| 2018-03-11T05:35:29
| null |
UTF-8
|
C++
| false
| false
| 989
|
cc
|
output.cc
|
// Copyright @2018 Pony AI Inc. All rights reserved.
#include <iostream>
#include <fstream>
#include <iomanip>
#include "homework2/pointcloud.h"
int main() {
// ATTENTION!!! : please use absolute path for reading the data file.
const PointCloud pointcloud = ReadPointCloudFromTextFile(
"/home/ubuntu/PublicCourse/homework2/sample_data/VelodyneDevice32c/0.txt");
std::cout << "Total points read: " << pointcloud.points.size() << std::endl;
std::cout << "Rotation: " << std::endl;
std::cout << pointcloud.rotation << std::endl;
std::cout << "Translation: " << std::endl;
std::cout << pointcloud.translation.transpose() << std::endl;
std::ofstream fout("/home/ubuntu/PublicCourse/homework2/p1.txt");
fout<<"Range"<<std::endl;
for (Eigen::Vector3d p : pointcloud.points) {
fout<<sqrt(p(0)*p(0)+p(1)*p(1)+p(2)*p(2))<<std::endl;
}
fout<<"Height"<<std::endl;
for (Eigen::Vector3d p : pointcloud.points) {
fout<<p(2)<<std::endl;
}
return 0;
}
|
917e867da10da0f0c7396fbad46c3da541e0ed5c
|
105e40cd7ba8b7a8c29b4210e74cc1bec64d51bc
|
/特征.h
|
36b473112b4c769e7fce1d26888ab31619bcca25
|
[] |
no_license
|
ArtificialZeng/202105-WEIXIN
|
32adf6d1bb997b8a5ec830c87492e0de74550716
|
bb404ba190be3698f224dc7a4918c9d880c0afcd
|
refs/heads/main
| 2023-07-09T10:22:05.648174
| 2021-08-10T11:48:25
| 2021-08-10T11:48:25
| 394,692,792
| 1
| 0
| null | 2021-08-10T14:53:05
| 2021-08-10T14:53:04
| null |
UTF-8
|
C++
| false
| false
| 13,528
|
h
|
特征.h
|
#pragma once
#include <cstdint>
#include <cmath>
#include "行爲.h"
struct 結構_特征
{
public:
uint32_t 樣本數 = 0;
uint32_t 設備和 = 0;
uint32_t 標籤數陣列[7]{ 0 };
uint32_t 視訊時長和 = 0;
float 播放時長和 = 0;
float 停留時長和 = 0;
void 新增行爲(const std::shared_ptr<結構_訓練行爲> 行爲指針, uint32_t 視訊時長)
{
樣本數 += 1;
設備和 += 行爲指針->設備;
for (auto 甲 = 0; 甲 < 7; 甲++)
標籤數陣列[甲] += 行爲指針->標籤陣列[甲];
視訊時長和 += 視訊時長;
播放時長和 += 行爲指針->播放時長;
停留時長和 += 行爲指針->停留時長;
}
void 新增測試行爲(const std::shared_ptr<結構_測試行爲> 行爲指針, uint16_t 視訊時長)
{
樣本數 += 1;
設備和 += 行爲指針->設備;
視訊時長和 += 視訊時長;
}
void 合併(const 結構_特征& 特征)
{
樣本數 += 特征.樣本數;
設備和 += 特征.設備和;
for (auto 甲 = 0; 甲 < 7; 甲++)
標籤數陣列[甲] += 特征.標籤數陣列[甲];
視訊時長和 += 特征.視訊時長和;
播放時長和 += 特征.播放時長和;
停留時長和 += 特征.停留時長和;
}
static auto 輸出(
std::vector<uint16_t>& 資料向量, const 結構_特征& 總特征
, uint32_t 非當折樣本數, uint32_t 非當折標籤數陣列[], uint32_t 非當折視訊時長和, float 非當折播放時長和, float 非當折停留時長和
, float 空值, bool 加入樣本數否, bool 加入設備平均值否, bool 加入視訊時長平均值否, bool 加入播放停留時長否)
{
auto 半精度空值 = 轉半精度(空值);
if (加入樣本數否)
資料向量.emplace_back(轉半精度(0.0001f * 總特征.樣本數));
if (非當折樣本數 > 0)
{
for (auto 甲 = 0; 甲 < 7; 甲++)
資料向量.emplace_back(轉半精度(float(非當折標籤數陣列[甲]) / 非當折樣本數));
}
else
{
for (auto 甲 = 0; 甲 < 7; 甲++)
資料向量.emplace_back(半精度空值);
}
if (加入設備平均值否)
{
if (總特征.樣本數 > 0)
資料向量.emplace_back(轉半精度(float(總特征.設備和) / 總特征.樣本數));
else
資料向量.emplace_back(半精度空值);
}
if (加入視訊時長平均值否)
{
if (總特征.樣本數 > 0)
資料向量.emplace_back(轉半精度(float(總特征.視訊時長和) / 總特征.樣本數));
else
資料向量.emplace_back(半精度空值);
}
if (加入播放停留時長否)
{
if (非當折樣本數 > 0)
{
資料向量.emplace_back(轉半精度(非當折播放時長和 / 非當折樣本數));
資料向量.emplace_back(轉半精度(非當折停留時長和 / 非當折樣本數));
資料向量.emplace_back(轉半精度((非當折停留時長和 - 非當折播放時長和) / 非當折樣本數));
資料向量.emplace_back(轉半精度(非當折播放時長和 / 非當折視訊時長和));
資料向量.emplace_back(轉半精度(非當折停留時長和 / 非當折視訊時長和));
}
else
{
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
}
}
}
static auto 空輸出(std::vector<uint16_t>& 資料向量, bool 加入樣本數否, bool 加入設備平均值否, bool 加入視訊時長平均值否, bool 加入播放停留時長否)
{
auto 半精度空值 = 轉半精度(NAN);
if (加入樣本數否)
資料向量.emplace_back(半精度空值);
for (auto 甲 = 0; 甲 < 7; 甲++)
資料向量.emplace_back(半精度空值);
if (加入設備平均值否)
資料向量.emplace_back(半精度空值);
if (加入視訊時長平均值否)
資料向量.emplace_back(半精度空值);
if (加入播放停留時長否)
{
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
資料向量.emplace_back(半精度空值);
}
}
static auto 輸出以陣列陣列(std::vector<uint16_t>& 資料向量, const 結構_特征** 折特征陣列陣列, uint32_t 標識, std::vector<uint32_t> 排除折向量, float 空值 = NAN, bool 加入樣本數否 = false, bool 加入設備平均值否 = false, bool 加入視訊時長平均值否 = false, bool 加入播放停留時長否 = false)
{
auto&& 總特征 = 折特征陣列陣列[0][標識];
auto 非當折樣本數 = 總特征.樣本數;
uint32_t 非當折標籤數陣列[7];
for (auto 甲 = 0; 甲 < 7; 甲++)
非當折標籤數陣列[甲] = 總特征.標籤數陣列[甲];
auto 非當折視訊時長和 = 總特征.視訊時長和;
auto 非當折播放時長和 = 總特征.播放時長和;
auto 非當折停留時長和 = 總特征.停留時長和;
for (auto 甲 : 排除折向量)
{
auto&& 甲折特征 = 折特征陣列陣列[甲][標識];
非當折樣本數 -= 甲折特征.樣本數;
for (auto 乙 = 0; 乙 < 7; 乙++)
非當折標籤數陣列[乙] -= 甲折特征.標籤數陣列[乙];
非當折視訊時長和 -= 甲折特征.視訊時長和;
非當折播放時長和 -= 甲折特征.播放時長和;
非當折停留時長和 -= 甲折特征.停留時長和;
}
輸出(資料向量, 總特征, 非當折樣本數, 非當折標籤數陣列, 非當折視訊時長和, 非當折播放時長和, 非當折停留時長和, 空值, 加入樣本數否, 加入設備平均值否, 加入視訊時長平均值否, 加入播放停留時長否);
}
static auto 輸出以映射指針陣列(std::vector<uint16_t>& 資料向量, const std::unordered_map<std::string, 結構_特征> 折交叉特征映射陣列[1 + 折數], const std::string& 標識, std::vector<uint32_t> 排除折向量, float 空值 = NAN, bool 加入樣本數否 = false, bool 加入設備平均值否 = false, bool 加入視訊時長平均值否 = false, bool 加入播放停留時長否 = false)
{
if (折交叉特征映射陣列[0].find(標識) == 折交叉特征映射陣列[0].end())
{
空輸出(資料向量, 加入樣本數否, 加入設備平均值否, 加入視訊時長平均值否, 加入播放停留時長否);
return;
}
auto&& 總特征 = 折交叉特征映射陣列[0].at(標識);
auto 非當折樣本數 = 總特征.樣本數;
uint32_t 非當折標籤數陣列[7];
for (auto 甲 = 0; 甲 < 7; 甲++)
非當折標籤數陣列[甲] = 總特征.標籤數陣列[甲];
auto 非當折視訊時長和 = 總特征.視訊時長和;
auto 非當折播放時長和 = 總特征.播放時長和;
auto 非當折停留時長和 = 總特征.停留時長和;
for (auto 甲 : 排除折向量)
{
if (折交叉特征映射陣列[甲].find(標識) == 折交叉特征映射陣列[甲].end())
continue;
auto&& 甲折特征 = 折交叉特征映射陣列[甲].at(標識);
非當折樣本數 -= 甲折特征.樣本數;
for (auto 乙 = 0; 乙 < 7; 乙++)
非當折標籤數陣列[乙] -= 甲折特征.標籤數陣列[乙];
非當折視訊時長和 -= 甲折特征.視訊時長和;
非當折播放時長和 -= 甲折特征.播放時長和;
非當折停留時長和 -= 甲折特征.停留時長和;
}
輸出(資料向量, 總特征, 非當折樣本數, 非當折標籤數陣列, 非當折視訊時長和, 非當折播放時長和, 非當折停留時長和, 空值, 加入樣本數否, 加入設備平均值否, 加入視訊時長平均值否, 加入播放停留時長否);
}
static auto 輸出以映射陣列陣列(std::vector<uint16_t>& 資料向量, const std::map<std::string, 結構_特征>* 折用戶作者類別特征映射陣列陣列[1 + 折數], int 標識, const std::string& 第二標識, std::vector<uint32_t> 排除折向量, float 空值 = NAN, bool 加入樣本數否 = false, bool 加入設備平均值否 = false, bool 加入視訊時長平均值否 = false, bool 加入播放停留時長否 = false)
{
if (折用戶作者類別特征映射陣列陣列[0][標識].find(第二標識) == 折用戶作者類別特征映射陣列陣列[0][標識].end())
{
空輸出(資料向量, 加入樣本數否, 加入設備平均值否, 加入視訊時長平均值否, 加入播放停留時長否);
return;
}
auto&& 總特征 = 折用戶作者類別特征映射陣列陣列[0][標識].at(第二標識);
auto 非當折樣本數 = 總特征.樣本數;
uint32_t 非當折標籤數陣列[7];
for (auto 甲 = 0; 甲 < 7; 甲++)
非當折標籤數陣列[甲] = 總特征.標籤數陣列[甲];
auto 非當折視訊時長和 = 總特征.視訊時長和;
auto 非當折播放時長和 = 總特征.播放時長和;
auto 非當折停留時長和 = 總特征.停留時長和;
for (auto 甲 : 排除折向量)
{
if (折用戶作者類別特征映射陣列陣列[甲][標識].find(第二標識) == 折用戶作者類別特征映射陣列陣列[甲][標識].end())
continue;
auto&& 甲折特征 = 折用戶作者類別特征映射陣列陣列[甲][標識].at(第二標識);
非當折樣本數 -= 甲折特征.樣本數;
for (auto 乙 = 0; 乙 < 7; 乙++)
非當折標籤數陣列[乙] -= 甲折特征.標籤數陣列[乙];
非當折視訊時長和 -= 甲折特征.視訊時長和;
非當折播放時長和 -= 甲折特征.播放時長和;
非當折停留時長和 -= 甲折特征.停留時長和;
}
輸出(資料向量, 總特征, 非當折樣本數, 非當折標籤數陣列, 非當折視訊時長和, 非當折播放時長和, 非當折停留時長和, 空值, 加入樣本數否, 加入設備平均值否, 加入視訊時長平均值否, 加入播放停留時長否);
}
};
struct 結構_二級特征
{
public:
uint32_t 一級特征數 = 0;
float 一級特征加權標籤和陣列[7]{ 0 };
float 一級特征播放時長平均值和 = 0;
float 一級特征停留時長平均值和 = 0;
float 一級特征視訊時長平均值和 = 0;
void 新增特征(const std::shared_ptr<結構_訓練行爲> 行爲指針, const 結構_特征& 用戶設備特征)
{
一級特征數 += 1;
for (auto 甲 = 0; 甲 < 7; 甲++)
一級特征加權標籤和陣列[甲] += 1 / (1 + float(pow(用戶設備特征.標籤數陣列[甲], 0.5)));
一級特征播放時長平均值和 += 用戶設備特征.播放時長和 / 用戶設備特征.樣本數;
一級特征停留時長平均值和 += 用戶設備特征.停留時長和 / 用戶設備特征.樣本數;
一級特征視訊時長平均值和 += 用戶設備特征.視訊時長和 / 用戶設備特征.樣本數;
}
void 合併(const 結構_二級特征& 二級特征)
{
一級特征數 += 二級特征.一級特征數;
for (auto 甲 = 0; 甲 < 7; 甲++)
一級特征加權標籤和陣列[甲] += 二級特征.一級特征加權標籤和陣列[甲];
一級特征播放時長平均值和 += 二級特征.一級特征播放時長平均值和;
一級特征停留時長平均值和 += 二級特征.一級特征停留時長平均值和;
一級特征視訊時長平均值和 += 二級特征.一級特征視訊時長平均值和;
}
static auto 輸出以陣列陣列(std::vector<uint16_t>& 資料向量, const 結構_二級特征** 折二級特征陣列陣列, uint32_t 標識, std::vector<uint32_t> 排除折向量)
{
auto&& 總特征 = 折二級特征陣列陣列[0][標識];
auto 非當折一級特征數 = 總特征.一級特征數;
float 非當折加權標籤和陣列[7];
for (auto 甲 = 0; 甲 < 7; 甲++)
非當折加權標籤和陣列[甲] = 總特征.一級特征加權標籤和陣列[甲];
auto 非當折一級特征播放時長平均值 = 總特征.一級特征播放時長平均值和;
auto 非當折一級特征停留時長平均值 = 總特征.一級特征停留時長平均值和;
auto 非當折一級特征視訊時長平均值 = 總特征.一級特征視訊時長平均值和;
for (auto 甲 : 排除折向量)
{
auto&& 甲折特征 = 折二級特征陣列陣列[甲][標識];
非當折一級特征數 -= 甲折特征.一級特征數;
for (auto 乙 = 0; 乙 < 7; 乙++)
非當折加權標籤和陣列[乙] -= 甲折特征.一級特征加權標籤和陣列[乙];
非當折一級特征播放時長平均值 -= 甲折特征.一級特征播放時長平均值和;
非當折一級特征停留時長平均值 -= 甲折特征.一級特征停留時長平均值和;
非當折一級特征視訊時長平均值 -= 甲折特征.一級特征視訊時長平均值和;
}
if (非當折一級特征數 > 0)
{
for (auto 甲 = 0; 甲 < 7; 甲++)
資料向量.emplace_back(轉半精度(非當折加權標籤和陣列[甲] / 非當折一級特征數));
資料向量.emplace_back(轉半精度(非當折一級特征播放時長平均值 / 非當折一級特征數));
資料向量.emplace_back(轉半精度(非當折一級特征停留時長平均值 / 非當折一級特征數));
資料向量.emplace_back(轉半精度(非當折一級特征視訊時長平均值 / 非當折一級特征數));
}
else
{
for (auto 甲 = 0; 甲 < 10; 甲++)
資料向量.emplace_back(-1);
}
}
};
|
ed6509a52f116a545bd7eea883488308ff920dbf
|
3d8d83a9e68f8ea6db242280f126c827ea94df2c
|
/__content/include_16.inc
|
21207ecfee85722871601edd26f52e81f563702a
|
[] |
no_license
|
rudyhyun/mark
|
53cc50e1f9c8aa6e04ec1256760595d01f0fcebb
|
f48afb5244e4fc5e4daf0e6cf6faea456dce03d3
|
refs/heads/master
| 2020-03-22T21:35:01.667634
| 2018-07-12T10:25:11
| 2018-07-12T10:25:11
| 140,697,933
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 31
|
inc
|
include_16.inc
|
<!--
google analytics
//-->
|
67c0d002dd13786237cde2817fd1dcdf5f98626c
|
6d48da9106dd6fa20630af71094d0790369cfb68
|
/cpp/fib.cpp
|
dda3479667d2d73f81b46b917d8157c62b58d65d
|
[] |
no_license
|
peanut-buttermilk/fun-run
|
968f587ea80f32be92c6825b9274ad25ff9ac275
|
187a11b41d14e4bf29380bdcd1c542d06545ee1a
|
refs/heads/master
| 2021-01-21T09:34:33.838314
| 2020-06-07T20:50:41
| 2020-06-07T20:50:41
| 53,075,983
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,159
|
cpp
|
fib.cpp
|
//
// fib.cpp
// CPP Test9
//
// Created by Balaji Cherukuri on 7/30/15.
// Copyright (c) 2015 FooBar. All rights reserved.
//
#include "fib.h"
#include <iostream>
#include <vector>
unsigned long nthFib(int n)
{
unsigned long prev1 = 0;
unsigned long prev2 = 1;
if (n <= 1) return prev1;
if (n == 2) return prev2;
unsigned long nthElem = 0;
for (int i = 2; i < n ; ++i )
{
nthElem = prev1 + prev2;
prev1 = prev2;
prev2 = nthElem;
}
return nthElem;
}
unsigned long nthFibDP(int n)
{
std::vector<unsigned long> fib(n);
fib[0] = 0;
fib[1] = 1;
if (n < 1) return 0;
if (n <= 2) return fib[n-1];
for (int i=2; i < n ; ++i )
{
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n-1];
}
// Unit Test //
void unitTestNthFib()
{
std::cout << nthFib(1) << " "<< nthFib(2) << " "<< nthFib(3) << " "<< nthFib(4) << " "<< nthFib(5) << " "<< nthFib(6) << "\n";
}
void unitTestNthFibDP()
{
std::cout << nthFibDP(1) << " "<< nthFibDP(2) << " "<< nthFibDP(3) << " "<< nthFibDP(4) << " "<< nthFibDP(5) << " "<< nthFibDP(6) << "\n";
}
|
64c74a62eec57c591e77958fc955ec64ca3928f9
|
4512a24742a8e860b6a482dcb57201ebc782e81c
|
/Projects/Project1/Guessing_Password/main.cpp
|
4ba85e73837700a35df3a1d3991c1c824ba1531a
|
[] |
no_license
|
yehaolan/CSC-5
|
1e99c85a342700cb80749d59ba5d8298fa0c1a48
|
a24da1ae8e2de9a6690870fb85274c579dc4486d
|
refs/heads/master
| 2021-05-29T04:24:41.417318
| 2015-02-12T16:57:07
| 2015-02-12T16:57:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,875
|
cpp
|
main.cpp
|
/*
* File: main.cpp
* Author: Haolan Ye(Benjamin)
* Created on January 27, 2015, 12:32 PM
* Purpose: Project1(Name of the game:Bomb Password)
*/
//system Libraries
#include <iostream>
#include <cstdlib> //for random number
#include <string>
#include <vector>
#include <fstream> //file I/O
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
string toDash(int);//change the password to dash
void introduce();//introduce the game
void ask(char&,int&);//ask user for guessing
char check(char,int,const char[],int);//check whether number and digit are correct
bool indexOf(char,const char[],int);//return whether the char is in the char array
void replace(string&,char,int);//replace of the correct digit
bool inside(const vector<int>,int);//return whether this digit is finished
void sample();//display the sample of guessing
//Execution begins here
int main(int argc, char** argv) {
//set seed for random number
srand(static_cast<unsigned short>(time(0)));
//declare a file object
ofstream output;
//open the file
output.open("Times.dat");
//declare and initialize variables
const int TOTCHNS=12;//total chance of the game
const int SIZE=4;//the size of the char array
string dash;
string answer;
int times=0; //how many times user tried
int gusCorr=0;//how many correct number have been guessed
int chnsLft; //chance counter(how many chances left)
int digit=0; //digit of the user guesses
char guess=0; //the number user guesses
char pswd[SIZE]={};//the password store in the array
vector<int> inputDg(SIZE,5);//the digits finished
//introduce the game
introduce();
//get a random 4-digit password and put it in array
for(int i=0;i<SIZE;i++) {
pswd[i]=rand()%10+'0';
}
//Use for loop get the password into strings
for(int i=0;i<SIZE;i++) {
answer+=pswd[i];
}
dash=toDash(SIZE);//get the dash
chnsLft=TOTCHNS;
//game begins
while(chnsLft>0&&gusCorr<SIZE) {
//Prompt user for the guess
cout<<endl;
cout<<"The password now looks like this: "<<dash<<endl;//Output dash
cout<<"You have "<<chnsLft<<" chances left"<<endl;//output chances left
ask(guess,digit);//Prompt user for guess
char result=check(guess,digit,pswd,SIZE);//check the guess
switch(result) {
case'1': { //if the number and place both are correct
if(inside(inputDg,digit)) { //if user have finished that digit
cout<<"You already finish this digit,"
<<"try other digits"<<endl;
} else {//user didn't finish this digit
replace(dash,guess,digit);//replace of the correct digit
inputDg.push_back(digit-1);//record the digit which has been finished to vector
cout<<"Your guess is correct."<<endl;
gusCorr++;
}
break;
}
case'2': { //if number is correct but digit is wrong
cout<<"This is the correct number but in wrong place."<<endl;
chnsLft--;
break;
}
case'3': { //if number and digit both wrong
cout<<"Wrong number and wrong place."<<endl;
chnsLft--;
break;
}
default:;
}
times++;//keep track of how many times user have input
}
if(chnsLft==0) { //No chances left for player
cout<<"You lost"<<endl;
output<<"You lost"<<endl;
}
if(gusCorr==SIZE) { //when 4 digits have been guessed correctly
output<<"You win this game after "<<times<<" tries"<<endl;
cout<<"You win this game after "<<times<<" tries"<<endl;
}
cout<<"The answer is "<<answer<<endl;
output.close();
//Exit stage right
return 0;
}
string toDash(int size) {
string dashed="";
for(int i=0;i<size;i++) {
dashed+="-";
}
return dashed;
}
void introduce() {
cout<<"***************** Welcome to Bomb password *****************"<<endl;
cout<<"* In this game, you should guess the 4-digit password *"<<endl;
cout<<"* First, you will input a number that you guess *"<<endl;
cout<<"* Then, you will input the digit of this number *"<<endl;
cout<<"* The digit of the number from left to right is 1,2,3,4 *"<<endl;
cout<<"* After you input these two information,the computer *"<<endl;
cout<<"* will tell you whether the number and digit are correct *"<<endl;
cout<<"* Attention: some digits of password may be the same number*"<<endl;
cout<<"************************************************************"<<endl;
cout<<"Press Enter to start the game";
cin.ignore();
}
void ask(char& guess,int& digit) {
do {
cout<<"Please input a number you guess"<<endl;
cout<<"If you need sample for input, type \'s\'"<<endl;
cin>>guess;
cin.ignore();
if(guess=='s'||guess=='S') //when player need sample
sample(); //output sample via ifstream
else if(guess<48||guess>57)
cout<<"Invalid input"<<endl<<endl;
} while(guess<48||guess>57);
do {
cout<<"Please input the digit of this number"<<endl;
cin>>digit;
cin.ignore();
if(digit<1||digit>4)
cout<<"Invalid input"<<endl<<endl;
} while(digit<1||digit>4);
}
char check(char guess,int digit,const char pswd[],int size) {
//Because array counts from 0,but digit from left to right is 1,2,3,4,so it need digit-1 for array
if(guess==pswd[digit-1]) { //when guess and digit are correct
return '1';
} else if(indexOf(guess,pswd,size)) { //number is right but digit is wrong
return '2';
} else { //both are wrong
return '3';
}
}
//return whether the char is in the array
bool indexOf(char x,const char pswd[],int size) {
bool temp=false;
for(int i=0;i<size;i++) {
if(pswd[i]==x)
temp=true;
}
return temp;
}
void replace(string& dash,char guess,int digit) {
string part1=dash.substr(0,(digit-1));
string part2=dash.substr(digit);
dash=part1+guess+part2;
}
//return whether is digit has been finished
bool inside(const vector<int> inputDg,int digit) {
bool temp=false;
for(int i=0;i<inputDg.size();i++) {
if(inputDg[i]==(digit-1))
temp=true;
}
return temp;
}
//display sample via file
void sample() {
string str;
ifstream input;
input.open("Sample.dat");
while(input>>str) {
if(str=="Now"||str=="If"||str=="You"||str=="<"||str=="Then,")
cout<<endl;
cout<<str<<' ';
}
cout<<endl<<endl;
input.close();
}
|
6ebf476d5b5abc0899d46ec0d04c7fcaa59e659e
|
626a3751789a6aa19b184bcc3bf5e0600a6ec23f
|
/src/online/base.cpp
|
0bcd95fe1e8b4473570ab744290a67ead0798609
|
[] |
no_license
|
google-code/btm
|
1bfa15074f2a348d6fdf3a36260539e1429f6c9d
|
a4cd07b78f8f149bad0967092af65641bcebfab1
|
refs/heads/master
| 2016-08-04T07:52:26.641072
| 2015-03-16T01:42:33
| 2015-03-16T01:42:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,100
|
cpp
|
base.cpp
|
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cassert>
#include "sampler.h"
#include "str_util.h"
#include "base.h"
Base::Base(int K, int W, double a, double b) :
K(K), W(W), alpha(a), beta(b) {
srand(time(NULL));
nwz.resize(W, K);
nb_z.resize(K);
}
// using batch results to initialize nb_z and nwz
void Base::load_init(string pt) {
cout << "load bz: " << pt << endl;
ifstream rf(pt.c_str());
if (!rf) {
cout << "[Error] file not find: " << pt << endl;
exit(1);
}
string line;
while (getline(rf, line)) {
istringstream iss(line);
Biterm bi(line);
bs.push_back(bi);
// update recorders
int k = bi.get_z();
++nwz[bi.get_wi()][k];
++nwz[bi.get_wj()][k];
++nb_z[k];
}
cout << "init n(b):" << bs.size() << endl;
}
// sample procedure for ith biterm
void Base::update_biterm(Biterm& bi) {
if (bi.get_z() != -1)
reset_biterm_topic(bi);
// compute p(z|b)
Pvec<double> pz;
compute_pz_b(bi, pz);
// sample topic for biterm b
int k = Sampler::mult_sample(pz.to_vector());
assign_biterm_topic(bi, k);
}
// reset topic assignment of biterm i
void Base::reset_biterm_topic(Biterm& bi) {
int w1 = bi.get_wi();
int w2 = bi.get_wj();
int k = bi.get_z();
if (k < 0) return;
--nb_z[k]; // update proportion of biterms in topic K
--nwz[w1][k]; // update proportion w1's occurrence times in topic K
--nwz[w2][k];
assert(nb_z[k]>=0 && nwz[w1][k]>=0 && nwz[w2][k]>=0);
bi.reset_z();
}
// compute p(z|w_i, w_j)
void Base::compute_pz_b(Biterm& bi, Pvec<double>& pz) {
pz.resize(K);
int w1 = bi.get_wi();
int w2 = bi.get_wj();
double pw1k, pw2k;
for (int k = 0; k < K; ++k) {
double deno = 2 * nb_z[k] + W * beta;
pw1k = (nwz[w1][k] + beta) / deno;
pw2k = (nwz[w2][k] + beta) / deno;
pz[k] = (nb_z[k] + alpha) * pw1k * pw2k;
}
pz.normalize();
}
// assign topic k to biterm i
void Base::assign_biterm_topic(Biterm& bi, int k) {
int w1 = bi.get_wi();
int w2 = bi.get_wj();
bi.set_z(k);
++nb_z[k];
++nwz[w1][k];
++nwz[w2][k];
}
void Base::save_res(string dir) {
string ks = str_util::itos(K);
string pt = dir + "pz.k" + ks;
cout << "write p(z): " << pt << endl;
save_pz(pt);
string pt2 = dir + "pw_z.k" + ks;
cout << "write p(w|z): " << pt2 << endl;
save_pw_z(pt2);
}
// p(z) is determinated by the overall proportions
// of biterms in it
void Base::save_pz(string pt) {
Pvec<double> pz(K); // p(z) = theta
for (int k = 0; k < K; k++)
pz[k] = (nb_z[k] + alpha);
pz.normalize();
pz.write(pt);
}
void Base::save_pw_z(string pt) {
Pmat<double> pw_z(K, W); // p(w|z) = phi, size K * M
for (int k = 0; k < K; k++) {
double deno = 2 * nb_z[k] + W * beta;
for (int m = 0; m < W; m++)
pw_z[k][m] = (nwz[m][k] + beta) / deno;
}
pw_z.write(pt);
}
// format:wi wj z
void Base::save_bz(string dir) {
string pt = dir + "bz.k" + str_util::itos(K);
cout << "save bz: " << pt << endl;
ofstream wf(pt.c_str());
for (int b = 0; b < bs.size(); ++b)
wf << bs[b].str() << endl;
}
|
dc6e950bea229a91eb2a959c589a1cb55a09b8a3
|
dcf415dd868be5999942d874ad766bd5d0d0a074
|
/PlayerAPI/ZNV/PlayerAPIZNV/PlayerZNV.cpp
|
c868f28e0c9a449404767c7b6e44bbf37d8f4e10
|
[] |
no_license
|
github188/SPlayer
|
8f2dc00e2b2b8a26c5953390ae8cb89067bfbc80
|
d0439fe9130f0932eada82bb8b08b0b8b89b8411
|
refs/heads/master
| 2020-12-30T18:16:31.667255
| 2016-07-05T04:53:54
| 2016-07-05T04:53:54
| 62,694,150
| 0
| 2
| null | 2016-07-06T05:38:52
| 2016-07-06T05:38:51
| null |
GB18030
|
C++
| false
| false
| 5,698
|
cpp
|
PlayerZNV.cpp
|
#include "stdafx.h"
#include "PlayerZNV.h"
#include <stdio.h>
#include <time.h>
#include "../inc/PlaySDK.h"
#pragma comment(lib,"../lib/Play_SDK.lib")
int g_Speed[] = { -16, -8, -4, -2, 1, 2, 4, 8, 16 };
char* CPlayerFactoryZNV::Name()
{
return "中兴力维";
}
BOOL CPlayerFactoryZNV::IsBelongThis(char *pFile)
{
if (strstr(pFile, ".zv") || strstr(pFile, ".znv") || strstr(pFile, ".zte"))//判断ZNV文件
{
return true;
}
FILE *pfd = NULL;
int ret = fopen_s(&pfd, pFile, "rb");
if (pfd)//打开文件成功
{
char buf[8];
memset(buf, 0, 8);
fread(buf, 8, 1, pfd);
if (strncmp(buf, "pu8000", 6) == 0 || strncmp(buf, "8000", 4)==0)
{
return true;
}
fclose(pfd);
}
return false;
}
BOOL CPlayerFactoryZNV::Init()
{
return true;
}
void CPlayerFactoryZNV::Release()
{
}
IPlayer *CPlayerFactoryZNV::CreatePlayer()
{
return new CPlayerZNV();
}
/////////////
CPlayerZNV::CPlayerZNV() :m_iSpeed(4), m_bPause(false)
{
}
CPlayerZNV::~CPlayerZNV()
{
}
BOOL CPlayerZNV::OpenFile(char *PFile,HWND hwnd)
{
m_hwnd = hwnd;
int nRet = Play_GetPort((int*)&m_nPort);
if (nRet==0)
{
nRet = Play_OpenFile(m_nPort, (int)hwnd, PFile);
if (nRet == 0)
{
return true;
}
}
return false;
}
BOOL CPlayerZNV::Play()
{
int nRet = Play_Play(m_nPort);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::Pause(DWORD nPause)
{
int nRet = -1;
m_bPause = nPause;
if (nPause)
{
nRet = Play_Pause(m_nPort);
}
else
{
nRet = Play_Play(m_nPort);
}
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::Stop()
{
Play_Stop(m_nPort);
Play_CloseFile(m_nPort);
Play_FreePort(m_nPort);
return true;
}
BOOL CPlayerZNV::Fast()
{
if (m_iSpeed >8)
{
return false;
}
m_iSpeed++;
int nRet = Play_Speed(m_nPort, g_Speed[m_iSpeed]);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::Slow()
{
if (m_iSpeed < 0)
{
return false;
}
m_iSpeed--;
int nRet = Play_Speed(m_nPort, g_Speed[m_iSpeed]);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::OneByOne()
{
///Play_SetStepPlay(m_nPort);
return false;
}
BOOL CPlayerZNV::OneByOneBack()
{
return false;
}
BOOL CPlayerZNV::PlaySoundShare()
{
int nRet= Play_PlaySound(m_nPort);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::StopSoundShare()
{
int nRet = Play_StopSound(m_nPort);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::SetVolume(WORD nVolume)
{
return false;
}
DWORD CPlayerZNV::GetVolume()
{
return 0;
}
BOOL CPlayerZNV::SetPlayPos(float fRelativePos)
{
int nRet= Play_SetPlayedPos(m_nPort, fRelativePos*100);
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
float CPlayerZNV::GetPlayPos()
{
return Play_GetPlayedPos(m_nPort)/100.0;
}
DWORD CPlayerZNV::GetFileTime()
{
return Play_GetFileTime(m_nPort);
}
DWORD CPlayerZNV::GetPlayedTime()
{
return Play_GetPlayedTime(m_nPort);
}
BOOL CPlayerZNV::SetPlayedTimeEx(DWORD nTime)
{
return Play_SetPlayedTime(m_nPort, nTime);
}
BOOL CPlayerZNV::GetPictureSize(LONG *pWidth, LONG *pHeight)
{
return Play_GetVideoInfo(m_nPort, (int*)pWidth, (int*)pHeight);
}
BOOL CPlayerZNV::SetColor(DWORD nRegionNum, int nBrightness, int nContrast, int nSaturation, int nHue)
{
return false;
}
BOOL CPlayerZNV::GetColor(DWORD nRegionNum, int *pBrightness, int *pContrast, int *pSaturation, int *pHue)
{
return false;
}
void CPlayerZNV::ZNVFileEndCallback(long lParam)
{
CPlayerZNV* pPlayer = (CPlayerZNV*)lParam;
pPlayer->m_FileEndCallbackFun(pPlayer->m_nID,pPlayer->m_pUser);
}
BOOL CPlayerZNV::SetFileEndCallback(LONG nID, FileEndCallback callBack, void *pUser)
{
m_nID = nID;
m_FileEndCallbackFun = callBack;
m_pUser = pUser;
// Play_SetFileEndCallBack(m_nPort, (FileEndCallBack)&ZNVFileEndCallback, (long)pUser);
return false;
}
BOOL CPlayerZNV::SetDisplayCallback(LONG nID, DisplayCallback displayCallback, void * nUser)
{
return false;
m_DisplayCallbackFun = displayCallback;
m_DisplayCalUser = nUser;
int nRet = Play_SetYUVCallBack(m_nPort, (Play_VideoYUVCallBack)&DisplayCBFunBack, (long)this);//无效,无数据回调
if (nRet == 0)
{
return true;
}
else
{
return false;
}
}
void CPlayerZNV::DisplayCBFunBack(long nPort, char * pBuf, long nSize, long nWidth, long nHeight, unsigned __int64 nStamp, long nType, long nReserved)
{
CPlayerZNV* pPlayer = (CPlayerZNV*)nReserved;
if (pPlayer)
{
DISPLAYCALLBCK_INFO displayInfo;
displayInfo.pBuf = (char*)pBuf;
displayInfo.nWidth = nWidth;
displayInfo.nHeight = nHeight;
displayInfo.nStamp = nStamp;
displayInfo.nUser = (long)pPlayer->m_DisplayCalUser;
pPlayer->m_DisplayCallbackFun(&displayInfo);
}
}
BOOL CPlayerZNV::GetSystemTime(unsigned long long *systemTime)
{/*
PLAYM4_SYSTEM_TIME sysTime;
bool bRet=PlayM4_GetSystemTime(m_nPort, &sysTime);
struct tm tblock;
tblock.tm_year=sysTime.dwYear-1900;
tblock.tm_mon = sysTime.dwMon-1;
tblock.tm_mday = sysTime.dwDay;
tblock.tm_hour = sysTime.dwHour;
tblock.tm_min = sysTime.dwMin;
tblock.tm_sec = sysTime.dwSec;
*systemTime = mktime(&tblock);
return bRet;*/
return false;
}
BOOL CPlayerZNV::CapturePic(char *pSaveFile, int iType)
{
int nRet = Play_CapturePicture(m_nPort, pSaveFile);
if (nRet == 0)
{
Sleep(1000);
return true;
}
else
{
return false;
}
}
BOOL CPlayerZNV::FileCutStart(const char* srcFileName, const char* destFileName, unsigned __int64 startTime, unsigned __int64 endTime, BOOL bFast)
{
return false;
}
BOOL CPlayerZNV::FileCutClose()
{
return false;
}
int CPlayerZNV::FileCutProcess()
{
return 0;
}
|
5104129bf9f52faa97cc2e1ee563423a3c206123
|
5781992b8eb5f8e8f6ce7ccf8069b60138b6f4d7
|
/src/ui/replay/playergold.h
|
a163d3031ec02a92544ed275a2d6d8e59c52dacb
|
[] |
no_license
|
liyonghelpme/dota-replay-manager
|
fd7c041cc48bac9fd726af4771a03fe8ec1a4ae6
|
21b965a8a63e077df275379d1f5055d77d98e580
|
refs/heads/master
| 2021-01-10T08:11:31.169556
| 2014-12-24T21:35:29
| 2014-12-24T21:35:29
| 36,912,875
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 633
|
h
|
playergold.h
|
#ifndef __UI_REPLAY_PLAYERGOLD__
#define __UI_REPLAY_PLAYERGOLD__
#include "ui/replaywnd.h"
#include "frameui/graphwnd.h"
#include "frameui/controlframes.h"
class GoldGraphWindow;
class ReplayPlayerGoldTab : public ReplayTab
{
GoldGraphWindow* graph;
struct PlayerButtons
{
Frame* frame;
ImageFrame* icon;
ButtonFrame* check;
ColorFrame* bar;
};
ButtonFrame* totals[2];
PlayerButtons buttons[10];
uint32 onMessage(uint32 message, uint32 wParam, uint32 lParam);
void onSetReplay();
public:
ReplayPlayerGoldTab(Frame* parent);
};
#endif // __UI_REPLAY_PLAYERGOLD__
|
35719a0ff6af36d0d443c74a6408a5eb61816f0a
|
a2f7fd5673f214e74f244cb3af06f59d73d71872
|
/BrainActivityVisualization/gmainwindow.cpp
|
653edad1397eb535f752e970a20730253f8ebbd3
|
[] |
no_license
|
18David/BrainActivityVisualization
|
374895646d5cd4fc5f2b151c66b873ac5d7e7f59
|
72f01e6fe5fcd9141e7e91ec5e0114e30b3d9f06
|
refs/heads/master
| 2021-05-04T03:55:43.817857
| 2016-12-13T09:56:45
| 2016-12-13T09:56:45
| 70,809,172
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,775
|
cpp
|
gmainwindow.cpp
|
/**
* Project Untitled
*/
#include "filenumberstreamreader.h"
#include "gmainwindow.h"
#include "ui_gmainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTableWidget>
#include <coherencewidget.h>
GMainWindow::GMainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::GMainWindow)
{
ui->setupUi(this);
ui->tableWidget->setRowCount(20);
ui->tableWidget->setColumnCount(20);
m_coherenceManager.setRange(0,0.1); // VALEUR PAR DEFAUT A MODIFIER !!!!!!
ui->lineEditMiniRange->setText("0"); // min
ui->lineEditMaxRange->setText("0.1"); // max
//win = new CoherenceWidget(this);
connect(&m_coherenceManager,SIGNAL(computeFinishedTotally()),this,SLOT(computeFinished()));
connect(ui->actionOpen,SIGNAL(triggered(bool)),this,SLOT(openFile()));
connect(&m_matrixManager, SIGNAL(progressChanged(int)), ui->progressBar, SLOT(setValue(int)));
connect(&m_matrixManager, SIGNAL(progressRangeChanged(int,int)), ui->progressBar, SLOT(setRange(int,int)));
connect(ui->pushButtonUp, SIGNAL(clicked(bool)), this, SLOT(setCoherenceRange(bool)));
}
GMainWindow::~GMainWindow()
{
delete ui;
}
/**
* GMainWindow implementation
*
* Fenêtre principale contenant le graphique et le menu permettant d'ouvrir un dossier
*/
/**
* Affiche une fenêtre de dialogue permettant de choisir le répertoire des fichiers à lire
*
* Connecté à l'action "Ouvrir" dans le menu
* @return void
*/
void GMainWindow::openFile()
{
m_fileName = QFileDialog::getOpenFileName(this,tr("Open a file"),"","Matrix file (*.txt)");
if(m_fileName.isEmpty()){
QMessageBox::information(this,tr("Fichier Introuvable"),tr("Aucun fichier !"));
}else{
//int ret = QMessageBox::question(this, "Multithread", "Utiliser multithread ?", QMessageBox::Yes | QMessageBox::No);
computeFile();
}
}
void GMainWindow::paintEvent(QPaintEvent *evt)
{
}
/**
* Récupère les chemins des fichiers présent dans le dossier passé en paramètre.
*
* Pour chaque fichier crée un lecteur de mot et l'ajoute à la liste "m_readers"
*
* Lance le traitement sur les fichiers du dossier en multithread ou non (suivant la valeur du booléen passé en paramètre) en passant la liste "m_readers" au "m_wordStatisticMatrixManager" et en lancant le calcul à l'aide de sa méthode "run"
* @param dir
* @param useMultithread
* @return void
*/
void GMainWindow::computeFile()
{
QList<AbstractMatrixReader *> readers;
readers.append(new FileNumberStreamReader(m_fileName));
m_matrixManager.setReaders(readers);
m_matrixManager.run();
m_coherenceManager.setMatrix(m_matrixManager.getResults());
m_coherenceManager.run();
// }
}
/**
* Connecté au signal "computeFinished" du WordStatisticWorkerManager.
*
* Lorsque ce slot est appelé il va récupérer les résultats et les afficher dans la fenêtre
* @return void
*/
void GMainWindow::computeFinished()
{
QVector<QVector<QVector<float>>> resMatrix;
resMatrix = m_matrixManager.getResults();
for (int i=0 ;i< ui->tableWidget->rowCount();i++){
for(int j=0 ; j< ui->tableWidget->columnCount(); j++)
{
QString tmp="[";
for(int k=0; k<5; k++){
tmp+=tr("%1;").arg(resMatrix[i][j][k]);
}
tmp+="]";
QTableWidgetItem* itm = new QTableWidgetItem(tmp);
ui->tableWidget->setItem(i,j,itm);
}
}
QPen pen;
pen.setWidth(2);
pen.setCapStyle(Qt::RoundCap);
int cpt_col=0;
int cpt_row=0;
int nb_res = 0;
QVector<QList<QVector<QPoint>>> res;
QVector<CoherenceWidget*> win;
res= m_coherenceManager.getResults();
for(int i = 0;i<res.size();i++){
if(i==0){
win.append(new CoherenceWidget(m_fileName.split("/").last()+" - Delta"));
pen.setColor(Qt::red);
}else if(i==1){
win.append(new CoherenceWidget(m_fileName.split("/").last()+" - Theta"));
pen.setColor(Qt::green);
}else if(i==2){
win.append(new CoherenceWidget(m_fileName.split("/").last()+" - Alpha"));
pen.setColor(Qt::blue);
}else if(i==3){
win.append(new CoherenceWidget(m_fileName.split("/").last()+" - Beta"));
pen.setColor(Qt::yellow);
}else {
win.append(new CoherenceWidget(m_fileName.split("/").last()+" - Gamma"));
pen.setColor(Qt::gray);
}
win[i]->move(cpt_col*537,cpt_row*537);
win[i]->setPoints(res[i]);
win[i]->setMinimumSize(537,480);
win[i]->setMaximumSize(537,480);
win[i]->setPen(pen);
win[i]->setBrush(QBrush());
win[i]->show();
nb_res+=res[i].size();
cpt_col++;
if(cpt_col==3){
cpt_row++;
cpt_col=0; //int tab[x][Y][Z] // tab[0][0][0] =300 ;
}
}
ui->value_number->setText(QString::number(nb_res));
/*//traitement pour afficher
QPixmap pix("://Images/EEG 21.png");
QPainter *painter = new QPainter(ui->QWidgetpaint);
//painter->setRenderHints(QPainter::Antialiasing);
QPen pen;
pen.setWidth(100);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(Qt::red);
painter->setPen(pen);
foreach(QPoint * line,res){
painter->drawPoint(line[0]);
//painter->drawPoint(line[1]);
//painter->drawLine(line[0], line[1]);
}
painter->setBackground(pix);*/
}
void GMainWindow::setCoherenceRange(bool e)
{
m_coherenceManager.setRange(ui->lineEditMiniRange->text().toFloat(),ui->lineEditMaxRange->text().toFloat());
m_matrixManager.raz();
m_coherenceManager.raz();
computeFile();
}
|
978910ed29c49754e3742721c252276f516f716e
|
73795df51faad1f3c5f8ee04ce000349344b3de2
|
/src/util/String.cpp
|
94ede2b2667490662e5ee4002a5260f1a3787ebe
|
[
"MIT"
] |
permissive
|
mohaque0/simple-util-cpp
|
495bc25aeb1023ab474e68f30a6ec95b5fe042e5
|
23c0d7d622e0df960fefe96107ba032ce847e32c
|
refs/heads/master
| 2020-04-03T07:55:12.801940
| 2019-08-03T20:36:58
| 2019-08-03T20:36:58
| 155,117,846
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,064
|
cpp
|
String.cpp
|
#include "String.hpp"
#include <cstddef>
#include <cstring>
#include <iostream>
#include <sstream>
namespace Util {
const size_t String::NOTFOUND = -1;
//
// StringData
//
StringData::StringData() :
memory(),
data(NULL),
len(0)
{}
StringData::StringData(const char *str, bool copy) :
memory(),
data(str),
len(strlen(str))
{
if (copy) {
char* buffer = new char[len];
memcpy(buffer, str, len * sizeof(char));
memory.reset(buffer, std::default_delete<char[]>());
data = buffer;
}
}
StringData::StringData(const char *str, size_t offset, size_t len_, bool copy) :
memory(),
data(&str[offset]),
len(len_)
{
if (copy) {
char* buffer = new char[len];
memcpy(buffer, &str[offset], len * sizeof(char));
memory.reset(buffer, std::default_delete<char[]>());
data = buffer;
}
}
StringData::StringData(const StringData& other, size_t offset, size_t len_) :
memory(other.memory),
data(&other.data[offset]),
len(len_)
{
// Make sure we don't go past the end of memory.
if (offset > other.size()) {
offset = other.size();
data = &other.data[offset];
}
if (offset + len > other.size()) {
len = other.size() - offset;
}
}
StringData::StringData(const std::vector<StringData> &sources) :
memory(),
data(NULL),
len(0)
{
// How big should we be?
for (const StringData &datum : sources) {
len += datum.size();
}
// Initialize storage.
char* buffer = new char[len];
// Copy data.
char* ptr = buffer;
for (const StringData &datum : sources) {
memcpy(ptr, datum.get(), datum.size() * sizeof(char));
ptr += datum.size();
}
memory.reset(buffer, std::default_delete<char[]>());
data = buffer;
}
const char *StringData::get() const {
return data;
}
size_t StringData::size() const
{
return len;
}
//
// String
//
String::String(StringData datum)
{
data.push_back(datum);
}
String::String()
{}
String::String(const char c)
{
char str[2] = {c, '\0'};
data.push_back(StringData(str));
}
String::String(const int i)
{
std::stringstream stream;
stream << i;
data.push_back(StringData(stream.str().c_str()));
}
String::String(const float f)
{
std::stringstream stream;
stream << f;
data.push_back(StringData(stream.str().c_str()));
}
String::String(const double d)
{
std::stringstream stream;
stream << d;
data.push_back(StringData(stream.str().c_str()));
}
String::String(const long l)
{
std::stringstream stream;
stream << l;
data.push_back(StringData(stream.str().c_str()));
}
String::String(const unsigned long l)
{
std::stringstream stream;
stream << l;
data.push_back(StringData(stream.str().c_str()));
}
String::String(const char *str, bool copy)
{
data.push_back(StringData(str, copy));
}
String::String(const char *str, size_t offset, size_t len, bool copy)
{
data.push_back(StringData(str, offset, len, copy));
}
String::String(const std::string &other)
{
data.push_back(StringData(other.c_str()));
}
String::String(const String &other) :
data(other.data)
{}
String::String(String &&other) :
data(std::move(other.data))
{}
void String::optimize() const
{
if (data.size() > 1) {
StringData newData(data);
data.clear();
data.push_back(newData);
}
}
String &String::operator=(const String &other)
{
data = other.data;
return *this;
}
String &String::operator=(const char *str)
{
StringData newData(str);
data.clear();
data.push_back(newData);
return *this;
}
String &String::operator=(char c)
{
char str[2] = {c, '\0'};
StringData newData(str);
data.clear();
data.push_back(newData);
return *this;
}
String String::operator+(const String &other) const
{
String retVal;
for (const StringData &datum : data) {
retVal.data.push_back(datum);
}
for (const StringData &datum : other.data) {
retVal.data.push_back(datum);
}
return retVal;
}
String &String::operator+=(const String &other)
{
data.insert(data.end(), other.data.begin(), other.data.end());
return *this;
}
String &String::operator+=(const char *str)
{
*this += String(str);
return *this;
}
String &String::operator+=(char c)
{
// TODO: Very inefficient. Should realloc and append if possible?
char str[2] = {c, '\0'};
*this += String(str);
return *this;
}
const char String::operator[](const size_t index) const
{
return at(index);
}
const String String::substr(size_t start, size_t len) const
{
optimize();
if (data.size() == 0) {
return String();
}
StringData newStringData(data[0], start, len);
return String(newStringData);
}
const size_t String::size() const
{
size_t s = 0;
for (const auto& datum : data) {
s += datum.size();
}
return s;
}
const char String::at(const size_t index) const
{
// TODO: Perhaps there's a better way?
optimize();
return data[0].get()[index];
}
const size_t String::find(const String& toFind, const size_t start) const
{
return find(toFind, start, toFind.size());
}
const size_t String::find(const String& toFind, const size_t start, const size_t matchLength) const
{
optimize();
for (size_t current = start; current < size() - matchLength; current++) {
size_t idx = 0;
for (idx = 0; idx < matchLength; idx++) {
if (at(current + idx) != toFind.at(idx)) {
break;
}
}
// Found it!
if (idx == matchLength) {
return current;
}
}
return NOTFOUND;
}
const std::shared_ptr<char> String::c_str() const
{
char* buffer = new char[size() + 1];
for (size_t i = 0; i < size(); i++) {
buffer[i] = at(i);
}
buffer[size()] = '\0';
return std::shared_ptr<char>(buffer, std::default_delete<char[]>());
}
std::ostream &operator<<(std::ostream &out, const String &str)
{
for (const StringData &datum : str.data) {
for (size_t i = 0; i < datum.size(); ++i) {
const char * c = datum.get();
out.put(c[i]);
}
}
return out;
}
String operator+(const char* a, const String& b)
{
return String(a) + b;
}
bool operator==(const String& a, const String& b)
{
if (a.size() != b.size()) {
return false;
}
for (size_t i = 0; i < a.size(); i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
bool operator!=(const String& a, const String& b)
{
return !(a == b);
}
}
|
3ef29fb702697de562a87552a01e52a39352b283
|
a947e022a8d9d2214e83386ddf1c4908a42255d7
|
/M_03/ex03/DiamondTrap.hpp
|
bfd1932fa66869f9d3ea2078bed79fbafcc42947
|
[] |
no_license
|
BooDeer/CPP_modules
|
03c4c3a6a7e9c7ef9cd24d34f53af09db22d8dca
|
36219b52ed30fd226870a61b8938a1c1c11bedbe
|
refs/heads/master
| 2022-03-11T08:05:31.545415
| 2022-02-07T16:55:19
| 2022-02-07T16:55:19
| 249,405,415
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 922
|
hpp
|
DiamondTrap.hpp
|
#ifndef DIAMONDTRAP_HPP
# define DIAMONDTRAP_HPP
#include "FragTrap.hpp"
#include "ClapTrap.hpp"
#include "ScavTrap.hpp"
class DiamondTrap: public FragTrap, public ScavTrap
{
/* ======================*/
/* public attributes */
/* ==================== */
public:
/* (Con/Des)tructors */
DiamondTrap( void ); // default constructor.
DiamondTrap( std::string name ); // constructor with parameters.
DiamondTrap( const DiamondTrap& src ); // copy constructor.
~DiamondTrap( void ); // destructor.
/* Operators overloaders */
DiamondTrap& operator=( const DiamondTrap& rhs ); // assignement operator overload.
/* Public methods */
/* ======================*/
/* protected attributes */
/* ==================== */
protected:
/* ======================*/
/* private attributes */
/* ==================== */
private:
std::string _name;
};
#endif
|
f08061e3b78617e85e35fcbc1b972fda74f25742
|
005cb1c69358d301f72c6a6890ffeb430573c1a1
|
/Pods/Headers/Private/GeoFeatures/boost/geometry/policies/is_valid/failure_type_policy.hpp
|
bb10a8b0d8575cce2ed03403f568daada6a3c574
|
[
"Apache-2.0"
] |
permissive
|
TheClimateCorporation/DemoCLUs
|
05588dcca687cc5854755fad72f07759f81fe673
|
f343da9b41807694055151a721b497cf6267f829
|
refs/heads/master
| 2021-01-10T15:10:06.021498
| 2016-04-19T20:31:34
| 2016-04-19T20:31:34
| 51,960,444
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 101
|
hpp
|
failure_type_policy.hpp
|
../../../../../../../GeoFeatures/GeoFeatures/boost/geometry/policies/is_valid/failure_type_policy.hpp
|
79c1872e02ea7001294666285d979e3bea80778e
|
075735e3b987cb8ad5c629440ee6419ff2762f81
|
/leetcode/322_Coin_Change/Coin_Change.cpp
|
e51648fe5e89df15626bd6eaedbd04f1f1b8a165
|
[] |
no_license
|
Masterqsx/ProgrammingPractice
|
6f0d4c08f1857f5a409b78c9ae7cd0ec234899be
|
acf42fb807dc8584b4ae0081ddf65c495314eabe
|
refs/heads/master
| 2021-01-24T20:26:17.552529
| 2019-07-22T19:16:58
| 2019-07-22T19:16:58
| 68,643,503
| 0
| 0
| null | 2020-10-13T01:11:46
| 2016-09-19T20:26:10
|
HTML
|
UTF-8
|
C++
| false
| false
| 536
|
cpp
|
Coin_Change.cpp
|
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
unsigned int num[(unsigned int)amount+1] = {0};
fill_n(num, (unsigned int)amount+1, INT_MAX);
num[0] = 0;
for (unsigned int i=0;i<coins.size();i++) {
for (unsigned int j=coins[i];j<=amount;j++) {
if (j >= coins[i])
num[j] = min(num[j], num[j-coins[i]] == INT_MAX?INT_MAX:num[j-coins[i]]+1);
}
}
return num[amount] == INT_MAX?-1:num[amount];
}
};
|
5179b33a9b0f504a7f3fa3e5868bcd8d096e7871
|
d3e498007ddeba12dc1d479a3bacf7086f73f8da
|
/437.cpp
|
608e0232761488429ae195219ec949af2233147d
|
[] |
no_license
|
vicwer/leetcode2020
|
76590c3c176f5e24848d240e454cc48f81ca5ae0
|
e682c01c5bc0b2060665acf81be747627ee759b7
|
refs/heads/master
| 2023-02-06T07:17:53.741644
| 2020-12-15T11:56:54
| 2020-12-15T11:56:54
| 258,710,157
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 835
|
cpp
|
437.cpp
|
#include <iostream>
#include <vector>
#include <queue>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
};
int count = 0;
int cntPathSum(TreeNode* root, int sum)
{
if(!root)
return;
if(root->val - sum == 0)
count += 1;
cntPathSum(root->left, sum-root->val);
cntPathSum(root->right, sum-root->val);
}
int pathSum(TreeNode* root, int sum)
{
if(!root)
return 0;
int pathNum = 0;
std::queue<TreeNode*> cnt_layer;
cnt_layer.push(root);
while(!cnt_layer.empty())
{
TreeNode* cnt_root = cnt_layer.front();
cnt_layer.pop();
if(cnt_root->left)
cnt_layer.push(cnt_root->left);
if(cnt_root->right)
cnt_layer.push(cnt_root->right);
cntPathSum(cnt_root, sum);
}
return pathNum;
}
|
4abaca9aedea91d0a2e6641e9c959a8c69057ca8
|
5a54c51b5972f55acd74244b4ae561b8eb343ac9
|
/sketch_mar30a.ino
|
b5536f945492fd8b6116e0136b2cb920887656a1
|
[] |
no_license
|
Nathan-K-Public/headset-tester
|
b96ab3173e166501d6132f1be710a126b5220276
|
4e0d4e129798353d8ff3ff8d8771a3a16be7c841
|
refs/heads/master
| 2022-11-22T18:31:46.536840
| 2020-07-31T07:46:18
| 2020-07-31T07:46:18
| 283,970,204
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,722
|
ino
|
sketch_mar30a.ino
|
#include <Wire.h>
#include <Adafruit_MCP4725.h>
#include "mariosongs.h"
#include "ringbuffer.h"
Adafruit_MCP4725 dac;
// Set this value to 9, 8, 7, 6 or 5 to adjust the resolution
#define DAC_RESOLUTION (8)
#define ADC_DELAY 40
// Increase if ADC starts reading 0 vals due to sampling cap not filling
#define pinLED PC13
#define buzzerPin PB0
#define maxLimit 100
#define minLimit 10
#define RC_CONST 0.632120558828557678404476
#define ADC_TRIGGER_V 0.20
#define VCC_CORRECT (3210-3218)
#define BIAS_R 2200
#define BIAS_MV 2200
static int successLog = 0b1111;
typedef ringbuffer_t<int, 512> ringbuffer_med_t;
static ringbuffer_med_t message_buffer;
typedef ringbuffer_t<uint32_t, 512> ringbuffer_long_t;
static ringbuffer_long_t time_buffer;
int VCC_Self = 0;
void setup_vcc_sensor() {
adc_reg_map *regs = ADC1->regs;
regs->CR2 |= ADC_CR2_TSVREFE; // enable VREFINT and temp sensor
regs->SMPR1 = ADC_SMPR1_SMP17; // sample rate for VREFINT ADC channel
}
void setup() {
Serial.begin(115200);
pinMode(pinLED, OUTPUT);
digitalWrite(pinLED, HIGH);
pinMode(buzzerPin, OUTPUT);
pinMode(PA0, INPUT_ANALOG);
pinMode(PA1, INPUT_ANALOG);
delay(500);
Serial.println("START");
dac.begin(0x60);
Serial.print("\r\nPrint Internal VCC Voltage: ");
setup_vcc_sensor();
systick_uptime_millis = 0; // really sleazy way to reset millis;
//uint32_t t0 = millis();
//Serial.print(t0); Serial.print(" ");
delay(100);
VCC_Self = 1200 * 4096 / adc_read(ADC1, 17); // ADC sample to millivolts
//Serial.print(millivolts/1000,DEC);Serial.print(".");Serial.print(millivolts%1000,DEC);
Serial.print(VCC_Self / 1000.0, 2);
Serial.println("v");
//110 is correction from predicted VCC to actual Multimeter at pin
Serial.print("Vcc correction: ");
Serial.print(VCC_CORRECT / 1000.0, 2);
Serial.println("v");
VCC_Self = VCC_Self - VCC_CORRECT;
int cal = int(4095.0 * BIAS_MV / VCC_Self);
Serial.print("Driving to 2.2v: "); Serial.print(" "); Serial.print(cal);
Serial.println(" / 4095");
dac.setVoltage(cal, false);
}
void loop() {
digitalWrite(pinLED, LOW);
sing(7, buzzerPin);
/*
sing(1, buzzerPin);
sing(6, buzzerPin);
sing(5, buzzerPin);
sing(4, buzzerPin);
sing(3, buzzerPin);
sing(2, buzzerPin);
*/
/*
message_buffer.push_back_nc(1234);
time_buffer.push_back_nc(123);
message_buffer.push_back_nc(5678);
time_buffer.push_back_nc(456);
timingCheck(5678);
*/
Serial.println();
// static int i = minLimit;
// static int mod = 10;
// i = i + mod;
// if ( i > maxLimit || i < minLimit ) {
// mod *= -1;
// }
//delay(i);
digitalWrite(pinLED, HIGH);
//Serial.println("Hello World");
// delay(i);
/*
uint32 sumRead = 0;
int n = 0;
int tempRead = 0;
for (n = 0; n < 100; n++) {
delay(10);
tempRead = analogRead(PA0);
sumRead = sumRead + tempRead;
//Serial.println(tempRead/4095.0 * VCC_Self/1000.0 ,4);
//Serial.print(" ");
//Serial.println(analogRead(PA1)*3300/4096);
}
Serial.print("Average over "); Serial.print(n); Serial.print(" samples is "); Serial.println( (float) sumRead / n * (float) VCC_Self / 1000.0 / 4095.0 , 4);
*/
flagTransition();
}
int resultIntegrate(int resistance, int timing)
{
//Serial.println();
if(resistance == -9){
Serial.println("==== [Resetting] ====");
sing(7, buzzerPin);
return -9;
}
int summary = max (resistance, timing);
switch (summary) {
case 0:
Serial.println("==== [Pass] ====");
sing(5, buzzerPin);
break;
case 1:
Serial.println("==== [Marginal pass] ====");
sing(2, buzzerPin);
break;
case 2:
Serial.println("==== [Fail!] ====");
sing(4, buzzerPin);
break;
case 3:
Serial.println("==== [MAJOR FAIL!] ====");
sing(3, buzzerPin);
break;
}
return 0;
}
int timingCheck(int vf)
{
Serial.print("Running timing check on "); Serial.print(message_buffer.available()); Serial.println(" buffer entries");
//RC_CONST
/*
Serial.println("Dumping circular buffer...");
for (int n = 0; message_buffer.available(); n++) {
int val = message_buffer.pop_front();
uint32_t time = time_buffer.pop_front();
Serial.print(n);
Serial.print(": ");
Serial.print(time);
Serial.print(" <-> ");
Serial.println(val);
}
*/
if (message_buffer.empty()) {
Serial.println("-- No data in buffer.");
return 0;
}
uint32_t t0 = time_buffer.pop_front();
uint32_t t1 = t0;
int v0 = message_buffer.pop_front();
int v1 = v0;
Serial.print("-- t0:\t");
Serial.print(t0);
Serial.print("\tv0:\t");
Serial.println(v0);
Serial.print("-- tf:\t");
Serial.print("---");
Serial.print("\tvf:\t");
Serial.println(vf);
for (int n = message_buffer.available() + 1; message_buffer.available() > 0; n--) {
static float ratio;
int vtemp;
uint32_t ttemp;
vtemp = message_buffer.pop_back();
ttemp = time_buffer.pop_back();
ratio = ((float) (vtemp - v0)) / ((float)(vf - v0));
/*
Serial.print("-- ");
Serial.print(n);
Serial.print(":\t");
Serial.print(ttemp);
Serial.print("\t \t");
Serial.print(vtemp);
Serial.print("\t \t");
Serial.println(ratio * 100, 2);
*/
//If % to goal is less than 63.2% break
if ( ratio <= RC_CONST) {
ratio = ((float) (v1 - v0)) / ((float)(vf - v0));
Serial.print("-- t");
Serial.print(n);
Serial.print(":\t");
Serial.print(t1);
Serial.print("\tv");
Serial.print("n:\t");
Serial.print(v1);
Serial.print("\t");
Serial.println(ratio * 100, 2);
break;
}
v1 = vtemp;
t1 = ttemp;
}
int trc = t1 - t0;
Serial.print("-- Time to RC constant (mills):\t");
Serial.println(trc);
if (trc <= 100) {
Serial.println("== [Pass] (<100ms)");
return 0;
}
else if (trc <= 160) {
Serial.println("== [Marginal pass] (<160ms)");
return 1;
}
else if (trc <= 250) {
Serial.println("== [Fail!] (<250ms)");
return 2;
}
else {
Serial.println("== [MAJOR FAIL!] (>250ms)");
return 3;
}
Serial.println("SOMETHING WEIRD SLIPPED THROUGH");
sing(9, buzzerPin);
return -1;
}
int resistanceCheck(float functionR)
{
/*
Ear 16 ohms or higher Recommend 32 - 300 ohms
0 67.5 Function A [Play/Pause]
135 187.5 Function D [Reserved/Nexus Voice command]
240 355 Function B [Vol+]
470 735 Function C [Vol-]
Mic 1000 ohms minimum
*/
float tolerance = 0;
float target = 0;
float drift = 0;
float rmin = 0;
float rmax = 0;
Serial.print("Running resistance check on "); Serial.println(functionR);
if (functionR < 0 || functionR > 100000){
Serial.println("-- Open circuit");
Serial.println("== [RESETTING]");
return -9;
}
if (functionR >= 800) {
target = 1000;
tolerance = -1;
rmin = 1000;
rmax = -1;
Serial.println("-- Microphone");
}
else if (functionR < 800 && functionR >= 355) {
target = 470;
tolerance = 1;
rmin = 355;
rmax = 800;
Serial.println("-- Function C [Vol-]");
}
else if (functionR < 355 && functionR >= 187.5) {
target = 240;
rmin = 187.5;
rmax = 355;
tolerance = 1;
Serial.println("-- Function B [Vol+]");
}
else if (functionR < 187.5 && functionR >= 67.5) {
target = 135;
tolerance = 1;
rmin = 67.5;
rmax = 187.5;
Serial.println("-- Function D [Reserved]");
}
else if (functionR < 67.5 && functionR >= 0) {
target = 0;
tolerance = -1;
rmin = -1;
rmax = 67.5;
Serial.println("-- Function A [Play/Pause]");
}
Serial.print("-- Drift of ");
// DO NOT drift-check (a) 0 target or (b)No-tolerance measurements
if (tolerance >= 0 && target > 0 ) {
drift = abs(functionR - target) / target * 100.0;
Serial.print(drift); Serial.print("%");
}
else {
drift = -1;
Serial.print(abs(functionR - target)); Serial.print("(abs)");
}
Serial.print(" from target ");
Serial.print(target, 0);
if (tolerance >= 0 && target > 0) {
Serial.print("±"); Serial.print(tolerance, 0); Serial.println("%");
}
else {
Serial.print(" (Limit");
if (rmin >= 0) {
Serial.print(" "); Serial.print(rmin); Serial.print(" min");
if (rmax >= 0) Serial.print (" -");
}
if (rmax >= 0) {
Serial.print(" "); Serial.print(rmax); Serial.print(" max");
}
Serial.println(")");
}
// drift = abs(functionR - target);
// tolerance = target * tolerance;
//PASS FAIL LOGIC
//===============
float toCompare = -1;
if (drift >= 0) {
if ( drift <= tolerance ) {
Serial.println("== [Pass (tolerance)]");
//sing(5, buzzerPin);
return 0;
}
}
if (functionR >= target)
toCompare = (rmax >= 0) ? rmax : -1;
if (functionR < target)
toCompare = (rmin >= 0) ? rmin : -1;
//If there's a checkbox
if (toCompare >= 0) {
//Get drift "to the limit that side"
drift = abs(functionR - target) / abs(target - toCompare) * 100.0;
Serial.print("-- Margin ");
Serial.print(drift); Serial.print("% of threshold ");
Serial.println(toCompare);
if (drift <= 25 ) {
Serial.println("== [Marginal pass]");
return 1;
//sing(2, buzzerPin);
}
else if (drift <= 50) {
Serial.println("== [Fail!]");
return 2;
//sing(4, buzzerPin);
////sing(8, buzzerPin);
}
else if (drift > 50) {
Serial.println("== [MAJOR FAIL!]");
return 3;
//sing(3, buzzerPin);
}
return 0;
}
else if (toCompare < 0) {
Serial.println("== [Pass (no limit)]");
//sing(5, buzzerPin);
return 0;
}
Serial.println("SOMETHING WEIRD SLIPPED THROUGH");
sing(9, buzzerPin);
return -1;
}
void flagTransition()
{
uint32_t t0 = millis();
uint32_t t1 = t0;
uint32_t x0 = t0;
int tempRead = 0;
int lastRead = 0;
bool neverRead = true;
bool quasiStable = false;
bool longStable = false;
float quasiVal;
float equivR;
int quasiRead = 0;
uint32 sumRead = 0;
int n = 0;
float threshold = ADC_TRIGGER_V;//.040; //.045
int adcThreshold = threshold * 1000.0 / (float) VCC_Self * 4095;
static int x_count = 0;
static bool logging = false;
while (true) {
Serial.print("Waiting for transition above "); Serial.print(threshold); Serial.print(" or ADC of "); Serial.println(adcThreshold);
while (true) {
delay(ADC_DELAY);
lastRead = tempRead;
tempRead = analogRead(PA0);
if (neverRead) {
neverRead = false;
lastRead = tempRead;
quasiRead = tempRead;
message_buffer.clear();
time_buffer.clear();
}
if (!logging) {
x0 = t1;
t1 = millis();
}
else {
t1 = millis();
message_buffer.push_back(tempRead);
time_buffer.push_back(t1);
}
//Serial.print(tempRead); Serial.print(" -- "); Serial.println( ((float)tempRead)/4095.0 * (float) VCC_Self/1000.0 ,4);
sumRead += tempRead;
n++;
//========================
// QUASI-STABLE LOGIC
if (quasiStable == false && t1 - t0 > 1000) {
quasiStable = true;
quasiRead = sumRead / n;
quasiVal = ((float) sumRead) / ((float)n) * ((float) VCC_Self) / 1000.0 / 4095.0;
Serial.print("Quasi-stable over "); Serial.print(n); Serial.print(" samples at "); Serial.print( quasiRead ); Serial.print(" = "); Serial.println( quasiVal , 4);
equivR = BIAS_R * quasiVal / ( BIAS_MV / 1000.0 - quasiVal);
Serial.print("Equivalent resistance: "); Serial.println(equivR);
}
//========================
// STABLE LOGIC
if (longStable == false && t1 - t0 > 2000) {
//Stop logging either here or in full stable
if (logging) {
logging = false;
digitalWrite(pinLED, HIGH);
Serial.print("±");
}
longStable = true;
quasiRead = sumRead / n;
quasiVal = ((float) sumRead) / ((float)n) * ((float) VCC_Self) / 1000.0 / 4095.0;
Serial.print("Stable over "); Serial.print(n); Serial.print(" samples at "); Serial.print( quasiRead ); Serial.print(" = "); Serial.println( quasiVal , 4);
equivR = BIAS_R * quasiVal / ( BIAS_MV / 1000.0 - quasiVal);
Serial.print("Equivalent resistance: "); Serial.println(equivR);
Serial.print("Circular buffer has "); Serial.print(message_buffer.available()); Serial.println(" entries");
Serial.println();
Serial.println("================");
int resistanceResult = resistanceCheck(equivR);
int timingResult = timingCheck(quasiRead);
resultIntegrate(resistanceResult, timingResult);
message_buffer.clear();
time_buffer.clear();
systick_uptime_millis = 0;
t1 = 0;
t0 = 0;
x0 = 0;
sumRead = 0;
n = 0;
neverRead = true;
//quasiStable=false; //optional
//longStable=false; //optional
}
//===================
// TRANSITION LOGIC
if (abs(tempRead - lastRead) >= adcThreshold || (quasiStable && abs(quasiRead - ((lastRead + tempRead) / 2)) >= adcThreshold / 2) ) {
if (quasiStable == true)
Serial.println();
if (!logging) {
Serial.print("±");
digitalWrite(pinLED, LOW);
logging = true;
message_buffer.clear();
time_buffer.clear();
// systick_uptime_millis = 0;
// x0=0;
// t0=0;
// t1=0;
message_buffer.push_back_nc(lastRead);
time_buffer.push_back_nc(x0); //x0
message_buffer.push_back_nc(tempRead);
time_buffer.push_back_nc(t1); //t1
}
x_count++;
Serial.print("TRANSITION! "); Serial.println(x_count);
if (abs(tempRead - lastRead) >= adcThreshold) {
//Serial.println("Mode A");
Serial.print (tempRead); Serial.print(" <=x= "); Serial.println(lastRead);
}
if (quasiStable && abs(quasiRead - tempRead) >= adcThreshold / 2) {
//Serial.println("Mode B");
Serial.print (tempRead); Serial.print(" <=q= "); Serial.println(quasiRead);
}
//CLEANUP post-transition detect
//DO NOT reset millis() here!!! Logging disrupted! systick_uptime_millis = 0;
t0 = t1;
sumRead = 0;
n = 0;
quasiStable = false;
longStable = false;
break;
}
}
}
return;
}
|
c012c6edc4369670743c82231c2ef74919717f0a
|
9a79e271ca0f54c7aa75e689127bc630592d9d6c
|
/Edge.cpp
|
cf027b2a0f2395aa95aa5ea4caa06659b04e938b
|
[] |
no_license
|
mnmz81/Smart-pointer-And-move-semantics
|
d4b2b0a4efc64c4cbd0f2f05a0b938551bc260ca
|
7e9bb1d5d46fa261c16d53ba44e108a50499e3d3
|
refs/heads/master
| 2022-12-10T16:48:18.451702
| 2020-09-10T10:45:10
| 2020-09-10T10:45:10
| 294,380,639
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,499
|
cpp
|
Edge.cpp
|
#include "Edge.h"
/******************************************************/
Edge::Edge(shared_ptr<Vertex>& d,Shipping& temp):from(temp.getSource()),dest(d),weightBoxs(temp.getBox()),weightTime(temp.getTime()){
this->allShiping.push_back(temp);
}
/******************************************************/
Edge::Edge(const Edge& temp):from(temp.from),dest(temp.dest),weightBoxs(temp.weightBoxs),weightTime(temp.weightTime),allShiping(temp.allShiping){}
/******************************************************/
Edge::Edge(Edge&& temp):from(temp.from),dest(temp.dest),weightBoxs(temp.weightBoxs),weightTime(temp.weightTime),allShiping(temp.allShiping){}
/******************************************************/
void Edge::upDateShipping(Shipping& newShiping){
this->allShiping.push_back(newShiping);
weightBoxs+=newShiping.getBox();
weightTime+=newShiping.getTime();
dest->getInfo().getNewShipping(newShiping);
}
/******************************************************/
string Edge::getDest(){
return dest->getInfo().Getlabel();
}
/******************************************************/
bool operator==(const Edge& lhs,const Edge& rhs){
if(*(lhs.dest)==*(rhs.dest)) return true;
return false;
}
/******************************************************/
bool operator==(const Edge &lhs, const string &rhs) {
if(lhs.dest->getInfo().Getlabel()==rhs) return true;
return false;
}
/******************************************************/
ostream& operator<<(ostream& out,const Edge& temp){
int sum=0;
if(temp.allShiping.size()!=0) sum=temp.weightTime/temp.allShiping.size();
out<<temp.dest->getInfo().Getlabel()<<","<<sum<<endl;
return out;
}
/******************************************************/
Edge &Edge::operator=(const Edge &rhs) {
if(this==&rhs) return *this;
from=rhs.from;
dest=rhs.dest;
weightBoxs=rhs.weightBoxs;
weightTime=rhs.weightTime;
allShiping.clear();
allShiping.assign(rhs.allShiping.begin(),rhs.allShiping.end());
return *this;
}
/******************************************************/
Edge &Edge::operator=(Edge &&rhs) {
if(this==&rhs) return *this;
from=rhs.from;
dest=rhs.dest;
weightBoxs=rhs.weightBoxs;
weightTime=rhs.weightTime;
allShiping.clear();
allShiping.assign(rhs.allShiping.begin(),rhs.allShiping.end());
return *this;
}
/******************************************************/
|
db6e3492dc53f07a76aba16668e8651fac12f164
|
908fbab5d1c478b6453d2657d0d75b5fa752ec06
|
/DEMO/mainwindow.cpp
|
42e8ff2636a3050db5988ef68a304509ea5b127e
|
[] |
no_license
|
zbl2018/draw_tool
|
bba7f273feef4e9ac32d40a80934094c00e88251
|
688962822fd4e4b7afea527b27012f42bd3a2c60
|
refs/heads/master
| 2020-03-16T20:58:32.487093
| 2018-05-17T04:07:07
| 2018-05-17T04:07:07
| 132,979,731
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,923
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "coordinate.h"
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsView>
#include <QApplication>
#include "myitem.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
submap_file_number = 0;
submap_mum = 0;
segments_index = "MapGenerator_Cartographer/input/segments.txt";
help_file_path = "help/help.txt";
segment_pos_num =0 ;
modify_angle_step_loc =-1;
ui->setupUi(this);
submap_scene = new QGraphicsScene; //场景
full_map_scene = new QGraphicsScene;
item =new PaintSubMap;
submap_coordinate_item = new coordinate;
full_map_coordinate_item = new coordinate;
submap_scene->addItem(item); //项添加到场景
submap_scene->addItem(submap_coordinate_item);
full_map_scene->addItem(full_map_coordinate_item);
ui->my_view->setScene(submap_scene); //视图关联场景
ui->full_map_view->setScene(full_map_scene);
ui->my_view->show(); //显示视图
ui->full_map_view->show();
connect(item,SIGNAL(sendsignallocation(point)),this,SLOT(getsignallocation(point)));
connect(ui->full_map_view,SIGNAL(ReturnLastAngle(bool)),this,SLOT(is_ReturnLastAngle(bool)));
connect(ui->full_map_view,SIGNAL(SkipNextAngle(bool)),this,SLOT(is_SkipNextAngle(bool)));
connect(ui->full_map_view,SIGNAL(SubMapPressKeyEvent(int)),this,SLOT(is_SubMapPressKeyEvent(int)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *event){
if ((event->modifiers() == Qt::ControlModifier)&&(event->key() == Qt::Key_H)){
QString info = PaintSubMap::ReadAllInfoFromFile(help_file_path);
QMessageBox::about(NULL,"help manual",info);
}
}
QString MainWindow::EraseTailZero(QString str){
int len = str.size();
for(int i = len -1;i>0;i--){
if(str[i]== '0')
str.chop(1);
else {
return str;
}
}
return str;
}
void MainWindow::getsignallocation(point loc)
{
// qDebug()<<"12dsdas1:"<<EraseTailZero(QString::number(loc.heading,'f',10))<<endl;
// qDebug()<<"pos:"<<qSetRealNumberPrecision(7)<<loc.x<<" "<<loc.y<<endl;
ui->lineEdit_x->setText(EraseTailZero(QString::number(loc.x,'f',6)));
ui->lineEdit_y->setText(EraseTailZero(QString::number(loc.y,'f',6)));
ui->lineEdit_heading->setText(EraseTailZero(QString::number(loc.heading,'f',6)));
}
void * MainWindow::thead_AdjustAngle(void * arg){
MainWindow * main = (MainWindow*)arg;
FILE *fp;
fp = popen("cd MapGenerator_Cartographer/&&./MapGenerator","r");
//wait for the terminatation of subprocess
while(true)
{
if(!feof(fp))
{
pclose(fp);
break;
}
}
main->th_status = true;
//qDebug()<<"12dsdas1:"<<endl;
}
void MainWindow::GetDrawMapSignal(PaintSubMap* ob)
{
//record which map had modified
modify_angle_step_loc++;
if(modify_angle_step_loc == record_which_map_modeified.size()){
record_which_map_modeified.append(ob->submap_number.toInt());
}
else{
record_which_map_modeified.replace(modify_angle_step_loc,ob->submap_number.toInt());
}
//qDebug()<<"mod:"<<record_which_map_modeified.at(modify_angle_step_loc-1)<<endl;
//qDebug()<<"line1:"<<modify_angle_step_loc<<" "<<record_which_map_modeified.size()<<endl;
on_exec_process_clicked();
}
void MainWindow::is_ReturnLastAngle(bool status){
if(status){
if(modify_angle_step_loc !=-1){
int loc = record_which_map_modeified.at(modify_angle_step_loc)-1;//the last submap modified
modify_angle_step_loc-- ;
submap_item[loc].optional_angle_index--; //retreat a step
//qDebug()<<"1:"<<submap_item[loc].optional_angle_index<<endl;
submap_item[loc].ModifyAAngleInSubmapsFile(submap_item[loc].submap_number.toInt(),submap_item[loc].save_optional_angel.at(submap_item[loc].optional_angle_index));
//qDebug()<<"2:"<<submap_item[loc].optional_angle_index<<endl;
on_exec_process_clicked();
}
else{
PaintSubMap::PrintAttentionInfo( "Cant't retreat!");
}
}
}
void MainWindow::is_SkipNextAngle(bool status){
if(status){
if(modify_angle_step_loc+1 != record_which_map_modeified.size()){
int loc = record_which_map_modeified.at(++modify_angle_step_loc)-1;//the last submap modified
// modify_angle_step_loc++ ;
submap_item[loc].optional_angle_index++; //go-forward a step
//qDebug()<<"1:"<<submap_item[loc].optional_angle_index<<endl;
submap_item[loc].ModifyAAngleInSubmapsFile(submap_item[loc].submap_number.toInt(),submap_item[loc].save_optional_angel.at(submap_item[loc].optional_angle_index));
//qDebug()<<"2:"<<submap_item[loc].optional_angle_index<<endl;
on_exec_process_clicked();
}
else {
PaintSubMap::PrintAttentionInfo("Can't Skip!");
}
}
}
void MainWindow::is_SubMapPressKeyEvent(int event_type){
switch(event_type){
case CTRL_H:{
QString info = PaintSubMap::ReadAllInfoFromFile(help_file_path);
QMessageBox::about(NULL,"help manual",info);
}
}
}
void MainWindow::on_read_file_clicked()
{
point loc;
QStringList node_list;
QString str;
submap_file_number++;
file_index = QString("MapGenerator_Cartographer/input/%1.txt").arg(submap_file_number);
if(isFileExist(file_index)){
submap = SetLineDataFromFile(file_index,SUBMAP_FILE,-1,-1);
ui->lineEdit_file_name->setText(QString("%1.txt").arg(submap_file_number));
}
else{
qDebug()<<"open file fail"<<endl;
submap_file_number = 1;
file_index = QString("MapGenerator_Cartographer/input/%1.txt").arg(submap_file_number);
submap = SetLineDataFromFile(file_index,SUBMAP_FILE,-1,-1);
}
ui->lineEdit_file_name->setText(QString("%1.txt").arg(submap_file_number));
item->SetMapData(submap,QString::number(submap_file_number));
submap.map_data.clear();
}
void MainWindow::on_get_point_clicked()
{
if(ui->lineEdit_x->text() == NULL || ui->lineEdit_y->text() == NULL || ui->lineEdit_heading->text() == NULL)
return;
point_str[segment_pos_num].x =ui->lineEdit_x->text();
point_str[segment_pos_num].y =ui->lineEdit_y->text();
point_str[segment_pos_num].heading =ui->lineEdit_heading->text();
segment_pos_num++;
if(segment_pos_num==2){
// int key = QMessageBox::information( this, "Application name here","The document contains unsaved changes","&Save", "&Discard", "&Cancel", 0,2 );
// switch(key) {
// case 0: // Save被点击或者Alt+S被按下或者Enter被按下。
// qDebug()<<"0"<<endl;
// break;
// case 1: // Discard被点击或者Alt+D被按下。
// // 不保存但退出
// qDebug()<<"1"<<endl;
// break;
// case 2: // Cancel被点击或者Alt+C被按下或者Escape被按下。
// qDebug()<<"2"<<endl;
// // 不退出
// break;
// }
bool isOK;
QString point_name;
QStringList point_name_list;
point_name = QInputDialog::getText(NULL, QString("this is %1").arg(ui->lineEdit_file_name->text()),
"Please input the name of the points: ",
QLineEdit::Normal,
"1,2",
&isOK);
if(isOK) {
point_name_list = point_name.split(",");
if(point_name_list.size() != 2||point_name_list.at(1)==NULL || point_name_list.at(0)==NULL ){
PaintSubMap::PrintAttentionInfo("the name is error! please get point again!");
segment_pos_num = 0;
return;
}
}
else{
segment_pos_num = 0;
return;
//qDebug()<<"2222:"<<optional_angle_index<<" "<<save_optional_angel.size()<<endl;
}
//save the point to segments file
QString filename = QString("%1.txt").arg(submap_file_number);
QFile file(segments_index);
if(file.open(QIODevice::WriteOnly|QIODevice::Append))
{
QTextStream out(&file);
out<<filename<<" "<<point_name_list.at(0)<<" "<<point_str[0].x<<" "<<point_str[0].y<<" "<<point_str[0].heading<<" "<<
point_name_list.at(1)<<" "<<point_str[1].x<<" "<<point_str[1].x<<" "<<point_str[1].heading<<endl;
segment_pos_num = 0;
PaintSubMap::PrintAttentionInfo("get the points successfully!");
//qDebug()<<"open segments file successfully"<<endl;
}
else{
qDebug()<<"open file fail"<<endl;
}
file.close();
}
}
void MainWindow::on_exec_process_clicked()
{
QProgressDialog status_process;
status_process.setLabelText(tr("generating fullmap again..."));
status_process.setRange(0,50000);
status_process.setModal(true);
status_process.setCancelButtonText(tr("cancel"));
status_process.setMinimumDuration(0);
pthread_t th_id;
th_status = false;
pthread_create(&th_id,NULL,thead_AdjustAngle,this);
int i = 0;
while(!th_status){
for(int j=0;j<25000;j++);
status_process.setValue(i);
if(i!=49999)
i++;
}
status_process.setValue(50000);
on_draw_map_clicked();
return;
}
void MainWindow::on_draw_map_clicked()
{
if(submap_mum == 0){
draw_full_map(ONCE_DRAW);
}
else draw_full_map(REDRAW);
}
void MainWindow::draw_full_map(int status){
QString str;
QString txt_name;
QStringList segments_list;
QStringList txt_name_list;
QString line_index;
int head,tail;
map line_data;
QFile file(segments_index);
int last_txt = 1;
if(file.open(QIODevice::ReadOnly))
{
//qDebug()<<"open file successfully"<<endl;
//QThread::sleep(3);
QTextStream in(&file);
while(!in.atEnd())
{
str = in.readLine();
if(str.compare("")==0)
continue;
segments_list = str.split(" ");
txt_name = segments_list.at(0);
head = segments_list.at(1).toInt();
tail = segments_list.at(5).toInt();
txt_name_list = txt_name.split(".");
txt_name = txt_name_list.at(0);
//read a lines file
line_index = QString("MapGenerator_Cartographer/lines/%1(%2-%3).txt").arg(txt_name).arg(head).arg(tail);
//qDebug()<<"www:"<<line_index<<endl;
if(!isFileExist(line_index))
{
continue;
}
line_data = SetLineDataFromFile(line_index,LINE_FILE,head,tail);
if(last_txt == txt_name.toInt()){
//qDebug()<<"last_txt:"<<last_txt<<" "<<txt_name.toInt()<<endl;
submap.map_data+=line_data.map_data;
submap.map_passage+=line_data.map_passage;
}
else{
//set submap map_data
submap_item[last_txt-1].SetMapData(submap,QString::number(txt_name.toInt()-1));
//add submap
if(status == ONCE_DRAW){
submap_mum++;
QObject::connect(&submap_item[last_txt-1],SIGNAL(SendDrawMapSignal(PaintSubMap*)),this,SLOT(GetDrawMapSignal(PaintSubMap*)));
full_map_scene->addItem(&submap_item[last_txt-1]);
}
submap.map_data.clear();
submap.map_passage.clear();
submap.map_data+=line_data.map_data;
submap.map_passage+=line_data.map_passage;
last_txt = txt_name.toInt();
}
str.clear();
}
submap_item[last_txt-1].SetMapData(submap,txt_name);
if(status == ONCE_DRAW){
submap_mum++;
QObject::connect(&submap_item[last_txt-1],SIGNAL(SendDrawMapSignal(PaintSubMap*)),this,SLOT(GetDrawMapSignal(PaintSubMap*)));
full_map_scene->addItem(&submap_item[last_txt-1]);
}
submap.map_data.clear();
submap.map_passage.clear();
}
else{
qDebug()<<"open file fail"<<endl;
}
submap.map_data.clear();
submap.map_passage.clear();
//qDebug()<<"num:"<<submap_mum<<endl;
}
map MainWindow::SetLineDataFromFile(QString file_index,int file_type,int head,int tail){
QFile file(file_index);
double x_pos,y_pos,heading_pos;
map one_passage;
// QVector<point> line_data;
passage line_info;
point loc;
QString str;
QStringList node_list;
bool first_node = false;
bool last_node =false;
//QVector<passasge>submap_line;
if(file.open(QIODevice::ReadOnly))
{
//qDebug()<<"open file successfully"<<endl;
QTextStream in(&file);
switch(file_type){
case SUBMAP_FILE:{
x_pos = 0;
y_pos = 1;
heading_pos = 2;
break;
}
case LINE_FILE:{
x_pos = 2;
y_pos = 4;
heading_pos = 7;
first_node = true;
last_node = true;
break;
}
}
while(!in.atEnd())
{
str = in.readLine();
if(str.compare("")==0)
continue;
node_list = str.split(" ");
loc.x = node_list.at(x_pos).toDouble()-0.3;
loc.y = node_list.at(y_pos).toDouble();
loc.heading = node_list.at(heading_pos).toDouble();
if(first_node){
//qDebug() <<"first: "<<first_node<<endl;
line_info.head = head;
loc.break_point = head;
one_passage.map_data.append(loc);
loc.break_point = -1;
first_node = false;
}
else one_passage.map_data.append(loc);
//qDebug() <<"line:"<< loc.x<<" "<<loc.y<<" "<< loc.heading<<" "<<loc.break_point<<endl;
str.clear();
}
if(last_node){
//the last point int this line
(one_passage.map_data.end()-1)->break_point = tail;
line_info.tail = tail;
//qDebug() <<"last node:"<< (line_data.end()-1)->x<<" "<<(line_data.end()-1)->y<<" "<< (line_data.end()-1)->heading<<" "<<(line_data.end()-1)->break_point<<endl;
}
one_passage.map_passage.append(line_info);
// for(int i =0;i<one_passage.map_data.size();i++){
// qDebug() <<"last node:"<<one_passage.map_data.at(i).x<<" "<<one_passage.map_data.at(i).y<<endl;
// }
// QFile fp("../DEMO/MapGenerator_Cartographer/input/temp.txt");
// if(fp.open(QIODevice::WriteOnly))
// {
// //qDebug()<<"open file successfully"<<endl;
// QTextStream out(&fp);
// for(int i =0;i<one_passage.map_data.size();i++){
// out<<one_passage.map_data.at(i).x<<" "<<one_passage.map_data.at(i).y<<" "<<one_passage.map_data.at(i).heading<<endl;
// }
// }
return one_passage;
}
else{
qDebug()<<"open file fail"<<endl;
//return;
}
}
bool MainWindow::isFileExist(QString fullFilePath)
{
QFileInfo fileInfo(fullFilePath);
if(fileInfo.exists())
{
return true;
}
return false;
}
|
59ee75fcbdbcf80218b116a56df8c2372435d4ff
|
cade12b2ff4411b2e26e9fef3caf660ea7a5aae9
|
/100-answers/13-first-bad-version.cpp
|
1ff3fcd2f11d01f7dba7cdbcf05ceabed5f9c6bd
|
[] |
no_license
|
hanrick2000/100
|
a53bbe85f9bb76b2c2d640b0a0dd1879d08a4b5f
|
fb6a8a4eaf9b3304b2f462f389b4b58e956c8c85
|
refs/heads/master
| 2020-12-31T08:12:24.292722
| 2019-08-03T15:12:52
| 2019-08-03T15:12:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 955
|
cpp
|
13-first-bad-version.cpp
|
/*
https://www.lintcode.com/en/problem/first-bad-version/
The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.
You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code's annotation part.
*/
class Solution {
public:
/*
* @param n: An integer
* @return: An integer which is the first bad version.
*/
int findFirstBadVersion(int n) {
int lo = 1;
int hi = n;
int mid;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
if (SVNRepo::isBadVersion(mid)) {
hi = mid;
if (lo == hi) break;
} else {
lo = mid + 1;
}
}
return mid;
}
};
|
4d2883584bb8f62b9dcfd355d76f6ad8229e7b3e
|
ac15d1b3c5a0173bbbd6d14f2b59f65fb15ff653
|
/tools/tileskin/main.cpp
|
f4a94e68a8e0ca5501c69728ab51ff9d5a091e3d
|
[] |
no_license
|
invoketeam/invokemagic
|
4c6d9a7fee40e141a5184b42fecc749ed11fb0ca
|
f2c355049e4f3ae0e51b15d38867420d84630897
|
refs/heads/master
| 2021-01-10T19:30:48.990796
| 2014-08-09T21:27:23
| 2014-08-09T21:27:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,565
|
cpp
|
main.cpp
|
#pragma warning (disable : 4786)
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <conio.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <cctype>
#define MINIZ_HEADER_FILE_ONLY
#define MINIZ_NO_STDIO
#define MINIZ_NO_TIME
#include "miniz.h"
#include "xImage.h"
void writePng(xImage * img, std::string fname)
{
if (img->dat == 0) { return; }
size_t size;
void * buf;
FILE * file;
img->endianSwap();
buf = tdefl_write_image_to_png_file_in_memory(img->dat, img->mw, img->mh, 4, &size);
img->endianSwap();
file = fopen(fname.c_str(), "wb");
fwrite(buf, 1, size, file);
fclose(file);
mz_free(buf);
}//writepng
class xCmnd
{
public:
std::vector <std::string> vecArg;
std::map <std::string, std::string> mapCmd;
public:
xCmnd() {}
bool hasCommand(std::string c)
{ return (mapCmd.count(c) > 0); }
std::string getCommandArg(std::string c)
{
if (mapCmd.count(c) < 1) { return "null"; }
return mapCmd[c];
}//getarg
void initArg(int argc, char * argv[])
{
int i;
std::string temp;
for (i = 0; i < argc; i++)
{
temp = argv[i];
vecArg.push_back(temp);
}//nexti
int num;
num = vecArg.size() - 1;
for (i = 0; i < num; i++)
{
if (isCommand(vecArg[i]))
{
if (isCommand(vecArg[i+1])==false)
{
temp = getCmdStr(vecArg[i]);
mapCmd[temp] = vecArg[i+1];
printf("Found command %s \n", temp.c_str());
}//endif2
}//endif
}//nexti
}//initarg
std::string getCmdStr(std::string in)
{
int k;
k = in.find_first_not_of('-');
return in.substr(k);
}//getcmdstr
bool isCommand(std::string &str)
{
if (str.size() < 2) { return false; }
if (str[0] == '-') { return true; }
if (str[1] == '-') { return true; }
return false;
}//iscommand
};//xcmnd
//maximum number of tiles in tiled
#define MAX_TILENUM 9999
xImage vecTile[MAX_TILENUM];
int getSize(int tw, int th, int num)
{
int i;
int size;
int cx, cy;
bool bDone;
size = 64;
bDone = false;
while (bDone == false)
{
size += size; //*2
cx = 1;
cy = 1;
bDone = true;
for (i = 0; i < num; i++)
{
cx += tw + 2;
if (cx+tw+tw+2 >= size) { cx = 1; cy += th + 2;}
if (cy >= size) { bDone = false; break; }
}//nexti
}//wend
xImage testImage;
testImage.init(size, size);
cx = 1;
cy = 1;
for (i = 0; i < num; i++)
{
testImage.drawRect(cx, cy,tw,th, 0xFF00FF00);
cx += tw + 2;
if (cx+tw+tw+2 >= size) { cx = 1; cy += th + 2;}
if (cy >= size) { break; }
}//nexti
writePng(&testImage, "out_testImage.png");
return size;
}//getsize
//might also need to save some file about the new coordinates of the tiles
//(a better idea is to generate the texture ingame)
void procTile(void)
{
xImage myImage;
xImage myTile;
xImage outImage;
int tw;
int th;
int size;
int maxNum;
int num;
//todo -- set these from parameters (min 8x8)
tw = 64; //32;
th = 64;// 32;
//todo -- also check the maximum number of tiles that fit in the image
num = 256; //512;
// myImage.loadImage("megaset.png");
myImage.loadImage("terratex.png");
maxNum = (myImage.mw/tw) * (myImage.mh/th);
printf("num %d maxNum %d \n", num, maxNum);
if (num > maxNum) { num = maxNum;}
if (num > MAX_TILENUM) { num = MAX_TILENUM; }
size = getSize(tw, th, num);
printf("size %d \n", size);
myTile.init(tw, th);
myTile.drawImage(&myImage, 0, 0);
writePng(&myTile, "out_test.png");
xImage * a;
int i;
int setw;
setw = myImage.mw/tw;
int kx, ky;
int cx, cy;
cx = 1;
cy = 1;
for (i = 0; i < num; i++)
{
kx = i % setw;
ky = i / setw;
a = &(vecTile[i]);
a->init(tw, th);
a->drawImage(&myImage, -(kx*tw), -(ky*th));
//a->drawImage(&myImage, 0, 0);
a->x = cx;
a->y = cy;
cx += tw + 2;
if (cx+tw+tw+2 >= size) { cx = 1; cy += th + 2;}
}//nexti
//save out tile
outImage.init(size, size);
for (i = 0; i < num; i++)
{
a = &(vecTile[i]);
//outImage.drawRect(a->x-1, a->y-1,tw+1,th+1, 0xFF00FF00);
//bleeding
outImage.drawImage(a, a->x-1, a->y);
outImage.drawImage(a, a->x+1, a->y);
outImage.drawImage(a, a->x, a->y-1);
outImage.drawImage(a, a->x, a->y+1);
//corners
outImage.setPixel(a->x-1, a->y-1, a->getPixel32(0,0));
outImage.setPixel(a->x+tw, a->y-1, a->getPixel32(tw-1,0));
outImage.setPixel(a->x-1, a->y+th, a->getPixel32(0,th-1));
outImage.setPixel(a->x+tw, a->y+th, a->getPixel32(tw-1,th-1));
outImage.drawImage(a, a->x, a->y);
}//outimage
writePng(&outImage, "out_done.png");
//the sprite file is special -- as it uses id instead of name
std::string picname;
std::ofstream myfile;
picname = "out_set";
myfile.open ((picname+".xms").c_str());
myfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
myfile << "<tiletex width=\""<< size <<"\" height=\""<< size <<"\" name=\"" << picname << ".png\">\n";
for (i = 0; i < num; i++)
{
a = &(vecTile[i]);
myfile << " <image x=\""<< (a->x) <<"\" y=\"" << (a->y) << "\" width=\""<< (a->mw) <<"\" height=\""<< (a->mh) <<"\" id=\""<< i <<"\"/>\n";
}//nextit
myfile << "</tiletex>\n";
myfile.close();
}//proctile
int main(int argc, char* argv[])
{
xCmnd myCommand;
myCommand.initArg(argc, argv);
procTile();
return 0;
}//main
|
dce5567c2f24eeca52aa69a8865efcfd53249979
|
7c0c04068f3802cac026901e6451a6a10f385146
|
/FileCoroutine.cpp
|
899f54fbedbe3505fdd667c83b5710fd5b32977f
|
[] |
no_license
|
deegoy2/crehoboam
|
89026bed5257c9405178302cabf58d2b32c484f2
|
418c030c5c063eaa4c301de9e15f0480be6c1f8b
|
refs/heads/main
| 2023-05-02T17:21:03.495997
| 2023-05-01T10:11:51
| 2023-05-01T10:11:51
| 370,427,833
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,719
|
cpp
|
FileCoroutine.cpp
|
#include <iostream>
#include <fstream>
#include <coroutine>
#include <future>
using namespace std;
// using namespace std::experimental;
struct FileReader {
const char* filename;
ifstream file;
FileReader(const char* fn) : filename(fn), file(filename, ios::binary) {}
struct promise_type {
char* buffer;
FileReader get_return_object() {
return FileReader(nullptr);
}
auto initial_suspend() {
return suspend_never{};
}
auto final_suspend() {
return suspend_always{};
}
void unhandled_exception() {
terminate();
}
auto yield_value(char* buf) {
buffer = buf;
return suspend_always{};
}
char* value() {
return buffer;
}
};
FileReader(FileReader&& other) : filename(other.filename), file(move(other.file)) {}
bool await_ready() {
return file.good();
}
void await_suspend(coroutine_handle<promise_type> handle) {
char* buffer = new char[1024];
if (file.read(buffer, 1024)) {
handle.promise().yield_value(buffer);
} else {
handle.promise().yield_value(nullptr);
}
}
char* await_resume() {
return nullptr;
}
};
int main() {
FileReader reader("filename.ext"); // replace filename.ext with the name of your file
auto coroutine = [&]() -> coroutine_handle<> {
while (true) {
char* data = co_await reader;
if (!data) break;
// do something with the data
delete[] data;
}
co_return {};
};
coroutine();
return 0;
}
|
1651067a9994d42325441362da0559ad3ab1f31b
|
f6814c464c9c43bf1c5fb4a7acfcaabc3bef0a6e
|
/runtime/gc/accounting/heap_bitmap.h
|
987e77facdd2de251dbb93ef430a23240e71af57
|
[
"Apache-2.0"
] |
permissive
|
fizous/gcaas-kk-art
|
1fc7727dd62d57b48ea5291ae194db53fee57e05
|
7012dc776b90fa7c417d97c5176e59a4addb7774
|
refs/heads/master
| 2021-07-20T05:18:20.919937
| 2017-10-30T02:36:37
| 2017-10-30T02:36:37
| 108,298,128
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,278
|
h
|
heap_bitmap.h
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_RUNTIME_GC_ACCOUNTING_HEAP_BITMAP_H_
#define ART_RUNTIME_GC_ACCOUNTING_HEAP_BITMAP_H_
#include "base/logging.h"
#include "gc_allocator.h"
#include "locks.h"
#include "space_bitmap.h"
#define GC_SERVICE_SHARABLE_HEAP_BITMAP ART_GC_SERVICE
#ifndef BASE_HEAP_BITMAP_T
#if (ART_GC_SERVICE)
#define BASE_HEAP_BITMAP_T BaseHeapBitmap
#else
#define BASE_HEAP_BITMAP_T HeapBitmap
#endif
#endif
namespace art {
namespace gc {
class Heap;
namespace accounting {
#if (ART_GC_SERVICE)
class SharedHeapBitmap;
class BaseHeapBitmap {
public:
static BaseHeapBitmap* CreateHeapBitmap(/*Heap* heap,*/ bool sharable = false);
static BaseHeapBitmap* ReShareHeapBitmap(/*Heap* heap,*/ SharedHeapBitmap* originalBMap,
GCSrvceSharedHeapBitmap* header_addr);
virtual bool Test(const mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
virtual bool TestNoLock(const mirror::Object* obj);
virtual void Clear(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
virtual void Set(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
virtual SPACE_BITMAP* GetContinuousSpaceBitmap(const mirror::Object* obj) = 0;
virtual void Walk(SPACE_BITMAP::Callback* callback, void* arg)
SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) = 0;
template <typename Visitor>
void Visit(const Visitor& visitor)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Find and replace a bitmap pointer, this is used by for the bitmap swapping in the GC.
virtual void ReplaceBitmap(SPACE_BITMAP* old_bitmap, SPACE_BITMAP* new_bitmap)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) = 0;
// Find and replace a object set pointer, this is used by for the bitmap swapping in the GC.
virtual void ReplaceObjectSet(SpaceSetMap*, SpaceSetMap*)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_){}
explicit BaseHeapBitmap(/*Heap* */) {}
virtual ~BaseHeapBitmap(){}
virtual void AddContinuousSpaceBitmap(SPACE_BITMAP*) = 0;
virtual void AddDiscontinuousObjectSet(SpaceSetMap*){}
virtual int GetContinuousSize() = 0;
virtual SPACE_BITMAP* GetContBitmapFromIndex(int index) = 0;
virtual int GetDiscContinuousSize() {
return 0;
}
virtual SpaceSetMap* GetDiscContBitmapFromIndex(int index){
return NULL;
}
};//class BaseHeapBitmap
class SharedHeapBitmap : public BaseHeapBitmap {
public:
typedef std::vector<SPACE_BITMAP*, GCAllocator<SPACE_BITMAP*> > SpaceBitmapVector;
static int MaxHeapBitmapIndex;
SharedHeapBitmap(/*Heap* heap, */GCSrvceSharedHeapBitmap* header_addr = NULL);
~SharedHeapBitmap(){}
void AddContinuousSpaceBitmap(SPACE_BITMAP* bitmap);
void Walk(SPACE_BITMAP::Callback* callback, void* arg)
SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
void ReplaceBitmap(SPACE_BITMAP* old_bitmap, SPACE_BITMAP* new_bitmap)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
void FixDataEntries(void);
// SPACE_BITMAP* GetContinuousSpaceBitmap(const mirror::Object* obj) {
// SPACE_BITMAP* _bitmap = NULL;
// for(int i = 0; i < header_->index_; i ++) {
// _bitmap = header_->bitmaps_[i];
// if (_bitmap->HasAddress(obj)) {
// return _bitmap;
// }
// }
// return NULL;
// }
SPACE_BITMAP* GetContinuousSpaceBitmap(const mirror::Object* obj) {
for (const auto& bitmap : continuous_space_bitmaps_) {
if (bitmap->HasAddress(obj)) {
return bitmap;
}
}
return NULL;
}
int GetContinuousSize() {
return continuous_space_bitmaps_.size();
}
// int GetContinuousSize() {
// return header_->index_;
// }
// SPACE_BITMAP* GetContBitmapFromIndex(int index) {
// return header_->bitmaps_[index];
// }
SPACE_BITMAP* GetContBitmapFromIndex(int index) {
return continuous_space_bitmaps_[index];
}
GCSrvceSharedHeapBitmap* header_;
// Bitmaps covering continuous spaces.
SpaceBitmapVector continuous_space_bitmaps_;
private:
};
////////////////////////////////////////////////////////////////
class HeapBitmap : public BaseHeapBitmap {
public:
typedef std::vector<SPACE_BITMAP*, GCAllocator<SPACE_BITMAP*> > SpaceBitmapVector;
typedef std::vector<SpaceSetMap*, GCAllocator<SpaceSetMap*> > SpaceSetMapVector;
bool Test(const mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
void Clear(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
void Set(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
SPACE_BITMAP* GetContinuousSpaceBitmap(const mirror::Object* obj) {
for (const auto& bitmap : continuous_space_bitmaps_) {
if (bitmap->HasAddress(obj)) {
return bitmap;
}
}
return NULL;
}
SpaceSetMap* GetDiscontinuousSpaceObjectSet(const mirror::Object* obj) {
for (const auto& space_set : discontinuous_space_sets_) {
if (space_set->Test(obj)) {
return space_set;
}
}
return NULL;
}
void Walk(SPACE_BITMAP::Callback* callback, void* arg)
SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
// Find and replace a bitmap pointer, this is used by for the bitmap swapping in the GC.
void ReplaceBitmap(SPACE_BITMAP* old_bitmap, SPACE_BITMAP* new_bitmap)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
// Find and replace a object set pointer, this is used by for the bitmap swapping in the GC.
void ReplaceObjectSet(SpaceSetMap* old_set, SpaceSetMap* new_set)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
explicit HeapBitmap(/*Heap* heap*/) : BaseHeapBitmap(/*heap*/){}//, heap_(heap) {}
void AddContinuousSpaceBitmap(SPACE_BITMAP* bitmap);
void AddDiscontinuousObjectSet(SpaceSetMap* set);
int GetContinuousSize() {
return continuous_space_bitmaps_.size();
}
SPACE_BITMAP* GetContBitmapFromIndex(int index) {
return continuous_space_bitmaps_[index];
}
int GetDiscContinuousSize() {
return discontinuous_space_sets_.size();
}
SpaceSetMap* GetDiscContBitmapFromIndex(int index) {
return discontinuous_space_sets_[index];
}
//const Heap* const heap_;
private:
// Bitmaps covering continuous spaces.
SpaceBitmapVector continuous_space_bitmaps_;
// Sets covering discontinuous spaces.
SpaceSetMapVector discontinuous_space_sets_;
//friend class art::gc::Heap;
};
#else
class HeapBitmap {
public:
typedef std::vector<SpaceBitmap*, GCAllocator<SpaceBitmap*> > SpaceBitmapVector;
typedef std::vector<SpaceSetMap*, GCAllocator<SpaceSetMap*> > SpaceSetMapVector;
bool Test(const mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
SpaceBitmap* bitmap = GetContinuousSpaceBitmap(obj);
if (LIKELY(bitmap != NULL)) {
return bitmap->Test(obj);
} else {
return GetDiscontinuousSpaceObjectSet(obj) != NULL;
}
}
bool TestNoLock(const mirror::Object* obj) {
SPACE_BITMAP* bitmap = GetContinuousSpaceBitmap(obj);
if (LIKELY(bitmap != NULL)) {
return bitmap->Test(obj);
} else {
LOG(FATAL) << "Test: object does not belong to any bitmap";
}
return false;
}
void Clear(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
SpaceBitmap* bitmap = GetContinuousSpaceBitmap(obj);
if (LIKELY(bitmap != NULL)) {
bitmap->Clear(obj);
} else {
SpaceSetMap* set = GetDiscontinuousSpaceObjectSet(obj);
DCHECK(set != NULL);
set->Clear(obj);
}
}
void Set(const mirror::Object* obj) EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
SpaceBitmap* bitmap = GetContinuousSpaceBitmap(obj);
if (LIKELY(bitmap != NULL)) {
bitmap->Set(obj);
} else {
SpaceSetMap* set = GetDiscontinuousSpaceObjectSet(obj);
DCHECK(set != NULL);
set->Set(obj);
}
}
SpaceBitmap* GetContinuousSpaceBitmap(const mirror::Object* obj) {
for (const auto& bitmap : continuous_space_bitmaps_) {
if (bitmap->HasAddress(obj)) {
return bitmap;
}
}
return NULL;
}
SpaceSetMap* GetDiscontinuousSpaceObjectSet(const mirror::Object* obj) {
for (const auto& space_set : discontinuous_space_sets_) {
if (space_set->Test(obj)) {
return space_set;
}
}
return NULL;
}
void Walk(SpaceBitmap::Callback* callback, void* arg)
SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
template <typename Visitor>
void Visit(const Visitor& visitor)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
// Find and replace a bitmap pointer, this is used by for the bitmap swapping in the GC.
void ReplaceBitmap(SpaceBitmap* old_bitmap, SpaceBitmap* new_bitmap)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
// Find and replace a object set pointer, this is used by for the bitmap swapping in the GC.
void ReplaceObjectSet(SpaceSetMap* old_set, SpaceSetMap* new_set)
EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_);
explicit HeapBitmap(Heap* heap) : heap_(heap) {}
private:
const Heap* const heap_;
void AddContinuousSpaceBitmap(SpaceBitmap* bitmap);
void AddDiscontinuousObjectSet(SpaceSetMap* set);
// Bitmaps covering continuous spaces.
SpaceBitmapVector continuous_space_bitmaps_;
// Sets covering discontinuous spaces.
SpaceSetMapVector discontinuous_space_sets_;
friend class art::gc::Heap;
};
#endif
} // namespace accounting
} // namespace gc
} // namespace art
#endif // ART_RUNTIME_GC_ACCOUNTING_HEAP_BITMAP_H_
|
3ca795447a841e7ae86ca07b04060b52c769c8db
|
5330f231335e58492cf31fb7040394011002728e
|
/DoAn/HeSo.h
|
938e67dabe9f836c58f03038c4bbb289fc681562
|
[] |
no_license
|
xxxcodexxx/OOP
|
806c74f37987731c6362ab95de3e2b4688d39b6a
|
455c998b7c2a95efe7eaca550aec2de42f03ccc8
|
refs/heads/master
| 2021-01-21T14:53:27.490740
| 2017-06-25T16:52:59
| 2017-06-25T16:52:59
| 95,353,961
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 279
|
h
|
HeSo.h
|
#pragma once
#include <string>
using namespace std;
class HeSo
{
protected:
int heSo;
string value;
void convertToNotDec(int);
void convertToDec();
public:
void setVal(string val);
string getVal();
int getHeSo();
};
class HeSo2;
class HeSo8;
class HeSo10;
class HeSo16;
|
94161e1570972293464bb72c2f4e572f94a892dc
|
03867cfe1b76d650b70853aeb5e378c9f9c67b7d
|
/L2andJERScripts/extrapol_helpers.h
|
b69036a918af63700a2c009a991ee6074961ebbc
|
[] |
no_license
|
stadie/Kalibri
|
7a350f495751b8eb57809cf4986d8aa1a9ee9d4a
|
049132730ec1c37ccf00555aacc202ec1f853af6
|
refs/heads/master
| 2016-09-06T13:34:51.102082
| 2014-08-08T15:39:34
| 2014-08-08T15:39:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,902
|
h
|
extrapol_helpers.h
|
void setStyle()
{
gStyle->SetPalette(1);
// For the canvas:
gStyle->SetCanvasBorderMode(0);
gStyle->SetCanvasColor(kWhite);
gStyle->SetCanvasDefH(800); //Height of canvas
gStyle->SetCanvasDefW(800); //Width of canvas
gStyle->SetCanvasDefX(0); //Position on screen
gStyle->SetCanvasDefY(0);
// For the frame
gStyle->SetFrameBorderMode(0);
gStyle->SetFrameBorderSize(1);
gStyle->SetFrameFillColor(kBlack);
gStyle->SetFrameFillStyle(0);
gStyle->SetFrameLineColor(kBlack);
gStyle->SetFrameLineStyle(0);
gStyle->SetFrameLineWidth(1);
// For the Pad:
gStyle->SetPadBorderMode(0);
gStyle->SetPadColor(kWhite);
gStyle->SetPadGridX(false);
gStyle->SetPadGridY(false);
gStyle->SetGridColor(0);
gStyle->SetGridStyle(3);
gStyle->SetGridWidth(1);
// For the histo:
gStyle->SetHistLineColor(kBlack);
gStyle->SetHistLineStyle(0);
gStyle->SetHistLineWidth(1);
// For the statistics box:
gStyle->SetOptStat(0);
// gStyle->SetOptStat("neMR");
gStyle->SetStatColor(kWhite);
gStyle->SetStatFont(42);
gStyle->SetStatFontSize(0.03);
gStyle->SetStatTextColor(1);
gStyle->SetStatFormat("6.4g");
gStyle->SetStatBorderSize(1);
gStyle->SetStatX(0.92);
gStyle->SetStatY(0.86);
gStyle->SetStatH(0.16);
gStyle->SetStatW(0.22);
// For the legend
gStyle->SetLegendBorderSize(1);
// Margins
// -------------------------------------------
gStyle->SetPadTopMargin(0.16);
gStyle->SetPadBottomMargin(0.18);
gStyle->SetPadLeftMargin(0.19);
gStyle->SetPadRightMargin(0.18);
// For the Global title:
gStyle->SetOptTitle(1);
gStyle->SetTitleFont(42,"");
gStyle->SetTitleColor(1);
gStyle->SetTitleTextColor(1);
gStyle->SetTitleFillColor(0);
gStyle->SetTitleFontSize(0.12);
gStyle->SetTitleAlign(23);
gStyle->SetTitleX(0.515);
gStyle->SetTitleY(0.999);
gStyle->SetTitleH(0.06);
gStyle->SetTitleXOffset(0);
gStyle->SetTitleYOffset(0);
gStyle->SetTitleBorderSize(0);
// For the axis labels:
// For the axis labels and titles
// -------------------------------------------
gStyle->SetTitleColor(1,"XYZ");
gStyle->SetLabelColor(1,"XYZ");
// For the axis labels:
gStyle->SetLabelFont(42,"XYZ");
gStyle->SetLabelOffset(0.007,"XYZ");
gStyle->SetLabelSize(0.045,"XYZ");
// For the axis titles:
gStyle->SetTitleFont(42,"XYZ");
gStyle->SetTitleSize(0.06,"XYZ");
gStyle->SetTitleXOffset(1.2);
gStyle->SetTitleYOffset(1.5);
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
void TH1style(TH1D* histo, std::vector<Int_t> line_styles_, std::vector<Int_t> colours_, std::vector<Int_t> markers_, Int_t line_style, Int_t colour, Int_t marker, TString ytitle)
{
histo->SetMarkerStyle(markers_[marker]);
histo->SetMarkerColor(colours_[colour]);
histo->SetLineColor(colours_[colour]);
histo->SetLineStyle(line_styles_[line_style]);
histo->GetYaxis()->SetTitle(ytitle);
}
void TH1style_plus_fit(TH1D* histo, std::vector<Int_t> line_styles_, std::vector<Int_t> colours_, std::vector<Int_t> markers_, Int_t line_style, Int_t colour, Int_t marker, TString ytitle, TString fit_func_name)
{
histo->SetMarkerStyle(markers_[marker]);
histo->SetMarkerColor(colours_[colour]);
histo->SetLineColor(colours_[colour]);
histo->SetLineStyle(line_styles_[line_style]);
histo->GetYaxis()->SetTitle(ytitle);
if( histo->GetFunction(fit_func_name)){
histo->GetFunction(fit_func_name)->SetLineColor(colours_[colour]);
histo->GetFunction(fit_func_name)->SetLineStyle(line_styles_[line_style]);
}
}
void TGraphErrorsstyle(TGraphErrors* histo, std::vector<Int_t> line_styles_, std::vector<Int_t> colours_, std::vector<Int_t> markers_, Int_t line_style, Int_t colour, Int_t marker, TString ytitle)
{
histo->SetMarkerStyle(markers_[marker]);
histo->SetMarkerColor(colours_[colour]);
histo->SetLineColor(colours_[colour]);
histo->SetLineStyle(line_styles_[line_style]);
histo->GetYaxis()->SetTitle(ytitle);
}
void pm_eta_TGraph_draw(TCanvas* draw_canvas, TGraphErrors* all_eta, TGraphErrors* abs_eta,std::vector<Int_t> line_styles_, std::vector<Int_t> colours_, std::vector<Int_t> markers_)
{
Int_t no_abseta_points=abs_eta->GetN();
if(all_eta->GetN()!=2*no_abseta_points)cout << "da laeuft was schief alleta N: "<< all_eta->GetN() << " and " <<no_abseta_points << endl;
Double_t* abs_eta_x=abs_eta->GetX();
Double_t* abs_eta_ex=abs_eta->GetEX();
Double_t* all_eta_y=all_eta->GetY();
Double_t* all_eta_ey=all_eta->GetEY();
// Double_t* all_eta_x=all_eta->GetX();
// Double_t* all_eta_ex=all_eta->GetEX();
std::vector < Double_t > plus_eta_y;
std::vector < Double_t > plus_eta_ey;
std::vector < Double_t > minus_eta_y;
std::vector < Double_t > minus_eta_ey;
for(Int_t array_i=0;array_i<no_abseta_points;array_i++){
plus_eta_y.push_back(all_eta_y[no_abseta_points+array_i]);
plus_eta_ey.push_back(all_eta_ey[no_abseta_points+array_i]);
minus_eta_y.push_back(all_eta_y[no_abseta_points-(array_i+1)]);
minus_eta_ey.push_back(all_eta_ey[no_abseta_points-(array_i+1)]);
// cout << "Abseta eta: " << abs_eta_x[array_i] << " alleta plus_eta: " << all_eta_x[no_abseta_points+array_i] << " alleta minus_eta: " << all_eta_x[no_abseta_points-(array_i+1)] << endl;
}
TGraphErrors *plus_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&plus_eta_y[0],abs_eta_ex,&plus_eta_ey[0]);
TGraphErrors *minus_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&minus_eta_y[0],abs_eta_ex,&minus_eta_ey[0]);
TGraphErrorsstyle(abs_eta,line_styles_, colours_, markers_, 0,0,0,"bla");
TGraphErrorsstyle(plus_eta,line_styles_, colours_, markers_, 0,1,1,"bla");
TGraphErrorsstyle(minus_eta,line_styles_, colours_, markers_, 0,2,2,"bla");
abs_eta->Draw("ALP");
abs_eta->GetXaxis()->SetTitle("|#eta|");
abs_eta->GetYaxis()->SetTitle("Correction factor");
abs_eta->GetYaxis()->SetRangeUser(0.8,1.2);
//p1->DrawClone();
cout << "was ist hier...?" << endl;
plus_eta->Draw("P same");
minus_eta->Draw("P same");
TLegend *leg_selected;
leg_selected = new TLegend(0.2,0.70,0.55,0.85);
leg_selected->SetFillColor(kWhite);
// leg->SetHeader("Legende");
leg_selected->AddEntry(abs_eta,"(|#eta|)","lep");
leg_selected->AddEntry(plus_eta,"(+#eta)","lep");
leg_selected->AddEntry(minus_eta,"(-#eta)","lep");
leg_selected->Draw();
draw_canvas->Print((TString)"PM_eta_draw"+abs_eta->GetName()+(TString) ".eps");
}
void pm_eta_TGraph_draw(TCanvas* draw_canvas, TGraphErrors* all_eta, TGraphErrors* abs_eta, TH1D* abs_eta_histo, std::vector<Int_t> line_styles_, std::vector<Int_t> colours_, std::vector<Int_t> markers_, TString ytitle, Double_t y_low=0.8, Double_t y_hig=1.2)
{
Int_t no_abseta_points=abs_eta->GetN();
if(all_eta->GetN()!=2*no_abseta_points)cout << "da laeuft was schief alleta N: "<< all_eta->GetN() << " and " <<no_abseta_points << endl;
Double_t* abs_eta_x=abs_eta->GetX();
Double_t* abs_eta_ex=abs_eta->GetEX();
Double_t* all_eta_y=all_eta->GetY();
Double_t* all_eta_ey=all_eta->GetEY();
// Double_t* all_eta_x=all_eta->GetX();
// Double_t* all_eta_ex=all_eta->GetEX();
std::vector < Double_t > plus_eta_y;
std::vector < Double_t > plus_eta_ey;
std::vector < Double_t > minus_eta_y;
std::vector < Double_t > minus_eta_ey;
std::vector < Double_t > diff_eta_y;
std::vector < Double_t > diff_eta_ey;
std::vector < Double_t > diff_eta_offset_y;
std::vector < Double_t > diff_eta_offset_ey;
for(Int_t array_i=0;array_i<no_abseta_points;array_i++){
plus_eta_y.push_back(all_eta_y[no_abseta_points+array_i]);
plus_eta_ey.push_back(all_eta_ey[no_abseta_points+array_i]);
minus_eta_y.push_back(all_eta_y[no_abseta_points-(array_i+1)]);
minus_eta_ey.push_back(all_eta_ey[no_abseta_points-(array_i+1)]);
diff_eta_y.push_back(plus_eta_y.back()-minus_eta_y.back());
diff_eta_ey.push_back(TMath::Sqrt(TMath::Power(plus_eta_ey.back(),2)+TMath::Power(minus_eta_ey.back(),2)));
diff_eta_offset_y.push_back(plus_eta_y.back()-minus_eta_y.back()+y_low);
diff_eta_offset_ey.push_back(TMath::Sqrt(TMath::Power(plus_eta_ey.back(),2)+TMath::Power(minus_eta_ey.back(),2)));
// cout << "Abseta eta: " << abs_eta_x[array_i] << " alleta plus_eta: " << all_eta_x[no_abseta_points+array_i] << " alleta minus_eta: " << all_eta_x[no_abseta_points-(array_i+1)] << endl;
}
TGraphErrors *plus_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&plus_eta_y[0],abs_eta_ex,&plus_eta_ey[0]);
TGraphErrors *minus_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&minus_eta_y[0],abs_eta_ex,&minus_eta_ey[0]);
TGraphErrors *diff_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&diff_eta_y[0],abs_eta_ex,&diff_eta_ey[0]);
TGraphErrors *diff_offset_eta = new TGraphErrors(no_abseta_points,abs_eta_x,&diff_eta_offset_y[0],abs_eta_ex,&diff_eta_offset_ey[0]);
TGraphErrorsstyle(abs_eta,line_styles_, colours_, markers_, 0,0,0,"bla");
TGraphErrorsstyle(plus_eta,line_styles_, colours_, markers_, 0,1,1,"bla");
TGraphErrorsstyle(minus_eta,line_styles_, colours_, markers_, 0,2,2,"bla");
TGraphErrorsstyle(diff_eta,line_styles_, colours_, markers_, 4,4,4,"bla");
TGraphErrorsstyle(diff_offset_eta,line_styles_, colours_, markers_, 4,4,4,"bla");
TH1style(abs_eta_histo,line_styles_, colours_, markers_, 0,0,0,"bla");
abs_eta_histo->Draw("hist");
abs_eta_histo->GetXaxis()->SetTitle("|#eta|");
abs_eta_histo->GetYaxis()->SetTitle(ytitle);
abs_eta_histo->GetYaxis()->SetRangeUser(y_low,y_hig);
//p1->DrawClone();
cout << "was ist hier...?" << endl;
plus_eta->Draw("P same");
minus_eta->Draw("P same");
TLegend *leg_selected;
leg_selected = new TLegend(0.2,0.70,0.55,0.85);
leg_selected->SetFillColor(kWhite);
// leg->SetHeader("Legende");
leg_selected->AddEntry(abs_eta,"(|#eta|)","le");
leg_selected->AddEntry(plus_eta,"(+#eta)","lep");
leg_selected->AddEntry(minus_eta,"(-#eta)","lep");
leg_selected->Draw();
draw_canvas->Print((TString)"PM_eta_draw_hist"+abs_eta->GetName()+(TString) ".eps");
TLine *line_offset = new TLine(abs_eta_x[0],y_low,abs_eta_x[no_abseta_points-1]+2,y_low);
line_offset->SetLineStyle(2);
abs_eta_histo->GetYaxis()->SetRangeUser(y_low-0.1,y_hig);
diff_offset_eta->Draw("P same");
line_offset->Draw();
TPaveText pt(.01,.25,.1,.35,"NDC ARC br");
pt.SetFillColor(kWhite);
pt.SetBorderSize(5);
pt.SetLineColor(kBlack);
// pt.SetLabel("Diff:");
pt.AddText("Diff:");
pt.Draw();
draw_canvas->Print((TString)"PM_eta_draw_hist_overlay_diff_"+abs_eta->GetName()+(TString) ".eps");
TLine *line = new TLine(abs_eta_x[0],0.0,abs_eta_x[no_abseta_points-1]+2,0.0);
line->SetLineStyle(2);
diff_eta->Draw("ALP");
diff_eta->GetYaxis()->SetRangeUser(-0.025,+0.025);
line->Draw();
draw_canvas->Print((TString)"PM_eta_draw_hist_difference"+abs_eta->GetName()+(TString) ".eps");
}
|
f4a4470ce245c3b777aec6f858f65b3d8102ddb5
|
e566fc4b0b1e035ec228fdde3d66a29c890c60d1
|
/src/comm_fp_inst
|
875ba2ae9de73a8d0af72db4b83220f51724758a
|
[] |
no_license
|
ExaScience/shark
|
a092c0d2d8c67fb7ca80355ac6b01d62e51c1e10
|
87cf885ddd76c5bf06260088fbe9302933d6daf7
|
refs/heads/master
| 2021-06-24T05:35:58.967343
| 2016-09-07T09:08:59
| 2016-09-07T09:08:59
| 6,867,622
| 9
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 680
|
comm_fp_inst
|
// vim: ft=cpp
#define COMMA ,
#if defined(SHARK_MPI_COMM)
SYMBT(float)
SYMBT(double)
SYMBT(std::valarray<float>)
SYMBT(std::valarray<double>)
#define SYMBD(d) SYMBT(shark::ndim::vec<d COMMA float>)
#include "inst_dim"
#undef SYMBD
#define SYMBD(d) SYMBT(shark::ndim::vec<d COMMA double>)
#include "inst_dim"
#undef SYMBD
#elif defined(SHARK_NO_COMM)
SYMBT(float)
SYMBT(double)
SYMBT(std::valarray<float>)
SYMBT(std::valarray<double>)
#define SYMBD(d) SYMBT(shark::ndim::vec<d COMMA float>)
#include "inst_dim"
#undef SYMBD
#define SYMBD(d) SYMBT(shark::ndim::vec<d COMMA double>)
#include "inst_dim"
#undef SYMBD
#else
#error "No comm defined"
#endif
#undef COMMA
|
|
b47920a7620f309af67a8a744b9470aa13e85126
|
01a946f5b9f454f66c1d515d074eafe6b81ace4a
|
/DLL/useDll2/main.cpp
|
1cd0484a64a934565b8e8ce4236faf96e621478e
|
[
"Apache-2.0"
] |
permissive
|
kingmax/cpp
|
bd70f7deb5bee7941f3358cb4f0b0d53a50d15b6
|
b0c3abcfc77094421d906695a4ac167463a43b92
|
refs/heads/master
| 2021-05-04T23:40:05.373647
| 2021-05-04T16:15:11
| 2021-05-04T16:15:11
| 119,319,341
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 257
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
//#pragma comment(lib, "Dll1.lib")
//_declspec(dllexport) int add(int, int);
_declspec(dllimport) int add(int, int);
int main()
{
cout << 1 << "+" << 2 << "=" << add(1, 2) << endl;
system("pause");
return 0;
}
|
d22488cdf9e051245bdbb38eb9dc439e52433fde
|
a85a1e6c776e0433c30aa5830aa353a82f4c8833
|
/coregame_ai/strategic_resource.cpp
|
674165a688abd724203fa50415e0a811b6704424
|
[] |
no_license
|
IceCube-22/darkreign2
|
fe97ccb194b9eacf849d97b2657e7bd1c52d2916
|
9ce9da5f21604310a997f0c41e9cd383f5e292c3
|
refs/heads/master
| 2023-03-20T02:27:03.321950
| 2018-10-04T10:06:38
| 2018-10-04T10:06:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,490
|
cpp
|
strategic_resource.cpp
|
/////////////////////////////////////////////////////////////////////////////
//
// Copyright 1997-1999 Pandemic Studios, Dark Reign II
//
// Strategic Resource
//
/////////////////////////////////////////////////////////////////////////////
//
// Includes
//
#include "strategic_private.h"
#include "strategic_resource.h"
#include "strategic_resource_manager.h"
#include "strategic_resource_decomposition.h"
#include "strategic_object.h"
#include "orders_game.h"
#include "resolver.h"
/////////////////////////////////////////////////////////////////////////////
//
// NameSpace Strategic
//
namespace Strategic
{
/////////////////////////////////////////////////////////////////////////////
//
// Class Resource
//
// Number of cycles between updates
const U32 updateInterval = 450;
//
// Constructor
//
Resource::Resource(Manager &manager, const ClusterGroup &clusterGroup, F32 proximity, U32 id)
: manager(manager),
id(id),
resource(clusterGroup.resource),
regen(clusterGroup.regen),
centre(clusterGroup.midAvg),
baseProximity(proximity),
updateCycle(GameTime::SimCycle() + updateInterval)
{
resources.AppendList(clusterGroup.resources);
for (List<MapCluster>::Iterator c(&clusterGroup.clusters); *c; ++c)
{
clusters.Append(*c);
}
// Register our construction
RegisterConstruction(dTrack);
}
//
// Constructor
//
Resource::Resource(Manager &manager, F32 proximity, U32 id)
: manager(manager),
id(id),
resource(0),
regen(0),
baseProximity(proximity),
updateCycle(GameTime::SimCycle() + updateInterval)
{
// Register our construction
RegisterConstruction(dTrack);
}
//
// Destructor
//
Resource::~Resource()
{
// Unlink all clusters
clusters.UnlinkAll();
// Clear on order types
onOrder.Clear();
// Clear units assigned
resourceStorers.Clear();
resourceTransports.Clear();
units.Clear();
// Clear resources
resources.Clear();
// Register our demise
RegisterDestruction(dTrack);
}
//
// SaveState
//
// Save state information
//
void Resource::SaveState(FScope *scope)
{
StdSave::TypeReaperList(scope, "Resources", resources);
StdSave::TypeU32(scope, "Resource", resource);
StdSave::TypeU32(scope, "Regen", regen);
StdSave::TypeReaperList(scope, "ResourceStorers", resourceStorers);
StdSave::TypeReaperList(scope, "ResourceTransports", resourceTransports);
StdSave::TypeReaperList(scope, "Units", units);
StdSave::TypeReaperListObjType(scope, "OnOrder", onOrder);
StdSave::TypeF32(scope, "BaseProximity", baseProximity);
StdSave::TypePoint(scope, "Centre", centre);
StdSave::TypeU32(scope, "UpdateCycle", updateCycle);
FScope *fScope = scope->AddFunction("Clusters");
for (List<MapCluster>::Iterator i(&clusters); *i; ++i)
{
FScope *sScope = fScope->AddFunction("Cluster");
sScope->AddArgInteger((*i)->xIndex);
sScope->AddArgInteger((*i)->zIndex);
}
}
//
// LoadState
//
// Load state information
//
void Resource::LoadState(FScope *scope)
{
FScope *sScope;
while ((sScope = scope->NextFunction()) != NULL)
{
switch (sScope->NameCrc())
{
case 0x8C34B766: // "Resources"
StdLoad::TypeReaperList(sScope, resources);
Resolver::ObjList<ResourceObj, ResourceObjType, ResourceObjListNode>(resources);
break;
case 0x4CD1BE27: // "Resource"
resource = StdLoad::TypeU32(sScope);
break;
case 0x192CADA5: // "Regen"
regen = StdLoad::TypeU32(sScope);
break;
case 0x41DB0A3A: // "ResourceStorers"
StdLoad::TypeReaperList(sScope, resourceStorers);
Resolver::ObjList<UnitObj, UnitObjType, UnitObjListNode>(resourceStorers);
break;
case 0x89777833: // "ResourceTransports"
StdLoad::TypeReaperList(sScope, resourceTransports);
Resolver::ObjList<UnitObj, UnitObjType, UnitObjListNode>(resourceTransports);
break;
case 0xCED02493: // "Units"
StdLoad::TypeReaperList(sScope, units);
Resolver::ObjList<UnitObj, UnitObjType, UnitObjListNode>(units);
break;
case 0x189FFF75: // "OnOrder"
StdLoad::TypeReaperListObjType(sScope, onOrder);
Resolver::TypeList<UnitObjType, UnitObjTypeListNode>(onOrder);
break;
case 0x511695C1: // "BaseProximity"
baseProximity = StdLoad::TypeF32(sScope);
break;
case 0x03633B25: // "Centre"
StdLoad::TypePoint(sScope, centre);
break;
case 0x87843E5F: // "UpdateCycle"
updateCycle = StdLoad::TypeU32(sScope);
break;
case 0x6ECAAA17: // "Clusters"
{
FScope *ssScope;
while ((ssScope = sScope->NextFunction()) != NULL)
{
switch (ssScope->NameCrc())
{
case 0xF5ACB747: // "Cluster"
{
// Get cluster location
U32 x = StdLoad::TypeU32(ssScope);
U32 z = StdLoad::TypeU32(ssScope);
// Get the cluster
clusters.Append(WorldCtrl::GetCluster(x, z));
break;
}
}
}
}
}
}
}
//
// Add on Order
//
void Resource::AddOnOrder(UnitObjType &type)
{
// On order types
onOrder.Append(&type);
}
//
// Remove on order
//
void Resource::RemoveOnOrder(UnitObjType &type)
{
// Find this type in the on order types
if (!onOrder.Remove(&type, TRUE))
{
ERR_FATAL(("Could not find type '%s' in the on order types", type.GetName()))
}
}
//
// Add unit
//
void Resource::AddUnit(UnitObj *unit)
{
ASSERT(unit)
// Is this unit a resource transporter ...
// If this unit is a resource transporter, order it to collect from our resources!
if (unit->UnitType()->GetResourceTransport())
{
// Add to the resource transporters
resourceTransports.Append(unit);
ResourceObj *resource = NULL;
U32 amount = 0;
resources.PurgeDead();
// Pick the most succulent resource we have
for (ResourceObjList::Iterator r(&resources); *r; ++r)
{
if ((**r)->GetResource() > amount)
{
resource = **r;
amount = resource->GetResource();
}
}
if (resource)
{
Orders::Game::ClearSelected::Generate(manager.GetObject());
Orders::Game::AddSelected::Generate(manager.GetObject(), unit);
Orders::Game::Collect::Generate(manager.GetObject(), resource->Id(), FALSE, Orders::FLUSH);
}
else
{
// The're no resource, this can happen but we
// expect this resource to be removed soon
}
}
else if (unit->HasProperty(0xAE95DF36)) // "Ability::StoreResource"
{
// Add to the resource storers
resourceStorers.Append(unit);
}
else
{
// Add to other units
units.Append(unit);
}
}
//
// Process
//
Bool Resource::Process()
{
// How long since we last processed ?
if (GameTime::SimCycle() > updateCycle)
{
updateCycle += updateInterval;
// Update the total quantity of resource at this site
resource = 0;
regen = 0;
for (ResourceObjList::Iterator r(&resources); *r; ++r)
{
if ((*r)->Alive())
{
resource += (**r)->GetResource();
regen += (**r)->ResourceType()->GetResourceRate();
}
}
// Is there zero resource ?
if (!resource && !regen)
{
// Recycle all of the refineries and all of the units
resourceStorers.PurgeDead();
units.PurgeDead();
if (resourceStorers.GetCount())
{
Orders::Game::ClearSelected::Generate(manager.GetObject());
for (UnitObjList::Iterator s(&resourceStorers); *s; ++s)
{
Orders::Game::AddSelected::Generate(manager.GetObject(), **s);
}
for (UnitObjList::Iterator u(&units); *u; ++u)
{
Orders::Game::AddSelected::Generate(manager.GetObject(), **u);
}
Orders::Game::Recycle::Generate(manager.GetObject());
}
return (TRUE);
}
else
{
// Check all of our resource transporters and make sure that
// we evenly distribute them to resource storage facilities
resourceTransports.PurgeDead();
resourceStorers.PurgeDead();
units.PurgeDead();
LOG_AI(("Performing transport assignment for resource"))
if (resourceStorers.GetCount() && resourceTransports.GetCount())
{
UnitObjList::Iterator s(&resourceStorers);
// Iterate the storers and assign transports
for (UnitObjList::Iterator t(&resourceTransports); *t; ++t)
{
LOG_AI(("Storer [%d] <- Transport [%d]", (*s)->Id(), (*t)->Id()))
Orders::Game::ClearSelected::Generate(manager.GetObject());
Orders::Game::AddSelected::Generate(manager.GetObject(), **t);
Orders::Game::Store::Generate(manager.GetObject(), (*s)->Id(), FALSE, TRUE, Orders::FLUSH);
if (!++s)
{
!s;
}
}
}
}
}
return (FALSE);
}
}
|
0beb33ffaa02fabe33a50aebcb30c9258d66a24c
|
d875107c7a919cacdf1f1cbf4efec4d2fa270fb8
|
/RayTracing/MyTracer/Tracer/Tracer.cpp
|
7b66a09448a726a534e6451ffd38c9d01b099993
|
[] |
no_license
|
terraritto/RayTracing
|
c2d451c4d53d093e383be7e755adcda07538d97e
|
d4a47772241fcec26c3662ef151934c7cfd0b1f9
|
refs/heads/master
| 2021-07-04T03:49:43.054692
| 2020-11-19T07:17:32
| 2020-11-19T07:17:32
| 200,249,837
| 0
| 0
| null | 2019-11-14T15:28:42
| 2019-08-02T14:34:58
|
C++
|
UTF-8
|
C++
| false
| false
| 386
|
cpp
|
Tracer.cpp
|
#include "Tracer.h"
Tracer::Tracer()
: mWorld(nullptr)
{
}
Tracer::Tracer(World* world)
: mWorld(world)
{
}
Tracer::~Tracer()
{
}
RGBColor Tracer::TraceRay(const Ray& ray) const
{
return black;
}
RGBColor Tracer::TraceRay(const Ray ray, const int depth) const
{
return black;
}
RGBColor Tracer::TraceRay(const Ray ray, float& tMin, const int depth) const
{
return black;
}
|
08a06bd9b75dafe06f00513a57e50868e22b66eb
|
82bba7a54b6c2832254b7c2c6c5753873116a316
|
/extension/src/stc.cpp
|
17f41c759c1d9a969ce178f259ce749150c45976
|
[
"MIT"
] |
permissive
|
Augustin-FL/wxExtension
|
213174f1c85e8973875721e83dde1f36cc611c8f
|
18b1931b7d90ff337977c48289a8bf38914a563a
|
refs/heads/master
| 2021-05-28T08:46:20.474642
| 2015-04-04T10:39:45
| 2015-04-04T10:39:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 54,356
|
cpp
|
stc.cpp
|
////////////////////////////////////////////////////////////////////////////////
// Name: stc.cpp
// Purpose: Implementation of class wxExSTC
// Author: Anton van Wezenbeek
// Copyright: (c) 2015 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/fdrepdlg.h> // for wxFindDialogEvent
#include <wx/numdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/stc.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/filename.h>
#include <wx/extension/frame.h>
#include <wx/extension/frd.h>
#include <wx/extension/hexmode.h>
#include <wx/extension/indicator.h>
#include <wx/extension/lexer.h>
#include <wx/extension/lexers.h>
#include <wx/extension/link.h>
#include <wx/extension/menu.h>
#include <wx/extension/printing.h>
#include <wx/extension/stcdlg.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
#include <wx/extension/vi.h>
#if wxUSE_GUI
enum
{
INDENT_NONE,
INDENT_WHITESPACE,
INDENT_LEVEL,
INDENT_ALL,
};
wxExConfigDialog* wxExSTC::m_ConfigDialog = NULL;
wxExSTCEntryDialog* wxExSTC::m_EntryDialog = NULL;
int wxExSTC::m_Zoom = -1;
wxExSTC::wxExSTC(wxWindow *parent,
const wxString& value,
long win_flags,
const wxString& title,
long menu_flags,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style)
: wxStyledTextCtrl(parent, id , pos, size, style, title)
, m_Flags(win_flags)
, m_MenuFlags(menu_flags)
, m_Goto(1)
, m_MarginDividerNumber(1)
, m_MarginFoldingNumber(2)
, m_MarginLineNumber(0)
, m_MarkerChange(1, -1)
, m_vi(wxExVi(this))
, m_File(this, title)
, m_Link(wxExLink(this))
, m_HexMode(wxExHexMode(this))
, m_Frame(dynamic_cast<wxExFrame*>(wxTheApp->GetTopWindow()))
{
Initialize(false);
PropertiesMessage();
if (!value.empty())
{
if (HexMode())
{
m_HexMode.AppendText(value.c_str());
}
else
{
SetText(value);
}
GuessType();
}
if (m_Flags & STC_WIN_READ_ONLY)
{
SetReadOnly(true);
}
}
wxExSTC::wxExSTC(wxWindow* parent,
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags,
long menu_flags,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style)
: wxStyledTextCtrl(parent, id, pos, size, style)
, m_File(this)
, m_Goto(1)
, m_MarginDividerNumber(1)
, m_MarginFoldingNumber(2)
, m_MarginLineNumber(0)
, m_MarkerChange(1, -1)
, m_Flags(flags)
, m_MenuFlags(menu_flags)
, m_vi(wxExVi(this))
, m_Link(wxExLink(this))
, m_HexMode(wxExHexMode(this))
, m_Frame(dynamic_cast<wxExFrame*>(wxTheApp->GetTopWindow()))
{
Initialize(filename.GetStat().IsOk());
if (filename.GetStat().IsOk())
{
Open(filename, line_number, match, col_number, flags);
}
}
wxExSTC::wxExSTC(const wxExSTC& stc)
: wxStyledTextCtrl(stc.GetParent(),
wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, stc.GetName())
, m_Flags(stc.m_Flags)
, m_Goto(stc.m_Goto)
, m_MenuFlags(stc.m_MenuFlags)
, m_MarginDividerNumber(stc.m_MarginDividerNumber)
, m_MarginFoldingNumber(stc.m_MarginFoldingNumber)
, m_MarginLineNumber(stc.m_MarginLineNumber)
, m_MarkerChange(stc.m_MarkerChange)
, m_Lexer(stc.m_Lexer)
, m_Link(wxExLink(this))
, m_File(this, stc.GetFileName().GetFullPath())
, m_vi(wxExVi(this)) // do not use stc.m_vi, crash
, m_DefaultFont(stc.m_DefaultFont)
, m_AutoComplete(stc.m_AutoComplete)
, m_Frame(stc.m_Frame)
, m_HexMode(wxExHexMode(this))
{
Initialize(stc.GetFileName().GetStat().IsOk());
if (stc.GetFileName().GetStat().IsOk())
{
Open(stc.GetFileName(), -1, wxEmptyString, 0, GetFlags());
DocumentStart();
}
else
{
SetLexer(m_Lexer, true);
SetEdgeMode(stc.GetEdgeMode());
}
}
bool wxExSTC::AutoIndentation(int c)
{
const long ai = wxConfigBase::Get()->ReadLong(_("Auto indent"), INDENT_ALL);
if (ai == INDENT_NONE)
{
return false;
}
bool is_nl = false;
switch (GetEOLMode())
{
case wxSTC_EOL_CR: is_nl = (c == '\r'); break;
case wxSTC_EOL_CRLF: is_nl = (c == '\n'); break; // so ignore first \r
case wxSTC_EOL_LF: is_nl = (c == '\n'); break;
}
const int currentLine = GetCurrentLine();
if (!is_nl || currentLine == 0)
{
return false;
}
const int level =
(GetFoldLevel(currentLine) & wxSTC_FOLDLEVELNUMBERMASK)
- wxSTC_FOLDLEVELBASE;
int indent = 0;
if (level <= 0 || ai == INDENT_WHITESPACE)
{
// the current line has yet no indents, so use previous line
indent = GetLineIndentation(currentLine - 1);
if (indent == 0)
{
return false;
}
}
else
{
indent = GetIndent() * level;
}
BeginUndoAction();
SetLineIndentation(currentLine, indent);
if (level < m_FoldLevel && m_AddingChars)
{
SetLineIndentation(currentLine - 1, indent);
}
EndUndoAction();
m_FoldLevel = level;
GotoPos(GetLineIndentPosition(currentLine));
return true;
}
void wxExSTC::BuildPopupMenu(wxExMenu& menu)
{
const wxString sel = GetSelectedText();
if (GetCurrentLine() == 0 && wxExLexers::Get()->GetCount() > 0)
{
menu.Append(ID_EDIT_SHOW_PROPERTIES, _("Properties"));
}
if (m_MenuFlags & STC_MENU_OPEN_LINK)
{
wxString filename;
if (LinkOpen(&filename))
{
menu.AppendSeparator();
menu.Append(ID_EDIT_OPEN_LINK, _("Open") + " " + filename);
}
}
if (m_MenuFlags & STC_MENU_VCS)
{
if (GetFileName().FileExists() && sel.empty())
{
if (wxExVCS::DirExists(GetFileName()))
{
menu.AppendSeparator();
menu.AppendVCS(GetFileName());
}
}
}
if (( sel.empty() && m_Lexer.GetScintillaLexer() == "hypertext") ||
(!sel.empty() && (sel.StartsWith("http") || sel.StartsWith("www."))))
{
menu.AppendSeparator();
menu.Append(ID_EDIT_OPEN_BROWSER, _("&Open In Browser"));
}
if (!m_vi.GetIsActive() && GetTextLength() > 0)
{
menu.AppendSeparator();
menu.Append(wxID_FIND);
if (!GetReadOnly())
{
menu.Append(wxID_REPLACE);
}
}
menu.AppendSeparator();
menu.AppendEdit();
if (!GetReadOnly())
{
if (!sel.empty())
{
wxExMenu* menuSelection = new wxExMenu(menu);
menuSelection->Append(ID_EDIT_UPPERCASE, _("&Uppercase\tF11"));
menuSelection->Append(ID_EDIT_LOWERCASE, _("&Lowercase\tF12"));
if (wxExGetNumberOfLines(sel) > 1)
{
wxExMenu* menuSort = new wxExMenu(menu);
menuSort->Append(wxID_SORT_ASCENDING);
menuSort->Append(wxID_SORT_DESCENDING);
menuSelection->AppendSeparator();
menuSelection->AppendSubMenu(menuSort, _("&Sort"));
}
menu.AppendSeparator();
menu.AppendSubMenu(menuSelection, _("&Selection"));
}
}
if (!GetReadOnly() && (CanUndo() || CanRedo()))
{
menu.AppendSeparator();
if (CanUndo()) menu.Append(wxID_UNDO);
if (CanRedo()) menu.Append(wxID_REDO);
}
// Folding if nothing selected, property is set,
// and we have a lexer.
if (
sel.empty() &&
GetProperty("fold") == "1" &&
m_Lexer.IsOk() &&
!m_Lexer.GetScintillaLexer().empty())
{
menu.AppendSeparator();
menu.Append(ID_EDIT_TOGGLE_FOLD, _("&Toggle Fold\tCtrl+T"));
menu.Append(ID_EDIT_FOLD_ALL, _("&Fold All Lines\tF9"));
menu.Append(ID_EDIT_UNFOLD_ALL, _("&Unfold All Lines\tF10"));
}
}
bool wxExSTC::CanCut() const
{
return wxStyledTextCtrl::CanCut() && !GetReadOnly() && !HexMode();
}
bool wxExSTC::CanPaste() const
{
return wxStyledTextCtrl::CanPaste() && !GetReadOnly() && !HexMode();
}
void wxExSTC::CheckAutoComp(const wxUniChar& c)
{
if (!m_UseAutoComplete ||
!wxConfigBase::Get()->ReadBool(_("Auto complete"), true))
{
return;
}
if (wxExIsCodewordSeparator(GetCharAt(GetCurrentPos() - 1)))
{
m_AutoComplete = c;
}
else
{
m_AutoComplete += c;
if (m_AutoComplete.length() > 3) // Only autocompletion for large words
{
if (!AutoCompActive())
{
AutoCompSetIgnoreCase(true);
AutoCompSetAutoHide(false);
}
if (m_Lexer.KeywordStartsWith(m_AutoComplete))
{
const wxString comp(
m_Lexer.GetKeywordsString(-1, 5, m_AutoComplete));
if (!comp.empty())
{
AutoCompShow(m_AutoComplete.length() - 1, comp);
}
}
else
AutoCompCancel();
}
}
}
void wxExSTC::CheckBrace()
{
if (HexMode())
{
m_HexMode.HighlightOther();
}
else if (!CheckBrace(GetCurrentPos()))
{
CheckBrace(GetCurrentPos() - 1);
}
}
bool wxExSTC::CheckBrace(int pos)
{
const int brace_match = BraceMatch(pos);
if (brace_match != wxSTC_INVALID_POSITION)
{
BraceHighlight(pos, brace_match);
return true;
}
else
{
BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
return false;
}
}
void wxExSTC::Clear()
{
if (m_vi.GetIsActive() && GetSelectedText().empty())
{
m_vi.Command(std::string(1, WXK_DELETE));
}
else
{
wxStyledTextCtrl::Clear();
}
}
void wxExSTC::ClearDocument(bool set_savepoint)
{
SetReadOnly(false);
ClearAll();
if (set_savepoint)
{
EmptyUndoBuffer();
SetSavePoint();
}
}
// This is a static method, cannot use normal members here.
int wxExSTC::ConfigDialog(
wxWindow* parent,
const wxString& title,
long flags,
wxWindowID id)
{
wxConfigBase* cfg = wxConfigBase::Get();
if (!cfg->Exists(_("Caret line")))
{
cfg->SetRecordDefaults(true);
}
const std::vector<wxExConfigItem> items{
// General page.
// use 3 cols here, but 1 for others on this page
wxExConfigItem(std::set<wxString> {
_("End of line"),
_("Line numbers"),
_("Use tabs"),
_("Caret line"),
_("Scroll bars"),
_("Auto complete"),
_("vi mode")}, _("General") + ":3"),
wxExConfigItem(_("Auto indent"), std::map<long, const wxString> {
std::make_pair(INDENT_NONE, _("None")),
std::make_pair(INDENT_WHITESPACE, _("Whitespace")),
std::make_pair(INDENT_LEVEL, _("Level")),
std::make_pair(INDENT_ALL, _("Both"))}, true, _("General"), 1),
wxExConfigItem(_("Wrap visual flags"), std::map<long, const wxString> {
std::make_pair(wxSTC_WRAPVISUALFLAG_NONE, _("None")),
std::make_pair(wxSTC_WRAPVISUALFLAG_END, _("End")),
std::make_pair(wxSTC_WRAPVISUALFLAG_START, _("Start")),
std::make_pair(wxSTC_WRAPVISUALFLAG_MARGIN, _("Margin"))}, true, _("General"), 1),
(wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Default font"), CONFIG_FONTPICKERCTRL): wxExConfigItem()),
wxExConfigItem(_("Whitespace"), std::map<long, const wxString> {
std::make_pair(wxSTC_WS_INVISIBLE, _("Invisible")),
std::make_pair(wxSTC_WS_VISIBLEAFTERINDENT, _("Visible after indent")),
std::make_pair(wxSTC_WS_VISIBLEALWAYS, _("Visible always"))}, true, _("General"), 1),
wxExConfigItem(_("Wrap line"), std::map<long, const wxString> {
std::make_pair(wxSTC_WRAP_NONE, _("None")),
std::make_pair(wxSTC_WRAP_WORD, _("Word")),
std::make_pair(wxSTC_WRAP_CHAR, _("Char"))
#if wxCHECK_VERSION(3,1,0)
,std::make_pair(wxSTC_WRAP_WHITESPACE, _("Whitespace"))}
#else
}
#endif
,true, _("General"), 1),
// Edge page.
wxExConfigItem(_("Edge column"), 0, 500, _("Edge")),
wxExConfigItem( _("Edge line"), std::map<long, const wxString> {
std::make_pair(wxSTC_EDGE_NONE, _("None")),
std::make_pair(wxSTC_EDGE_LINE, _("Line")),
std::make_pair(wxSTC_EDGE_BACKGROUND, _("Background"))}, true, _("Edge"), 1),
// Margin page.
wxExConfigItem(_("Tab width"), 1, cfg->ReadLong(_("Edge column"), 80), _("Margin")),
wxExConfigItem(_("Indent"), 0, cfg->ReadLong(_("Edge column"), 80), _("Margin")),
wxExConfigItem(_("Divider"), 0, 40, _("Margin")),
(wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Folding"), 0, 40, _("Margin")): wxExConfigItem()),
wxExConfigItem(_("Line number"), 0, 100, _("Margin")),
// Folding page.
(wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Indentation guide"), CONFIG_CHECKBOX, _("Folding")): wxExConfigItem()),
(wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Auto fold"), 0, INT_MAX, _("Folding")): wxExConfigItem()),
// next is experimental, wait for scintilla
//fchoices.insert(std::make_pair(wxSTC_FOLDFLAG_LEVELNUMBERS, _("Level numbers")));
(wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Fold flags"), std::map<long, const wxString> {
std::make_pair(wxSTC_FOLDFLAG_LINEBEFORE_EXPANDED, _("Line before expanded")),
std::make_pair(wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED, _("Line before contracted")),
std::make_pair(wxSTC_FOLDFLAG_LINEAFTER_EXPANDED, _("Line after expanded")),
std::make_pair(wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED, _("Line after contracted"))}, false,_("Folding")): wxExConfigItem()),
// Printer page
(!(flags & STC_CONFIG_SIMPLE) ? wxExConfigItem(_("Print flags"), std::map<long, const wxString> {
std::make_pair(wxSTC_PRINT_NORMAL, _("Normal")),
std::make_pair(wxSTC_PRINT_INVERTLIGHT, _("Invert on white")),
std::make_pair(wxSTC_PRINT_BLACKONWHITE, _("Black on white")),
std::make_pair(wxSTC_PRINT_COLOURONWHITE, _("Colour on white")),
std::make_pair(wxSTC_PRINT_COLOURONWHITEDEFAULTBG, _("Colour on white normal"))}, true, _("Printer"), 1): wxExConfigItem()),
// Directory page.
(!(flags & STC_CONFIG_SIMPLE) && wxExLexers::Get()->GetCount() > 0 ? wxExConfigItem(_("Include directory"), CONFIG_LISTVIEW_FOLDER, _("Directory"), false, wxID_ANY, 25, false): wxExConfigItem())};
if (cfg->IsRecordingDefaults())
{
// Set defaults only.
cfg->ReadLong(_("Auto fold"), 1500);
cfg->ReadLong(_("Auto indent"), INDENT_WHITESPACE);
cfg->ReadLong(_("Folding"), 16);
cfg->ReadBool(_("Scroll bars"), true);
cfg->ReadLong(_("Edge column"), 80);
cfg->SetRecordDefaults(false);
}
int buttons = wxOK | wxCANCEL;
if (flags & STC_CONFIG_WITH_APPLY)
{
buttons |= wxAPPLY;
}
const int style = wxExConfigDialog::CONFIG_NOTEBOOK;
if (!(flags & STC_CONFIG_MODELESS))
{
return wxExConfigDialog(
parent, items, title, 0, 1, buttons, id, style).ShowModal();
}
else
{
if (m_ConfigDialog == NULL)
{
m_ConfigDialog = new wxExConfigDialog(
parent, items, title, 0, 1, buttons, id, style);
}
return m_ConfigDialog->Show();
}
}
void wxExSTC::ConfigGet(bool init)
{
wxConfigBase* cfg = wxConfigBase::Get();
if (!cfg->Exists(_("Caret line")))
{
cfg->SetRecordDefaults(true);
}
const wxFont font(cfg->ReadObject(
_("Default font"), wxSystemSettings::GetFont(wxSYS_ANSI_FIXED_FONT)));
if (m_DefaultFont != font)
{
m_DefaultFont = font;
StyleResetDefault();
// Doing this once is enough, not yet possible.
wxExLexers::Get()->LoadDocument();
SetLexer(m_Lexer);
}
if (GetFileName().GetExt().CmpNoCase("log") == 0)
{
SetEdgeMode(wxSTC_EDGE_NONE);
}
else
{
SetEdgeColumn(cfg->ReadLong(_("Edge column"), 80));
SetEdgeMode(cfg->ReadLong(_("Edge line"), wxSTC_EDGE_NONE));
}
SetUseHorizontalScrollBar(cfg->ReadBool(_("Scroll bars"), true));
SetUseVerticalScrollBar(cfg->ReadBool(_("Scroll bars"), true));
SetPrintColourMode(cfg->ReadLong(_("Print flags"), wxSTC_PRINT_BLACKONWHITE));
SetCaretLineVisible(cfg->ReadBool(_("Caret line"), true));
SetFoldFlags(cfg->ReadLong( _("Fold flags"),
wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED | wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED));
const long def_tab_width = 2;
SetIndent(cfg->ReadLong(_("Indent"), def_tab_width));
SetIndentationGuides( cfg->ReadBool(_("Indentation guide"), false));
SetMarginWidth(m_MarginDividerNumber, cfg->ReadLong(_("Divider"), 16));
if (init)
{
Fold();
}
ShowLineNumbers(cfg->ReadBool(_("Line numbers"), false));
SetTabWidth(cfg->ReadLong(_("Tab width"), def_tab_width));
SetUseTabs(cfg->ReadBool(_("Use tabs"), false));
SetViewEOL(cfg->ReadBool(_("End of line"), false));
SetViewWhiteSpace(cfg->ReadLong(_("Whitespace"), wxSTC_WS_INVISIBLE));
SetWrapMode(cfg->ReadLong(_("Wrap line"), wxSTC_WRAP_NONE));
SetWrapVisualFlags(cfg->ReadLong(_("Wrap visual flags"), wxSTC_WRAPVISUALFLAG_END));
// Here the default vi mode is set, and used if the application
// is run for the first time.
m_vi.Use(cfg->ReadBool(_("vi mode"), false));
m_Link.SetFromConfig();
if (cfg->IsRecordingDefaults())
{
// Set defaults only.
cfg->ReadLong(_("Auto fold"), 1500);
cfg->ReadLong(_("Auto indent"), INDENT_WHITESPACE);
cfg->ReadLong(_("Folding"), 16);
cfg->ReadBool(_("Scroll bars"), true);
cfg->SetRecordDefaults(false);
}
}
void wxExSTC::ControlCharDialog(const wxString& caption)
{
if (GetSelectedText().length() > 2)
{
// Do nothing
return;
}
if (HexMode())
{
return m_HexMode.ControlCharDialog(caption);
}
if (GetReadOnly())
{
if (GetSelectedText().length() == 1)
{
const wxUniChar value = GetSelectedText().GetChar(0);
wxMessageBox(
wxString::Format("hex: %x dec: %d", value, value),
_("Control Character"));
}
return;
}
static int value = ' '; // don't use 0 as default as NULL is not handled
if (GetSelectedText().length() == 1)
{
value = GetSelectedText().GetChar(0);
}
int new_value;
if ((new_value = (int)wxGetNumberFromUser(_("Input") + " 0 - 255:",
wxEmptyString,
caption,
value,
0,
255,
this)) < 0)
{
return;
}
if (GetSelectedText().length() == 1)
{
if (value != new_value)
{
ReplaceSelection(wxString::Format("%c", (wxUniChar)new_value));
}
SetSelection(GetCurrentPos(), GetCurrentPos() + 1);
}
else
{
char buffer[2];
buffer[0] = (char)new_value;
buffer[1] = 0;
if (m_vi.GetIsActive())
{
m_vi.Command(std::string(buffer, 1));
}
else
{
AddTextRaw(buffer, 1);
}
ProcessChar(new_value);
}
value = new_value;
}
void wxExSTC::Copy()
{
if (CanCopy())
{
wxStyledTextCtrl::Copy();
}
}
void wxExSTC::Cut()
{
if (CanCut())
{
if (m_vi.GetIsActive())
{
const wxCharBuffer b(GetSelectedTextRaw());
m_vi.SetRegistersDelete(std::string(b.data(), b.length() - 1));
m_vi.SetRegisterYank(std::string(b.data(), b.length() - 1));
}
wxStyledTextCtrl::Cut();
}
}
bool wxExSTC::FileReadOnlyAttributeChanged()
{
SetReadOnly(!GetFileName().IsFileWritable()); // does not return anything
wxLogStatus(_("Readonly attribute changed"));
return true;
}
void wxExSTC::FileTypeMenu()
{
wxMenu* menu = new wxMenu();
// The order here should be the same as the defines for wxSTC_EOL_CRLF.
// So the FindItemByPosition can work
menu->AppendRadioItem(ID_EDIT_EOL_DOS, "&DOS");
menu->AppendRadioItem(ID_EDIT_EOL_MAC, "&MAC");
menu->AppendRadioItem(ID_EDIT_EOL_UNIX, "&UNIX");
menu->AppendSeparator();
wxMenuItem* hex = menu->AppendCheckItem(ID_EDIT_HEX, "&HEX");
menu->FindItemByPosition(GetEOLMode())->Check();
if (HexMode())
{
hex->Check();
}
PopupMenu(menu);
delete menu;
}
bool wxExSTC::FindNext(bool find_next)
{
return FindNext(
GetFindString(),
-1,
find_next);
}
bool wxExSTC::FindNext(
const wxString& text,
int find_flags,
bool find_next)
{
if (text.empty())
{
return false;
}
static bool recursive = false;
static int start_pos, end_pos;
if (find_next)
{
if (recursive) start_pos = 0;
else
{
start_pos = GetCurrentPos();
end_pos = GetTextLength();
}
}
else
{
if (recursive) start_pos = GetTextLength();
else
{
start_pos = GetCurrentPos();
if (GetSelectionStart() != -1)
start_pos = GetSelectionStart();
end_pos = 0;
}
}
SetTargetStart(start_pos);
SetTargetEnd(end_pos);
SetSearchFlags(find_flags);
if (SearchInTarget(text) == -1)
{
wxExFrame::StatusText(
wxExGetFindResult(text, find_next, recursive), wxEmptyString);
bool found = false;
if (!recursive)
{
recursive = true;
found = FindNext(text, GetSearchFlags(), find_next);
recursive = false;
}
return found;
}
else
{
if (!recursive)
{
wxLogStatus(wxEmptyString);
}
recursive = false;
switch (m_vi.GetMode())
{
case wxExVi::MODE_NORMAL:
SetSelection(GetTargetStart(), GetTargetEnd());
break;
case wxExVi::MODE_VISUAL:
SetSelection(GetSelectionStart(), GetTargetEnd());
break;
case wxExVi::MODE_VISUAL_LINE:
SetSelection(
PositionFromLine(LineFromPosition(GetSelectionStart())),
PositionFromLine(LineFromPosition(GetTargetEnd()) + 1));
break;
case wxExVi::MODE_VISUAL_RECT:
while (GetCurrentPos() < GetTargetEnd())
{
CharRightRectExtend();
}
break;
}
EnsureVisible(LineFromPosition(GetTargetStart()));
EnsureCaretVisible();
return true;
}
}
void wxExSTC::Fold(bool foldall)
{
if (
GetProperty("fold") == "1" &&
m_Lexer.IsOk() &&
!m_Lexer.GetScintillaLexer().empty())
{
SetMarginWidth(m_MarginFoldingNumber,
wxConfigBase::Get()->ReadLong(_("Folding"), 16));
SetFoldFlags(
wxConfigBase::Get()->ReadLong(_("Fold flags"),
wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED |
wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED));
if (
foldall ||
GetLineCount() > wxConfigBase::Get()->ReadLong(_("Auto fold"), 1500))
{
FoldAll();
}
}
else
{
SetMarginWidth(m_MarginFoldingNumber, 0);
}
}
void wxExSTC::FoldAll()
{
if (GetProperty("fold") != "1") return;
const int current_line = GetCurrentLine();
const bool xml = (m_Lexer.GetLanguage() == "xml");
int line = 0;
while (line < GetLineCount())
{
const int level = GetFoldLevel(line);
const int last_child_line = GetLastChild(line, level);
if (xml && (
level == wxSTC_FOLDLEVELBASE + wxSTC_FOLDLEVELHEADERFLAG))
{
line++;
}
else if (last_child_line > line + 1)
{
if (GetFoldExpanded(line)) ToggleFold(line);
line = last_child_line + 1;
}
else
{
line++;
}
}
GotoLine(current_line);
}
const wxString wxExSTC::GetEOL() const
{
switch (GetEOLMode())
{
case wxSTC_EOL_CR: return "\r"; break;
case wxSTC_EOL_CRLF: return "\r\n"; break;
case wxSTC_EOL_LF: return "\n"; break;
default: wxFAIL; break;
}
return "\r\n";
}
// Cannot be const because of GetSelectedText (not const in 2.9.4).
const wxString wxExSTC::GetFindString()
{
const wxString selection = GetSelectedText();
if (!selection.empty() && wxExGetNumberOfLines(selection) == 1)
{
bool alnum = true;
// If regexp is true, then only use selected text if text does not
// contain special regexp characters.
if (GetSearchFlags() & wxSTC_FIND_REGEXP)
{
for (size_t i = 0; i < selection.size() && alnum; i++)
{
if (
!isalnum(selection[i]) &&
selection[i] != ' ' &&
selection[i] != '.' &&
selection[i] != '-' &&
selection[i] != '_')
{
alnum = false;
}
}
}
if (alnum)
{
wxExFindReplaceData::Get()->SetFindString(selection);
}
}
return wxExFindReplaceData::Get()->GetFindString();
}
const wxString wxExSTC::GetWordAtPos(int pos) const
{
const int word_start =
const_cast< wxExSTC * >( this )->WordStartPosition(pos, true);
const int word_end =
const_cast< wxExSTC * >( this )->WordEndPosition(pos, true);
if (word_start == word_end && word_start < GetTextLength())
{
const wxString word =
const_cast< wxExSTC * >( this )->GetTextRange(word_start, word_start + 1);
if (!isspace(word[0]))
{
return word;
}
else
{
return wxEmptyString;
}
}
else
{
const wxString word =
const_cast< wxExSTC * >( this )->GetTextRange(word_start, word_end);
return word;
}
}
bool wxExSTC::GotoDialog()
{
if (HexMode())
{
m_HexMode.GotoDialog();
}
else
{
if (m_Goto > GetLineCount())
{
m_Goto = GetLineCount();
}
else if (m_Goto < 1)
{
m_Goto = 1;
}
long val;
if ((val = wxGetNumberFromUser(
_("Input") + wxString::Format(" 1 - %d:", GetLineCount()),
wxEmptyString,
_("Enter Line Number"),
m_Goto, // initial value
1,
GetLineCount(),
this)) < 0)
{
return false;
}
GotoLineAndSelect(val);
}
return true;
}
void wxExSTC::GotoLineAndSelect(
int line_number,
const wxString& text,
int col_number)
{
// line_number and m_Goto start with 1 and is allowed to be
// equal to number of lines.
// Internally GotoLine starts with 0, therefore
// line_number - 1 is used afterwards.
if (line_number > GetLineCount())
{
line_number = GetLineCount();
}
else if (line_number <= 0)
{
line_number = 1;
}
GotoLine(line_number - 1);
EnsureVisible(line_number - 1);
EnsureCaretVisible();
m_Goto = line_number;
if (!text.empty())
{
const int start_pos = PositionFromLine(line_number - 1);
const int end_pos = GetLineEndPosition(line_number - 1);
SetSearchFlags(-1);
SetTargetStart(start_pos);
SetTargetEnd(end_pos);
if (SearchInTarget(text) != -1)
{
SetSelection(GetTargetStart(), GetTargetEnd());
}
}
else if (col_number > 0)
{
const int max = GetLineEndPosition(line_number - 1);
const int asked = GetCurrentPos() + col_number - 1;
SetCurrentPos(asked < max ? asked: max);
// Reset selection, seems necessary.
SelectNone();
}
}
void wxExSTC::GuessType()
{
// Get a small sample from this document to detect the file mode.
const int length = (!HexMode() ? GetTextLength(): m_HexMode.GetBuffer().size());
const int sample_size = (length > 255 ? 255: length);
const wxString text = (!HexMode() ? GetTextRange(0, sample_size):
m_HexMode.GetBuffer().Mid(0, sample_size));
std::vector<wxString> v;
// If we have a modeline comment.
if (
m_vi.GetIsActive() &&
wxExMatch("vi: *(set [a-z0-9:=! ]+)", text.ToStdString(), v) > 0)
{
if (!m_vi.Command(wxString(":" + v[0]).ToStdString()))
{
wxLogStatus("Could not apply vi settings");
}
}
if (text.Contains("\r\n")) SetEOLMode(wxSTC_EOL_CRLF);
else if (text.Contains("\n")) SetEOLMode(wxSTC_EOL_LF);
else if (text.Contains("\r")) SetEOLMode(wxSTC_EOL_CR);
else return; // do nothing
#if wxUSE_STATUSBAR
wxExFrame::UpdateStatusBar(this, "PaneFileType");
#endif
}
void wxExSTC::HexDecCalltip(int pos)
{
if (CallTipActive())
{
CallTipCancel();
}
if (HexMode())
{
CallTipShow(pos, wxExHexModeLine(&m_HexMode).GetInfo());
return;
}
wxString word;
if (!GetSelectedText().empty())
{
word = GetSelectedText();
}
else
{
word = GetWordAtPos(pos);
}
if (word.empty()) return;
const wxUniChar c = word.GetChar(0);
if (c < 32 || c > 125)
{
const wxString text(wxString::Format("hex: %x dec: %d", c, c));
CallTipShow(pos, text);
wxExClipboardAdd(text);
return;
}
long base10_val, base16_val;
const bool base10_ok = word.ToLong(&base10_val);
const bool base16_ok = word.ToLong(&base16_val, 16);
if (base10_ok || base16_ok)
{
wxString text;
if ( base10_ok && !base16_ok)
text = wxString::Format("hex: %lx", base10_val);
else if (!base10_ok && base16_ok)
text = wxString::Format("dec: %ld", base16_val);
else if ( base10_ok && base16_ok)
text = wxString::Format("hex: %lx dec: %ld", base10_val, base16_val);
CallTipShow(pos, text);
wxExClipboardAdd(text);
}
}
void wxExSTC::Initialize(bool file_exists)
{
Sync();
if (m_Flags & STC_WIN_HEX)
{
m_HexMode.Set(true);
}
m_AddingChars = false;
m_AllowChangeIndicator = !(m_Flags & STC_WIN_NO_INDICATOR);
m_UseAutoComplete = true;
m_FoldLevel = 0;
m_SavedPos = -1;
m_SavedSelectionStart = -1;
m_SavedSelectionEnd = -1;
if (wxExLexers::Get()->GetCount() > 0)
{
m_DefaultFont = wxConfigBase::Get()->ReadObject(
_("Default font"), wxSystemSettings::GetFont(wxSYS_ANSI_FIXED_FONT));
}
#ifdef __WXMSW__
SetEOLMode(wxSTC_EOL_CRLF);
#elif __WXGTK__
SetEOLMode(wxSTC_EOL_LF);
#else
SetEOLMode(wxSTC_EOL_CR);
#endif
SetAdditionalCaretsBlink(true);
SetAdditionalCaretsVisible(true);
SetAdditionalSelectionTyping(true);
SetBackSpaceUnIndents(true);
SetMouseDwellTime(1000);
SetMarginType(m_MarginLineNumber, wxSTC_MARGIN_NUMBER);
SetMarginType(m_MarginDividerNumber, wxSTC_MARGIN_SYMBOL);
SetMarginType(m_MarginFoldingNumber, wxSTC_MARGIN_SYMBOL);
SetMarginMask(m_MarginFoldingNumber, wxSTC_MASK_FOLDERS);
SetMarginSensitive(m_MarginFoldingNumber, true);
if (m_Zoom == -1)
{
m_Zoom = GetZoom();
}
else
{
SetZoom(m_Zoom);
}
UsePopUp(false); // we have our own
const int accels = 20; // take max number of entries
wxAcceleratorEntry entries[accels];
int i = 0;
entries[i++].Set(wxACCEL_CTRL, (int)'Z', wxID_UNDO);
entries[i++].Set(wxACCEL_CTRL, (int)'Y', wxID_REDO);
entries[i++].Set(wxACCEL_CTRL, (int)'D', ID_EDIT_HEX_DEC_CALLTIP);
entries[i++].Set(wxACCEL_CTRL, (int)'K', ID_EDIT_CONTROL_CHAR);
entries[i++].Set(wxACCEL_CTRL, '=', ID_EDIT_ZOOM_IN);
entries[i++].Set(wxACCEL_CTRL, '-', ID_EDIT_ZOOM_OUT);
entries[i++].Set(wxACCEL_CTRL, '9', ID_EDIT_MARKER_NEXT);
entries[i++].Set(wxACCEL_CTRL, '0', ID_EDIT_MARKER_PREVIOUS);
entries[i++].Set(wxACCEL_CTRL, WXK_INSERT, wxID_COPY);
entries[i++].Set(wxACCEL_NORMAL, WXK_F3, ID_EDIT_FIND_NEXT);
entries[i++].Set(wxACCEL_NORMAL, WXK_F4, ID_EDIT_FIND_PREVIOUS);
entries[i++].Set(wxACCEL_NORMAL, WXK_F7, wxID_SORT_ASCENDING);
entries[i++].Set(wxACCEL_NORMAL, WXK_F8, wxID_SORT_DESCENDING);
entries[i++].Set(wxACCEL_NORMAL, WXK_F9, ID_EDIT_FOLD_ALL);
entries[i++].Set(wxACCEL_NORMAL, WXK_F10, ID_EDIT_UNFOLD_ALL);
entries[i++].Set(wxACCEL_NORMAL, WXK_F11, ID_EDIT_UPPERCASE);
entries[i++].Set(wxACCEL_NORMAL, WXK_F12, ID_EDIT_LOWERCASE);
entries[i++].Set(wxACCEL_NORMAL, WXK_DELETE, wxID_DELETE);
entries[i++].Set(wxACCEL_SHIFT, WXK_INSERT, wxID_PASTE);
entries[i++].Set(wxACCEL_SHIFT, WXK_DELETE, wxID_CUT);
wxAcceleratorTable accel(i, entries);
SetAcceleratorTable(accel);
// Prevent doing this double, see wxExLexer::Apply.
if (!file_exists)
{
wxExLexers::Get()->ApplyGlobalStyles(this);
}
ConfigGet(true);
Bind(wxEVT_KEY_DOWN, [=](wxKeyEvent& event) {
if (event.GetModifiers() != wxMOD_ALT)
{
if (HexMode())
{
if (
event.GetKeyCode() == WXK_LEFT ||
event.GetKeyCode() == WXK_RIGHT)
{
wxExHexModeLine(&m_HexMode).SetPos(event);
}
}
if (m_vi.OnKeyDown(event))
{
event.Skip();
}}});
Bind(wxEVT_KEY_UP, [=](wxKeyEvent& event) {
event.Skip();
CheckBrace();
m_FoldLevel =
(GetFoldLevel(GetCurrentLine()) & wxSTC_FOLDLEVELNUMBERMASK)
- wxSTC_FOLDLEVELBASE;});
Bind(wxEVT_LEFT_UP, [=](wxMouseEvent& event) {
PropertiesMessage();
event.Skip();
CheckBrace();
m_AddingChars = false;
m_FoldLevel =
(GetFoldLevel(GetCurrentLine()) & wxSTC_FOLDLEVELNUMBERMASK)
- wxSTC_FOLDLEVELBASE;});
if (m_MenuFlags != STC_MENU_NONE)
{
Bind(wxEVT_RIGHT_UP, [=](wxMouseEvent& event) {
int style = 0; // otherwise CAN_PASTE already on
if ( GetReadOnly() || HexMode()) style |= wxExMenu::MENU_IS_READ_ONLY;
if (!GetSelectedText().empty()) style |= wxExMenu::MENU_IS_SELECTED;
if ( GetTextLength() == 0) style |= wxExMenu::MENU_IS_EMPTY;
if ( CanPaste()) style |= wxExMenu::MENU_CAN_PASTE;
wxExMenu menu(style);
BuildPopupMenu(menu);
if (menu.GetMenuItemCount() > 0)
{
// If last item is a separator, delete it.
wxMenuItem* item = menu.FindItemByPosition(menu.GetMenuItemCount() - 1);
if (item->IsSeparator())
{
menu.Delete(item->GetId());
}
PopupMenu(&menu);
}});
}
Bind(wxEVT_STC_AUTOCOMP_SELECTION, [=](wxStyledTextEvent& event) {
if (m_vi.GetIsActive())
{
const std::string command(wxString(
event.GetText().Mid(m_AutoComplete.size())).ToStdString());
if (!command.empty() && !m_vi.Command(command))
{
wxLogStatus("Autocomplete failed");
}
}});
Bind(wxEVT_STC_CHARADDED, [=](wxStyledTextEvent& event) {
event.Skip();
AutoIndentation(event.GetKey());});
#if wxUSE_DRAG_AND_DROP
Bind(wxEVT_STC_DO_DROP, [=](wxStyledTextEvent& event) {
if (HexMode() || GetReadOnly())
{
event.SetDragResult(wxDragNone);
}
event.Skip();});
Bind(wxEVT_STC_START_DRAG, [=](wxStyledTextEvent& event) {
if (HexMode() || GetReadOnly())
{
event.SetDragAllowMove(false);
}
event.Skip();});
#endif
Bind(wxEVT_STC_DWELLEND, [=](wxStyledTextEvent& event) {
if (CallTipActive())
{
CallTipCancel();
}});
Bind(wxEVT_STC_MARGINCLICK, [=](wxStyledTextEvent& event) {
if (event.GetMargin() == m_MarginFoldingNumber)
{
const int line = LineFromPosition(event.GetPosition());
const int level = GetFoldLevel(line);
if ((level & wxSTC_FOLDLEVELHEADERFLAG) > 0)
{
ToggleFold(line);
}
}});
Bind(wxEVT_STC_UPDATEUI, [=](wxStyledTextEvent& event) {
event.Skip();
wxExFrame::UpdateStatusBar(this, "PaneInfo");});
wxExFindReplaceData* frd = wxExFindReplaceData::Get();
Bind(wxEVT_FIND, [=](wxFindDialogEvent& event) {
frd->SetFindString(frd->GetFindString());
FindNext(frd->SearchDown());});
Bind(wxEVT_FIND_NEXT, [=](wxFindDialogEvent& event) {
frd->SetFindString(frd->GetFindString());
FindNext(frd->SearchDown());});
Bind(wxEVT_FIND_REPLACE, [=](wxFindDialogEvent& event) {
ReplaceNext(wxExFindReplaceData::Get()->SearchDown());});
Bind(wxEVT_FIND_REPLACE_ALL, [=](wxFindDialogEvent& event) {
ReplaceAll(frd->GetFindString(), frd->GetReplaceString());});
Bind(wxEVT_CHAR, &wxExSTC::OnChar, this);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Copy();}, wxID_COPY);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Cut();}, wxID_CUT);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Paste();}, wxID_PASTE);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Undo();}, wxID_UNDO);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Redo();}, wxID_REDO);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {SelectAll();}, wxID_SELECTALL);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {if (!GetReadOnly() && !HexMode()) Clear();}, wxID_DELETE);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {GotoDialog();}, wxID_JUMP_TO);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {GetFindString(); event.Skip();}, wxID_FIND);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {GetFindString(); event.Skip();}, wxID_REPLACE);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {m_File.Read(event.GetString());}, ID_EDIT_READ);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {LinkOpen();}, ID_EDIT_OPEN_LINK);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {ShowProperties();}, ID_EDIT_SHOW_PROPERTIES);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {ControlCharDialog();}, ID_EDIT_CONTROL_CHAR);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {HexDecCalltip(GetCurrentPos());}, ID_EDIT_HEX_DEC_CALLTIP);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {LowerCase();}, ID_EDIT_LOWERCASE);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {UpperCase();}, ID_EDIT_UPPERCASE);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {FoldAll();}, ID_EDIT_FOLD_ALL);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {for (int i = 0; i < GetLineCount(); i++) EnsureVisible(i);}, ID_EDIT_UNFOLD_ALL);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {Reload(m_Flags ^ STC_WIN_HEX);}, ID_EDIT_HEX);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {SetZoom(++m_Zoom);}, ID_EDIT_ZOOM_IN);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {SetZoom(--m_Zoom);}, ID_EDIT_ZOOM_OUT);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {GetFindString(); FindNext(true);}, ID_EDIT_FIND_NEXT);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {GetFindString(); FindNext(false);}, ID_EDIT_FIND_PREVIOUS);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
if (GetSelectedText().empty())
{
wxLaunchDefaultBrowser(GetFileName().GetFullPath());
}
else
{
wxLaunchDefaultBrowser(GetSelectedText());}}, ID_EDIT_OPEN_BROWSER);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
const int level = GetFoldLevel(GetCurrentLine());
const int line_to_fold = (level & wxSTC_FOLDLEVELHEADERFLAG) ?
GetCurrentLine(): GetFoldParent(GetCurrentLine());
ToggleFold(line_to_fold);}, ID_EDIT_TOGGLE_FOLD);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
wxExVCSExecute(m_Frame, event.GetId() - ID_EDIT_VCS_LOWEST - 1,
std::vector< wxString >{GetFileName().GetFullPath()});},
ID_EDIT_VCS_LOWEST, ID_EDIT_VCS_HIGHEST);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
if (GetReadOnly())
{
wxLogStatus(_("Document is readonly"));
}
else
{
if (HexMode())
{
wxLogStatus(_("Not allowed in hex mode"));
return;
}
else
{
int eol_mode;
switch (event.GetId())
{
case ID_EDIT_EOL_DOS: eol_mode = wxSTC_EOL_CRLF; break;
case ID_EDIT_EOL_UNIX: eol_mode = wxSTC_EOL_LF; break;
case ID_EDIT_EOL_MAC: eol_mode = wxSTC_EOL_CR; break;
}
ConvertEOLs(eol_mode);
SetEOLMode(eol_mode);
#if wxUSE_STATUSBAR
wxExFrame::UpdateStatusBar(this, "PaneFileType");
#endif
}
}
}, ID_EDIT_EOL_DOS, ID_EDIT_EOL_MAC);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
int line = (event.GetId() == ID_EDIT_MARKER_NEXT ?
wxStyledTextCtrl::MarkerNext(GetCurrentLine() + 1, 0xFFFF):
wxStyledTextCtrl::MarkerPrevious(GetCurrentLine() - 1, 0xFFFF));
if (line == -1)
{
line = (event.GetId() == ID_EDIT_MARKER_NEXT ?
wxStyledTextCtrl::MarkerNext(0, 0xFFFF):
wxStyledTextCtrl::MarkerPrevious(GetLineCount() - 1, 0xFFFF));
}
if (line != -1)
{
GotoLine(line);
}
else
{
wxLogStatus(_("No markers present"));
}}, ID_EDIT_MARKER_NEXT, ID_EDIT_MARKER_PREVIOUS);
Bind(wxEVT_MENU, [=](wxCommandEvent& event) {
long pos;
if ((pos = wxGetNumberFromUser(_("Input") + ":",
wxEmptyString,
_("Enter Sort Position"),
GetCurrentPos() + 1 - PositionFromLine(GetCurrentLine()),
1,
GetLineEndPosition(GetCurrentLine()),
this)) > 0)
{
wxExSortSelection(this, event.GetId() == wxID_SORT_ASCENDING ? STRING_SORT_ASCENDING: STRING_SORT_DESCENDING, pos - 1);
}}, wxID_SORT_ASCENDING, wxID_SORT_DESCENDING);
}
bool wxExSTC::LinkOpen(wxString* filename)
{
const wxString sel = GetSelectedText();
const wxString text = (!sel.empty() ? sel: GetCurLine());
int line_no = 0;
int col_no = 0;
const wxString path = m_Link.GetPath(text, line_no, col_no);
if (!path.empty())
{
if (filename == NULL)
{
if (m_Frame != NULL)
{
return m_Frame->OpenFile(
path,
line_no,
wxEmptyString,
col_no,
GetFlags() | STC_WIN_FROM_OTHER);
}
else
{
return Open(
path,
line_no,
wxEmptyString,
col_no,
GetFlags() | STC_WIN_FROM_OTHER);
}
}
else
{
*filename = wxFileName(path).GetFullName();
}
}
return !path.empty();
}
bool wxExSTC::MarkerDeleteAllChange()
{
if (!wxExLexers::Get()->MarkerIsLoaded(m_MarkerChange))
{
return false;
}
MarkerDeleteAll(m_MarkerChange.GetNo());
return true;
}
void wxExSTC::MarkModified(const wxStyledTextEvent& event)
{
if (!wxExLexers::Get()->MarkerIsLoaded(m_MarkerChange))
{
return;
}
UseModificationMarkers(false);
const int line = LineFromPosition(event.GetPosition());
if (event.GetModificationType() & wxSTC_PERFORMED_UNDO)
{
if (event.GetLinesAdded() == 0)
{
MarkerDelete(line, m_MarkerChange.GetNo());
}
else
{
for (int i = 0; i < abs(event.GetLinesAdded()); i++)
{
MarkerDelete(line + 1, m_MarkerChange.GetNo());
}
}
if (!IsModified())
{
MarkerDeleteAllChange();
}
}
else if (
(event.GetModificationType() & wxSTC_MOD_INSERTTEXT) ||
(event.GetModificationType() & wxSTC_MOD_DELETETEXT))
{
if (event.GetLinesAdded() <= 0)
{
MarkerAdd(line, m_MarkerChange.GetNo());
}
else
{
for (int i = 0; i < event.GetLinesAdded(); i++)
{
MarkerAdd(line + i, m_MarkerChange.GetNo());
}
}
}
UseModificationMarkers(true);
}
void wxExSTC::OnChar(wxKeyEvent& event)
{
if (!m_vi.GetIsActive())
{
if (wxIsalnum(event.GetUnicodeKey()))
{
m_AddingChars = true;
}
}
else if (m_vi.GetMode() == wxExVi::MODE_INSERT)
{
if (wxIsalnum(event.GetUnicodeKey()))
{
m_AddingChars = true;
}
CheckAutoComp(event.GetUnicodeKey());
}
else
{
m_AddingChars = false;
}
if (m_vi.OnChar(event))
{
if (
GetReadOnly() &&
wxIsalnum(event.GetUnicodeKey()))
{
wxLogStatus(_("Document is readonly"));
return;
}
if (HexMode())
{
if (GetOvertype())
{
if (wxExHexModeLine(&m_HexMode).Replace(event.GetUnicodeKey()))
{
CharRight();
}
}
return;
}
if (!m_vi.GetIsActive())
{
CheckAutoComp(event.GetUnicodeKey());
}
event.Skip();
}
if (
event.GetUnicodeKey() == '>' &&
m_Lexer.GetScintillaLexer() == "hypertext")
{
const int match_pos = FindText(
GetCurrentPos() - 1,
PositionFromLine(GetCurrentLine()),
"<");
if (match_pos != wxSTC_INVALID_POSITION)
{
const wxString match(GetWordAtPos(match_pos + 1));
if (
!match.StartsWith("/") &&
GetCharAt(GetCurrentPos() - 2) != '/' &&
(m_Lexer.GetLanguage() == "xml" || m_Lexer.IsKeyword(match)))
{
const wxString add("</" + match + ">");
if (m_vi.GetIsActive())
{
const int esc = 27;
if (
!m_vi.Command(add.ToStdString()) ||
!m_vi.Command(wxString(wxUniChar(esc)).ToStdString()) ||
!m_vi.Command("%") ||
!m_vi.Command("i"))
{
wxLogStatus("Autocomplete failed");
}
}
else
{
InsertText(GetCurrentPos(), add);
}
}
}
}
}
void wxExSTC::OnIdle(wxIdleEvent& event)
{
event.Skip();
if (
m_File.CheckSync() &&
// the readonly flags bit of course can differ from file actual readonly mode,
// therefore add this check
!(m_Flags & STC_WIN_READ_ONLY) &&
GetFileName().GetStat().IsReadOnly() != GetReadOnly())
{
FileReadOnlyAttributeChanged();
}
}
void wxExSTC::OnStyledText(wxStyledTextEvent& event)
{
MarkModified(event);
event.Skip();
}
bool wxExSTC::Open(
const wxExFileName& filename,
int line_number,
const wxString& match,
int col_number,
long flags)
{
if (GetFileName() == filename && line_number > 0)
{
GotoLineAndSelect(line_number, match, col_number);
PropertiesMessage();
return true;
}
m_Flags = flags;
bool success;
if (m_File.FileLoad(filename))
{
SetName(filename.GetFullPath());
if (line_number > 0)
{
GotoLineAndSelect(line_number, match, col_number);
}
else
{
if (line_number == -1)
{
if (!match.empty())
{
FindNext(match, 0, false);
}
else
{
DocumentEnd();
}
}
else if (!match.empty())
{
FindNext(match);
}
}
PropertiesMessage();
success = true;
}
else
{
success = false;
}
if (success && m_Frame != NULL)
{
m_Frame->SetRecentFile(filename.GetFullPath());
}
return success;
}
void wxExSTC::Paste()
{
if (CanPaste())
{
wxStyledTextCtrl::Paste();
}
}
bool wxExSTC::PositionRestore()
{
if (m_SavedSelectionStart != -1 && m_SavedSelectionEnd != -1)
{
SetSelection(m_SavedSelectionStart, m_SavedSelectionEnd);
}
else if (m_SavedPos != -1)
{
SetSelection(m_SavedPos, m_SavedPos);
}
else
{
return false;
}
SetCurrentPos(m_SavedPos);
EnsureCaretVisible();
return true;
}
void wxExSTC::PositionSave()
{
m_SavedPos = GetCurrentPos();
m_SavedSelectionStart = GetSelectionStart();
m_SavedSelectionEnd = GetSelectionEnd();
}
#if wxUSE_PRINTING_ARCHITECTURE
void wxExSTC::Print(bool prompt)
{
wxPrintData* data = wxExPrinting::Get()->GetHtmlPrinter()->GetPrintData();
wxExPrinting::Get()->GetPrinter()->GetPrintDialogData().SetPrintData(*data);
wxExPrinting::Get()->GetPrinter()->Print(this, new wxExPrintout(this), prompt);
}
#endif
#if wxUSE_PRINTING_ARCHITECTURE
void wxExSTC::PrintPreview()
{
wxPrintPreview* preview = new wxPrintPreview(
new wxExPrintout(this),
new wxExPrintout(this));
if (!preview->Ok())
{
delete preview;
wxLogError("There was a problem previewing.\nPerhaps your current printer is not set correctly?");
return;
}
wxPreviewFrame* frame = new wxPreviewFrame(
preview,
this,
wxExPrintCaption(GetName()));
frame->Initialize();
frame->Show();
}
#endif
void wxExSTC::PropertiesMessage(long flags)
{
wxExLogStatus(GetFileName(), flags);
#if wxUSE_STATUSBAR
if (flags != STAT_SYNC)
{
wxExFrame::UpdateStatusBar(this, "PaneFileType");
wxExFrame::UpdateStatusBar(this, "PaneLexer");
}
wxExFrame::UpdateStatusBar(this, "PaneInfo");
#endif
if (!(flags & STAT_SYNC) && m_Frame != NULL)
{
const wxString file = GetName() +
(GetReadOnly() ? " [" + _("Readonly") + "]": wxString(wxEmptyString));
if (file.empty())
{
m_Frame->SetTitle(wxTheApp->GetAppName());
}
else
{
m_Frame->SetTitle(file);
}
}
}
void wxExSTC::Reload(long flags)
{
if (!m_HexMode.Set((flags & STC_WIN_HEX) > 0,
flags & STC_WIN_HEX ? GetTextRaw(): wxCharBuffer()))
{
return;
}
m_Flags = flags;
if (
(m_Flags & STC_WIN_READ_ONLY) ||
(GetFileName().Exists() && !GetFileName().IsFileWritable()))
{
SetReadOnly(true);
}
}
int wxExSTC::ReplaceAll(
const wxString& find_text,
const wxString& replace_text)
{
if (HexMode())
{
wxLogStatus(_("Not allowed in hex mode"));
return 0;
}
int selection_from_end = 0;
if (SelectionIsRectangle() || wxExGetNumberOfLines(GetSelectedText()) > 1)
{
TargetFromSelection();
selection_from_end = GetLength() - GetTargetEnd();
}
else
{
SetTargetStart(0);
SetTargetEnd(GetLength());
}
int nr_replacements = 0;
SetSearchFlags(-1);
BeginUndoAction();
while (SearchInTarget(find_text) != -1)
{
bool skip_replace = false;
// Check that the target is within the rectangular selection.
// If not just continue without replacing.
if (SelectionIsRectangle())
{
const int line = LineFromPosition(GetTargetStart());
const int start_pos = GetLineSelStartPosition(line);
const int end_pos = GetLineSelEndPosition(line);
const int length = GetTargetEnd() - GetTargetStart();
if (start_pos == wxSTC_INVALID_POSITION ||
end_pos == wxSTC_INVALID_POSITION ||
GetTargetStart() < start_pos ||
GetTargetStart() + length > end_pos)
{
skip_replace = true;
}
}
if (!skip_replace)
{
wxExFindReplaceData::Get()->UseRegEx() ?
ReplaceTargetRE(replace_text):
ReplaceTarget(replace_text);
nr_replacements++;
}
SetTargetStart(GetTargetEnd());
SetTargetEnd(GetLength() - selection_from_end);
if (GetTargetStart() >= GetTargetEnd())
{
break;
}
}
EndUndoAction();
wxLogStatus(_("Replaced: %d occurrences of: %s"),
nr_replacements, find_text.c_str());
return nr_replacements;
}
bool wxExSTC::ReplaceNext(bool find_next)
{
return ReplaceNext(
wxExFindReplaceData::Get()->GetFindString(),
wxExFindReplaceData::Get()->GetReplaceString(),
-1,
find_next);
}
bool wxExSTC::ReplaceNext(
const wxString& find_text,
const wxString& replace_text,
int find_flags,
bool find_next)
{
if (!GetSelectedText().empty())
{
TargetFromSelection();
}
else
{
SetTargetStart(GetCurrentPos());
SetTargetEnd(GetLength());
SetSearchFlags(find_flags);
if (SearchInTarget(find_text) == -1) return false;
}
if (HexMode())
{
for (const auto& it : replace_text)
{
wxExHexModeLine(&m_HexMode, GetTargetStart()).Replace(it);
}
}
else
{
wxExFindReplaceData::Get()->UseRegEx() ?
ReplaceTargetRE(replace_text):
ReplaceTarget(replace_text);
}
FindNext(find_text, find_flags, find_next);
return true;
}
void wxExSTC::ResetLexer()
{
m_Lexer.Reset(this);
wxExFrame::StatusText(m_Lexer.GetDisplayLexer(), "PaneLexer");
SetMarginWidth(m_MarginFoldingNumber, 0);
}
void wxExSTC::ResetMargins(bool divider_margin)
{
SetMarginWidth(m_MarginFoldingNumber, 0);
SetMarginWidth(m_MarginLineNumber, 0);
if (divider_margin)
{
SetMarginWidth(m_MarginDividerNumber, 0);
}
}
void wxExSTC::SelectNone()
{
if (SelectionIsRectangle())
{
// SetSelection does not work.
CharRight();
CharLeft();
}
else
{
// The base styledtextctrl version uses scintilla, sets caret at 0.
SetSelection(GetCurrentPos(), GetCurrentPos());
}
}
bool wxExSTC::SetIndicator(
const wxExIndicator& indicator,
int start,
int end)
{
if (!wxExLexers::Get()->IndicatorIsLoaded(indicator))
{
return false;
}
SetIndicatorCurrent(indicator.GetNo());
IndicatorFillRange(start, end - start);
return true;
}
bool wxExSTC::SetLexer(const wxExLexer& lexer, bool fold)
{
if (!m_Lexer.Set(lexer, this))
{
return false;
}
SetLexerCommon(fold);
return true;
}
bool wxExSTC::SetLexer(const wxString& lexer, bool fold)
{
if (!m_Lexer.Set(lexer, this))
{
return false;
}
SetLexerCommon(fold);
return true;
}
void wxExSTC::SetLexerCommon(bool fold)
{
if (fold)
{
Fold();
}
if (!HexMode() &&
m_Lexer.GetScintillaLexer() == "po")
{
if (!m_Link.AddBasePath())
{
wxLogStatus("Could not add base path");
}
}
wxExFrame::StatusText(m_Lexer.GetDisplayLexer(), "PaneLexer");
}
void wxExSTC::SetLexerProperty(const wxString& name, const wxString& value)
{
m_Lexer.SetProperty(name, value);
m_Lexer.Apply(this);
}
void wxExSTC::SetSearchFlags(int flags)
{
if (flags == -1)
{
flags = 0;
wxExFindReplaceData* frd = wxExFindReplaceData::Get();
if (frd->UseRegEx()) flags |= wxSTC_FIND_REGEXP;
if (frd->MatchWord()) flags |= wxSTC_FIND_WHOLEWORD;
if (frd->MatchCase()) flags |= wxSTC_FIND_MATCHCASE;
}
wxStyledTextCtrl::SetSearchFlags(flags);
}
void wxExSTC::SetText(const wxString& value)
{
ClearDocument();
AddTextRaw((const char *)value.c_str(), value.length());
DocumentStart();
// Do not allow the text specified to be undone.
EmptyUndoBuffer();
}
void wxExSTC::ShowLineNumbers(bool show)
{
const int margin = wxConfigBase::Get()->ReadLong(
_("Line number"),
TextWidth(wxSTC_STYLE_DEFAULT, "999999"));
SetMarginWidth(
m_MarginLineNumber,
show ? margin: 0);
}
void wxExSTC::ShowProperties()
{
// Added check, otherwise scintilla crashes.
const wxString propnames = (!m_Lexer.GetScintillaLexer().empty() ?
PropertyNames(): wxString(wxEmptyString));
wxString text;
if (!propnames.empty())
{
text += "Current properties\n";
}
// Add global properties.
for (const auto& it1 : wxExLexers::Get()->GetProperties())
{
text += it1.GetName() + ": " + GetProperty(it1.GetName()) + "\n";
}
// Add lexer properties.
for (const auto& it2 : m_Lexer.GetProperties())
{
text += it2.GetName() + ": " + GetProperty(it2.GetName()) + "\n";
}
// Add available properties.
if (!propnames.empty())
{
text += "\nAvailable properties\n";
wxStringTokenizer tkz(propnames, "\n");
while (tkz.HasMoreTokens())
{
const wxString prop = tkz.GetNextToken();
text += prop + ": " + DescribeProperty(prop) + "\n";
}
}
if (m_EntryDialog == NULL)
{
m_EntryDialog = new wxExSTCEntryDialog(
wxTheApp->GetTopWindow(),
_("Properties"),
text,
wxEmptyString,
wxOK);
}
else
{
m_EntryDialog->GetSTC()->SetText(text);
}
m_EntryDialog->Show();
}
void wxExSTC::Sync(bool start)
{
// do not use ?, compile error for gcc, as Bind is void, Unbind is bool
if (start)
Bind(wxEVT_IDLE, &wxExSTC::OnIdle, this);
else
Unbind(wxEVT_IDLE, &wxExSTC::OnIdle, this);
}
void wxExSTC::Undo()
{
wxStyledTextCtrl::Undo();
m_HexMode.Undo();
}
void wxExSTC::UseAutoComplete(bool use)
{
m_UseAutoComplete = use;
}
void wxExSTC::UseModificationMarkers(bool use)
{
if (use)
Bind(wxEVT_STC_MODIFIED, &wxExSTC::OnStyledText, this);
else
Unbind(wxEVT_STC_MODIFIED, &wxExSTC::OnStyledText, this);
}
#endif // wxUSE_GUI
|
e8dc833268ce85b2d74a644369b734d97c826f5b
|
808062326439f77d77c0140178edbb023606ffdb
|
/src/Graph.h
|
20425da8bc8176762a6709fb4ada7398bf2b8f89
|
[] |
no_license
|
diogo92/LAIG_2014_Turma3_Grupo4
|
702afb756f8351202cdce7d6d414027799a99679
|
53f7a02ac134ea8ed8f8c73cc3f5b9c5ba63c87c
|
refs/heads/master
| 2020-04-01T23:53:22.892288
| 2015-01-05T01:48:04
| 2015-01-05T01:48:04
| 24,146,416
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,155
|
h
|
Graph.h
|
#ifndef _GRAPH_H
#define _GRAPH_H
#include <map>
#include <string>
#include <vector>
#include "VisualObject.h"
#include "Camera.h"
#include "Light.h"
#include "Appearance.h"
#include "Animation.h"
using std::map;
using std::string;
using std::vector;
class Node;
struct Texture{
string id;
string file;
float texlength_s;
float texlength_t;
};
class Graph
{
public:
Graph(void);
~Graph(void);
void draw();
map<string,Node> nodes;
map<string,Camera *> cameras;
map<string,Texture> textures;
map<string,Appearance> appearances;
void setAppearances();
vector<Light*> lights;
string rootNode;
vector<Animation * > anims;
};
class Node
{
public:
Node(void);
~Node(void);
Node(string id);
void draw(Graph * graph);
void updateAnim(unsigned long t);
void setAppearances(Graph * graph);
void update(unsigned long t);
string id;
bool inherited;
Appearance * appear;
GLfloat matrix[16];
vector<string> childs;
vector<VisualObject*> primitives;
GLuint dispList;
bool displayList;
void draw2(Graph * graph);
void checkList(Graph * graph);
void animsTransforms();
unsigned int atualAnim;
vector<Animation * > anims;
};
#endif
|
464bf277878aea1cc3d18d0bbd78ee0e0b9a419f
|
af8679d6b9fa12b6d2072f4aec37e5ca65158770
|
/TankGame/selectlevelwindow.h
|
dce4d87a3d819d42bef92f95116ad16d38256fb2
|
[] |
no_license
|
anlowee/TankGame
|
8f503f971698b60391af1c9740e34e57368e4489
|
c2f122a9864d3ee91f0226cae9b5bd7419bc7c20
|
refs/heads/master
| 2020-06-16T16:45:53.244883
| 2019-07-20T16:14:44
| 2019-07-20T16:14:44
| 195,639,930
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
h
|
selectlevelwindow.h
|
#ifndef SELECTLEVELWINDOW_H
#define SELECTLEVELWINDOW_H
#include <QWidget>
#include <QPaintEvent>
#include "mainwindow.h"
namespace Ui {
class SelectLevelWindow;
}
class SelectLevelWindow : public QWidget
{
Q_OBJECT
public:
explicit SelectLevelWindow(QWidget *parent = nullptr);
~SelectLevelWindow();
private slots:
void paintEvent(QPaintEvent *event);
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::SelectLevelWindow *ui;
MainWindow *back;
bool is_close;
};
#endif // SELECTLEVELWINDOW_H
|
f7e5bb0977dbab7462545596dec0b863719fa5b1
|
e75f0371950d47f66c8d2c8d9df53d90d7daa1b2
|
/sources/thread/TimedFunction.hpp
|
0ac8d3270469bc9213b17ef578f3d52ebfc7eaae
|
[] |
no_license
|
DiantArts/ThreadPool
|
4c60eeeaa6c67e8b0d1b1e4f26565a7342b487d0
|
67deeff3c4d399a9249b93722a03d32152a1a6ab
|
refs/heads/main
| 2023-08-03T16:22:34.023687
| 2021-09-15T06:43:50
| 2021-09-15T06:43:50
| 406,660,488
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,810
|
hpp
|
TimedFunction.hpp
|
/*
** EPITECH PROJECT, 2020
** TimedFunction
** File description:
** Control the flow of a function over time
*/
#ifndef TIMED_FUNCTION_HPP
#define TIMED_FUNCTION_HPP
#include <list>
#include <functional>
#include <optional>
#include <chrono>
#include <atomic>
#include <deque>
#include "Pool.hpp"
struct arg_t {
uint_fast32_t numberOfTime;
std::chrono::steady_clock::time_point *intervalClockStart;
std::chrono::steady_clock::time_point *durationClockStart;
};
class ThreadPool;
class TimedFunction {
public:
explicit TimedFunction(ThreadPool &threadPool,
const std::function<void ()> &fn,
const std::optional<int> &howManyTimes = std::nullopt) noexcept;
explicit TimedFunction(ThreadPool &threadPool,
const std::function<void ()> &fn,
const std::chrono::duration<float> &interval,
const std::optional<int> &howManyTimes = std::nullopt) noexcept;
explicit TimedFunction(ThreadPool &threadPool,
const std::function<void ()> &fn,
const std::chrono::duration<float> &interval,
const std::chrono::duration<float> &duration,
const std::optional<int> &howManyTimes = std::nullopt) noexcept;
~TimedFunction() noexcept;
bool isOver() const noexcept;
void join() const noexcept;
void terminate() noexcept;
private:
friend void ThreadPool::parallelRun(ThreadPool &threadPool);
bool m_IsOver;
arg_t m_Args;
std::list<std::pair<std::function<std::optional<std::chrono::duration<float>> (void)>,
std::reference_wrapper<TimedFunction>>>::iterator m_Iterator;
};
#endif // TIMED_FUNCTION_HPP
|
82c0baf1db6a753bcd6571095867f4be734ec709
|
c47c254ca476c1f9969f8f3e89acb4d0618c14b6
|
/datasets/github_cpp_10/5/67.cpp
|
507d45ce2fd174c5672481124c3042c7e5bee8b1
|
[
"BSD-2-Clause"
] |
permissive
|
yijunyu/demo
|
5cf4e83f585254a28b31c4a050630b8f661a90c8
|
11c0c84081a3181494b9c469bda42a313c457ad2
|
refs/heads/master
| 2023-02-22T09:00:12.023083
| 2021-01-25T16:51:40
| 2021-01-25T16:51:40
| 175,939,000
| 3
| 6
|
BSD-2-Clause
| 2021-01-09T23:00:12
| 2019-03-16T07:13:00
|
C
|
UTF-8
|
C++
| false
| false
| 384
|
cpp
|
67.cpp
|
#include <stdio.h>
void towerOfHanoi(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move Disk 1 from %c to %c\n", from, to);
return;
}
towerOfHanoi(n - 1, from, aux, to);
printf("Move Disk %d from %c to %c\n", n, from, to);
towerOfHanoi(n - 1, aux, to, from);
}
int main() {
towerOfHanoi(3, 'A', 'C', 'B');
return 0;
}
|
36ec24c15fb1770601a9c8b45effc92798889fd0
|
b2eeb55b758b35f89aac8ef2f491266cd43b067a
|
/template_classes/Polynom.h
|
8810507381556b9d28fb0e4c9b6f5aaebca567fe
|
[] |
no_license
|
hurr1canexd/template-classes
|
74d8cf4d967b0ca1784a0c75f372535cb4331558
|
d6a4ce1340857586e84829aef83f94249729c33e
|
refs/heads/master
| 2022-03-04T12:58:34.323577
| 2022-02-25T21:03:23
| 2022-02-25T21:03:23
| 158,029,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,256
|
h
|
Polynom.h
|
#pragma once
#include <map>
#include <iterator>
using namespace std;
template<typename T>
class Polynom
{
private:
map<int, T> polynom;
public:
// Конструкторы
Polynom() = default;
Polynom(map<int, T>&);
Polynom(const Polynom&);
// Перегрузки
Polynom operator+(const Polynom&) const;
Polynom operator-(const Polynom&) const;
Polynom operator*(const Polynom&) const;
Polynom operator/(const Polynom&) const;
Polynom operator%(const Polynom&);
Polynom& operator=(const Polynom&);
friend ostream& operator<< <T>(ostream&, const Polynom&);
void addMonom(T, int);
Polynom differentiate();
T pointValue(T);
Polynom superposition(Polynom);
friend Polynom operator*(const Polynom& P, const int num)
{
Polynom<T> res;
for (auto it : P.polynom)
res.addMonom(it.second * num, it.first);
return res;
}
};
template<typename T>
Polynom<T>::Polynom(map<int, T> &mp)
{
for (auto it : mp)
if (it.second != 0)
polynom[it.first] = it.second;
}
// Конструктор копирования
template<typename T>
Polynom<T>::Polynom(const Polynom& P)
{
polynom = P.polynom;
}
//operator=
template<typename T>
Polynom<T> & Polynom<T>::operator=(const Polynom<T>& P)
{
polynom = P.polynom;
return *this;
}
//operator+
template<typename T>
Polynom<T> Polynom<T>::operator+(const Polynom<T>& P) const
{
Polynom<T> res(*this);
for (auto it : P.polynom)
res.addMonom(it.second, it.first);
return res;
}
//operator-
template<typename T>
Polynom<T> Polynom<T>::operator-(const Polynom<T>& P) const
{
Polynom<T> res(P * -1);
res = res + *this;
return res;
}
//operator*
template<typename T>
Polynom<T> Polynom<T>::operator*(const Polynom<T>& P) const
{
Polynom<T> res;
for (auto it1 : this->polynom)
{
for (auto it2 : P.polynom)
{
res.addMonom(it1.second * it2.second, it1.first + it2.first);
}
}
return res;
}
template<typename T>
Polynom<T> Polynom<T>::operator/(const Polynom<T>& P) const
{
Polynom<T> divisionPoly(*this);
Polynom<T> res;
auto inp_it = P.polynom.end();
--inp_it;
while (true)
{
if (divisionPoly.polynom.empty())
{
T var = 0;
res.addMonom(0, var);
return res;
}
auto div_it = divisionPoly.polynom.end();
--div_it;
if (div_it->first < inp_it->first)
return res;
else
{
for (auto it = P.polynom.begin(); it != inp_it; ++it)
{
T num = -1;
divisionPoly.addMonom(num * it->second * div_it->second / inp_it->second, it->first + div_it->first - inp_it->first);
}
res.addMonom(div_it->second / inp_it->second, div_it->first - inp_it->first);
divisionPoly.polynom.erase(div_it);
}
}
}
//operator%
template<typename T>
Polynom<T> Polynom<T>::operator%(const Polynom<T>& P)
{
Polynom<T> res(*this);
auto inp_it = P.polynom.end();
--inp_it;
while (true)
{
if (res.polynom.empty())
{
T var = 0;
res.addMonom(0, var);
return res;
}
auto res_it = res.polynom.end();
--res_it;
if (res_it->first < inp_it->first)
return res;
else
{
for (auto it = P.polynom.begin(); it != inp_it; ++it)
{
T num = -1;
res.addMonom(num * it->second * res_it->second / inp_it->second, it->first + res_it->first - inp_it->first);
}
res.polynom.erase(res_it);
}
}
}
// Добавить моном
template<typename T>
void Polynom<T>::addMonom(T item, int degree)
{
if (polynom.count(degree))
{
polynom[degree] = polynom[degree] + item;
}
else
polynom[degree] = item;
if (!polynom[degree])
{
auto it = polynom.find(degree);
polynom.erase(it);
}
}
// Производная
template<typename T>
Polynom<T> Polynom<T>::differentiate()
{
Polynom<T> res;
for (auto it : polynom)
{
if (it.first != 0)
res.addMonom(it.second * it.first, it.first - 1);
else
{
T num = 0;
res.addMonom(num, 0);
}
}
return res;
}
// Значение в точке
template<typename T>
T Polynom<T>::pointValue(T x)
{
if (!polynom.empty())
{
T sum = 0, pw_val;
for (auto it : polynom)
{
if (it.first != 0)
pw_val = x;
else
pw_val = 1;
for (int i = it.first - 1; i > 0; i--)
pw_val = pw_val * x;
sum += pw_val * it.second;
}
return sum;
}
else
{
return 0;
}
}
template<typename T>
Polynom<T> Polynom<T>::superposition(Polynom<T> P)
{
Polynom<T> res;
for (auto it : polynom)
{
if (it.first > 0)
{
Polynom<T> pwPolу(P), coeffsPoly;
for (int i = it.first - 1; i > 0; i--)
pwPolу = pwPolу * P;
coeffsPoly.addMonom(it.second, 0);
res = res + coeffsPoly * pwPolу;
}
else if (it.first == 0)
res.addMonom(it.second, 0);
}
return res;
}
// Перегрузка оператора вставки в поток
template<typename T>
ostream& operator<<(ostream& os, const Polynom<T>& P)
{
if (P.polynom.empty())
os << 0;
else
{
auto iter = P.polynom.end();
iter--;
for (auto it = P.polynom.begin(); it != iter; ++it)
{
if (it->first == 0)
os << it->second << " + ";
else
if (it->first == 1)
os << it->second << "x" << " + ";
else
os << it->second << "x^" << it->first << " + ";
}
if (iter->first == 0)
os << iter->second;
else
if (iter->first == 1)
os << iter->second << "x";
else
os << iter->second << "x^" << iter->first;
}
return os;
}
|
f7e515be71ccc16d307f602532e676e0e7f1fbe8
|
f812cbcfba682dd3c2bc973bcb2c2d4cd5930524
|
/IDE/utilities/MCUDataFiles/BinFile.h
|
f54dc193987fdd93070aca642ff9810e735cb507
|
[] |
no_license
|
AbyssAbbeba/MDS-picoblaze-AVR-ide
|
bceb4bd3e300fcdb4213a0880a5c7e6f6433704e
|
afc0cf7fd115ce063303f27d0bc03dc9f146e19b
|
refs/heads/master
| 2020-03-22T00:32:42.982094
| 2018-07-06T09:05:37
| 2018-07-06T09:05:37
| 139,251,486
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,731
|
h
|
BinFile.h
|
// =============================================================================
/**
* @brief
* C++ Interface: ...
*
* ...
*
* (C) copyright 2013, 2014 Moravia Microsystems, s.r.o.
*
* @author Martin Ošmera <martin.osmera@moravia-microsystems.com>
* @ingroup MCUDataFiles
* @file BinFile.h
*/
// =============================================================================
#ifndef BINFILE_H
#define BINFILE_H
#include "DataFile.h"
#include <string>
/**
* @brief
* @ingroup MCUDataFiles
* @class BinFile
*/
class BinFile : public DataFile
{
//// Constructors and Destructors ////
public:
/**
* @brief
* @param[in] arrsize
*/
BinFile ( unsigned int arrsize = 0x10000 ) : DataFile(arrsize) {};
/**
* @brief
* @param[in] file
*/
BinFile ( const std::string & file )
{
clearAndLoad(file);
}
//// Public Operations ////
public:
/**
* @brief Load binary file into the memory array
* @param[in] filename Source file
*/
virtual void clearAndLoad ( const char * filename ) override;
/// @overload
virtual void clearAndLoad ( const std::string & filename ) override;
/**
* @brief Save memory array in binary file
* @param[in] filename Target file
* @param[in] makeBackup Make backup file
*/
virtual void save ( const char * filename,
bool makeBackup = true ) override;
/// @overload
virtual void save ( const std::string & filename,
bool makeBackup = true ) override;
};
#endif // BINFILE_H
|
b899a767a39fe086df30cf813f30dcf90a13c190
|
ed33d9bb9ffe53cdbe4485dcba76d49209c9cf86
|
/DQuest/dqmodel.cpp
|
5b27fb42626fbae02239e76551892bb2bef53f2d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
OliverLetterer/DQuest
|
0b41dc2744d3419bd3121ece3a20b9bd53d795d8
|
5ee966bf0d266b0a65bdad8573bec0fb5f52eda0
|
refs/heads/master
| 2021-04-09T17:19:51.954878
| 2013-04-01T08:32:03
| 2013-04-01T08:32:03
| 9,143,691
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,416
|
cpp
|
dqmodel.cpp
|
#include <QtCore>
#include <QMetaObject>
#include <QMetaProperty>
#include "dqmodel.h"
#include "dqmetainfoquery_p.h"
#include "dqlist.h"
#include "dqsql.h"
//#define TABLE_NAME "Model without DQ_MODEL"
#define TABLE_NAME ""
DQModel::DQModel() : m_connection ( DQConnection::defaultConnection()){
}
DQModel::DQModel(DQConnection connection) : m_connection(connection)
{
}
DQModel::~DQModel(){
}
QString DQModel::tableName() const{
return TABLE_NAME;
}
QString DQModel::TableName() {
return TABLE_NAME;
}
void DQModel::setConnection(DQConnection connection){
m_connection = connection;
}
DQConnection DQModel::connection(){
return m_connection;
}
bool DQModel::save(bool forceInsert,bool forceAllField) {
if (!clean() ) {
return false;
}
DQModelMetaInfo *info = metaInfo();
Q_ASSERT(info);
QStringList fields = info->fieldNameList();
QStringList nonNullFields;
if (forceAllField) {
nonNullFields = fields;
} else {
foreach (QString field , fields) {
QVariant v = info->value(this,field);
if (forceInsert && field == "id" ) // skip id field when forceInsert
continue;
if (!v.isNull() ) {
// qDebug() << field;
nonNullFields << field;
}
}
}
bool res ;
DQSql sql = m_connection.sql();
if (forceInsert || id->isNull() ) {
res = sql.replaceInto(info,this,nonNullFields,true);
} else {
res = sql.replaceInto(info,this,nonNullFields,false);
}
m_connection.setLastQuery(sql.lastQuery());
return res;
}
bool DQModel::load(DQWhere where){
bool res = false;
_DQMetaInfoQuery query( metaInfo() , m_connection);
query = query.filter(where).limit(1);
if (query.exec()){
if (query.next()){
res = query.recordTo(this);
}
}
if (!res)
id->clear();
m_connection.setLastQuery(query.lastQuery());
return res;
}
bool DQModel::remove() {
if (id->isNull())
return false;
_DQMetaInfoQuery query( metaInfo() , m_connection);
query = query.filter(DQWhere("id = " , id()) );
bool res = query.remove();
if (res){
id->clear();
}
m_connection.setLastQuery( query.lastQuery());
return res;
}
bool DQModel::clean(){
return true;
}
DQSharedList DQModel::initialData() const {
return DQSharedList();
}
|
65dbc50c5f35f845a8045ca90663750b4f3d72a8
|
70ad0a06c54b68b7d817131f4b139b76739e2e20
|
/Zeroconf/ZeroconfTests.cc
|
4af6f28892af3d7a8f3c48e7b3cab1635b35ad58
|
[
"MIT"
] |
permissive
|
SherlockThang/sidecar
|
391b08ffb8a91644cbc86cdcb976993386aca70c
|
2d09dfaebee3c9b030db4d8503b765862e634068
|
refs/heads/master
| 2022-12-09T14:57:08.727181
| 2020-09-01T10:31:12
| 2020-09-01T10:31:12
| 313,326,062
| 1
| 0
|
MIT
| 2020-11-16T14:21:59
| 2020-11-16T14:21:58
| null |
UTF-8
|
C++
| false
| false
| 3,526
|
cc
|
ZeroconfTests.cc
|
#include <sys/types.h>
#include <unistd.h>
#include "ace/Event_Handler.h"
#include "ace/Reactor.h"
#include "boost/bind.hpp"
#include "Logger/Log.h"
#include "UnitTest/UnitTest.h"
#include "Zeroconf/ACEMonitor.h"
#include "Zeroconf/Browser.h"
#include "Zeroconf/Publisher.h"
using namespace SideCar::Zeroconf;
struct Test : public UnitTest::TestObj, public ACE_Event_Handler {
using ServiceEntryVector = Browser::ServiceEntryVector;
static Logger::Log& Log()
{
static Logger::Log& log = Logger::Log::Find("ZeroconfTests.Test");
return log;
}
Test() :
TestObj("Zeroconf"), ACE_Event_Handler(ACE_Reactor::instance()), name_(""), port_(::getpid()),
wasPublished_(false), found_(false)
{
char hostName[1024];
::gethostname(hostName, 1024);
std::ostringstream os("");
os << "ZCT_" << hostName << '_' << ::getpid();
name_ = os.str();
}
void test();
void publishedNotification(bool state);
void foundServiceNotification(const ServiceEntryVector& services);
int handle_timeout(const ACE_Time_Value& duration, const void* arg);
std::string name_;
uint16_t port_;
bool wasPublished_;
bool found_;
};
void
Test::publishedNotification(bool state)
{
Logger::ProcLog log("publishedNotification", Log());
LOGINFO << "state: " << state << std::endl;
wasPublished_ = state;
if (state && found_) {
LOGINFO << "shutting down" << std::endl;
ACE_Reactor::instance()->end_reactor_event_loop();
}
}
void
Test::foundServiceNotification(const ServiceEntryVector& services)
{
Logger::ProcLog log("foundServiceNotification", Log());
for (size_t index = 0; index < services.size() && !found_; ++index) {
LOGINFO << "found " << services[index]->getName() << std::endl;
if (services[index]->getName() == name_) {
LOGINFO << "found" << std::endl;
found_ = true;
}
}
if (wasPublished_ && found_) {
LOGINFO << "shutting down" << std::endl;
ACE_Reactor::instance()->end_reactor_event_loop();
}
}
int
Test::handle_timeout(const ACE_Time_Value& duration, const void* arg)
{
ACE_Reactor::instance()->end_reactor_event_loop();
return 0;
}
void
Test::test()
{
Logger::Log::Find("root").setPriorityLimit(Logger::Priority::kDebug);
ACEMonitorFactory::Ref monitorFactory(ACEMonitorFactory::Make());
Publisher::Ref publisher(Publisher::Make(monitorFactory->make()));
publisher->setType("_blah._tcp");
assertTrue(publisher.unique());
publisher->connectToPublishedSignal(boost::bind(&Test::publishedNotification, this, _1));
Browser::Ref browser(Browser::Make(monitorFactory, "_blah._tcp"));
assertTrue(browser.unique());
browser->connectToFoundSignal(boost::bind(&Test::foundServiceNotification, this, _1));
assertTrue(browser->start());
assertTrue(publisher->setTextData("one", "first", false));
assertTrue(publisher->setTextData("two", "second"));
publisher->setPort(port_);
assertTrue(publisher->publish(name_, false));
const ACE_Time_Value delay(10);
const ACE_Time_Value repeat(0);
long timer = reactor()->schedule_timer(this, 0, delay, repeat);
ACE_Reactor::instance()->run_reactor_event_loop();
reactor()->cancel_timer(timer);
assertTrue(wasPublished_);
assertTrue(found_);
publisher->stop();
browser->stop();
}
int
main(int argc, const char* argv[])
{
return Test().mainRun();
}
|
631474ce74b7b20d05d86d6253c9e56a6d5c0727
|
2f10f807d3307b83293a521da600c02623cdda82
|
/deps/boost/win/debug/include/boost/log/utility/setup/from_stream.hpp
|
ca306afacd01a0f14fc15b7b213135ec4127a85b
|
[] |
no_license
|
xpierrohk/dpt-rp1-cpp
|
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
|
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
|
refs/heads/master
| 2021-05-23T08:19:48.823198
| 2019-07-26T17:35:28
| 2019-07-26T17:35:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 129
|
hpp
|
from_stream.hpp
|
version https://git-lfs.github.com/spec/v1
oid sha256:39e73ed6d5dbffe1a6c63017ea1eb8c654f8c3fc3b7b61fe11dd882bd0a2d7e2
size 1290
|
bc20782d418bd00a474bbcb5fcb7d2e3adce4dba
|
5f73d1c903ccd3ea3c4bae168dff1f5cd58842ca
|
/qtTeamTalk/onlineusersdlg.h
|
e5e1183348fbd85e4d474e7f3572fcd49e9de5ba
|
[] |
no_license
|
supercoeus/TeamTalk5
|
805f3bd278e3c1a6b0007259f3d269c8fd2eb59b
|
a146ad3b7c161af4fb8b1d4ab2a489b2745fe785
|
refs/heads/master
| 2020-12-25T20:42:46.337718
| 2016-07-28T18:01:39
| 2016-07-28T18:01:39
| 64,459,213
| 1
| 0
| null | 2016-07-29T07:12:43
| 2016-07-29T07:12:43
| null |
UTF-8
|
C++
| false
| false
| 1,638
|
h
|
onlineusersdlg.h
|
/*
* Copyright (c) 2005-2016, BearWare.dk
*
* Contact Information:
*
* Bjoern D. Rasmussen
* Skanderborgvej 40 4-2
* DK-8000 Aarhus C
* Denmark
* Email: contact@bearware.dk
* Phone: +45 20 20 54 59
* Web: http://www.bearware.dk
*
* This source code is part of the TeamTalk 5 SDK owned by
* BearWare.dk. All copyright statements may not be removed
* or altered from any source distribution. If you use this
* software in a product, an acknowledgment in the product
* documentation is required.
*
*/
#ifndef ONLINEUSERSDLG_H
#define ONLINEUSERSDLG_H
#include "ui_onlineusers.h"
#include "onlineusersmodel.h"
#include <QSortFilterProxyModel>
class OnlineUsersDlg : public QDialog
{
Q_OBJECT
public:
OnlineUsersDlg(QWidget* parent = 0);
void updateTitle();
public slots:
void slotUserLoggedIn(const User& user);
void slotUserLoggedOut(const User& user);
void slotUserUpdate(const User& user);
void slotUserJoin(int channelid, const User& user);
void slotUserLeft(int channelid, const User& user);
signals:
void viewUserInformation(int userid);
void sendUserMessage(int userid);
void muteUser(int userid, bool mute);
void changeUserVolume(int userid);
void opUser(int userid, int chanid);
void kickUser(int userid, int chanid);
void kickbanUser(int userid, int chanid);
void streamfileToUser(int userid);
private slots:
void slotTreeContextMenu(const QPoint&);
private:
Ui::OnlineUsersDlg ui;
OnlineUsersModel* m_model;
QSortFilterProxyModel* m_proxyModel;
};
#endif
|
125967786e16aec39e9700f4e1c60b02d9b65c65
|
80d5a283df5f6c5a2d5b712c51664bcd8c628913
|
/WOFFCEdit/Custom_CEdit.h
|
09e63f8e480ea7e6e0b9e22a8c6de45cdaf8fcdf
|
[] |
no_license
|
Ruzry/WFFC-Edit
|
652e96170e6b40692279c3781490305b078b4c54
|
870999bbcdcba8a4a331fefea3ac17544424d4e4
|
refs/heads/master
| 2022-11-16T04:51:35.467951
| 2020-07-15T21:31:24
| 2020-07-15T21:31:24
| 275,418,829
| 0
| 0
| null | 2020-06-27T17:14:48
| 2020-06-27T17:14:47
| null |
UTF-8
|
C++
| false
| false
| 329
|
h
|
Custom_CEdit.h
|
#pragma once
#include <afxwin.h>
class Custom_CEdit :
public CEdit
{
public:
Custom_CEdit();
~Custom_CEdit();
bool checkPoint;
bool negative;
bool isFocused = false;
DECLARE_MESSAGE_MAP()
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
};
|
ce11fc6be5552269d4f17ada97f72accb2f61601
|
6e8750711d86736286324e3864f8dc0efd998aa1
|
/Utilities/Source/mklJac.h
|
d60e5099fbddbb668ccd66bdeb2132ebd33a5207
|
[
"BSD-3-Clause"
] |
permissive
|
jonathancurrie/OPTI
|
eb1825de5ce23a1e85a80bdaf18efa1130de2d1a
|
c9636bb2da69dc225d5791eac04fb36c7c0e71c8
|
refs/heads/master
| 2023-05-26T06:17:37.299405
| 2023-04-02T23:43:43
| 2023-04-02T23:43:43
| 34,312,503
| 184
| 122
| null | 2022-05-13T19:32:03
| 2015-04-21T07:51:06
|
C++
|
UTF-8
|
C++
| false
| false
| 569
|
h
|
mklJac.h
|
/* MKLJAC - A MATLAB MEX Interface to Intel MKL's DJACOBI
* Released Under the BSD 3-Clause License:
* https://www.controlengineering.co.nz/Wikis/OPTI/index.php/DL/License
*
* Copyright (C) Jonathan Currie 2012-2017
* www.controlengineering.co.nz
*/
#include "opti_mex_utils.h"
namespace opti_utility
{
class MKLJac
{
public:
static void differentiate(const opti_mex_utils::OptiMexArgs& args);
private:
static void checkInputArgs(const opti_mex_utils::OptiMexArgs& args, bool& haveSize, bool& haveTol);
};
} // namespace opti_utility
|
6e90a387796402959350a080ec3e61b77c9a9bc1
|
5b41b766d419fa2ff2501bd2a30e7cfe93431263
|
/color_wheel.cpp
|
5656473183274680e394dbf60e928161ee56ba69
|
[] |
no_license
|
scientLunatic/Color-picker
|
21785eb727f2bd6d2d8d41b73c2c1befd8d05de3
|
53ce11eb884cd71448fd89ce2a72c26d2bc76d7d
|
refs/heads/master
| 2021-07-31T19:24:31.567855
| 2021-07-29T10:34:11
| 2021-07-29T10:34:11
| 180,895,676
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 9,980
|
cpp
|
color_wheel.cpp
|
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "yet_another_list.h"
#define PI 3.1415926535898
#define GET_RED(ANGLE) get_function_by_angle(ANGLE)(ANGLE)
#define GET_GREEN(ANGLE) get_function_by_angle(ANGLE - 2 * PI/3)(ANGLE)
#define GET_BLUE(ANGLE) get_function_by_angle(ANGLE - 4 * PI/3)(ANGLE)
#define GET_COLOR(HUE, VALUE, SATURATION) (max(HUE, (1 - SATURATION)) * VALUE)
#define SET_RGB(R, G, B, ANGLE, VALUE, SATURATION)\
R = GET_COLOR(GET_RED(ANGLE), VALUE, SATURATION);\
G = GET_COLOR(GET_GREEN(ANGLE), VALUE, SATURATION);\
B = GET_COLOR(GET_BLUE(ANGLE), VALUE, SATURATION)
#define TRANSFORM_X (double)(((x - (double)(glutGet(GLUT_WINDOW_WIDTH)/2))) / PIX_COORD_SCALE) // mouse coordinate to Cartesian coordinate
#define TRANSFORM_Y -((double)(((y - (double)(glutGet(GLUT_WINDOW_HEIGHT)/2))) / PIX_COORD_SCALE)) // mouse coordinate to Cartesian coordinate
#define initialWindowWidth 640
typedef struct CL_POINT{
double x;
double y;
double r;
double g;
double b;
}CL_POINT;
double PIX_COORD_SCALE = initialWindowWidth / 20;
int rund = 100;
double hue[3], value = 1, satur = 1, siz = 10, thik = 2,
tempHUE[3] = {};
/*****************************************************************************************/
//Equation by parts.
YALIST* function_wheel = new_yalist();
double get_color_full(double angle){
return 1;
}
double get_color_fraction(double angle){//Do not touch
return (cos(3 * angle - PI) + 1)/2;
}
double get_color_none(double angle){
return 0;
}
//HAHAHAHAHAHAHAHAHA, HAHAHAH. TRY TO FIGURE THIS ONE OUT!
double (*get_function_by_angle(double ang))(double){//more or less OK, don't push it tho
ang = fabs(ang);
int index = (double)(ang/(2*PI))*(double)function_wheel->length;
return (double (*)(double))yalget(function_wheel, index);
}
/*****************************************************************************************/
//Utility
//![0 -- 1] real random
double simpleRand(void){
return (double)(rand()%1000)/1000;
}
void toClipboard(char* st){
OpenClipboard(0);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, strlen(st) + 1);
if(!hg){
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), st, strlen(st));
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
//!float RGB to 0x######
char* get_hex_color(double r, double g, double b){
int rbyte = r*255, gbyte = g*255, bbyte = b*255;
char rhex[3], ghex[3], bhex[3];
itoa(rbyte, rhex, 16);
if(strlen(rhex) < 2) sprintf(rhex, "%s%s", "0", rhex);
itoa(gbyte, ghex, 16);
if(strlen(ghex) < 2) sprintf(ghex, "%s%s", "0", ghex);
itoa(bbyte, bhex, 16);
if(strlen(bhex) < 2) sprintf(bhex, "%s%s", "0", bhex);
char* out = (char*)malloc(7);
sprintf(out, "%s%s%s", rhex, ghex, bhex);
return out;
}
void printColor(void)
{
char* colorHex = get_hex_color(GET_COLOR(hue[0], value, satur),
GET_COLOR(hue[1], value, satur),
GET_COLOR(hue[2], value, satur));
printf("%s\n", colorHex);
toClipboard(colorHex);//!Optional.
free(colorHex);
memccpy(tempHUE, hue, 3, sizeof(double));
return;
}
void simple_quad(CL_POINT start, CL_POINT finish){
glPushMatrix();
glBegin(GL_QUADS);
glColor3f(start.r, start.g, start.b);
glVertex2f(start.x, start.y); //
glVertex2f(finish.x, start.y); //
glColor3f(finish.r, finish.g, finish.b);
glVertex2f(finish.x, finish.y); //
glVertex2f(start.x, finish.y); //
glEnd();
glPopMatrix();
}
void wheel(double thi, double radius, double offset_x, double offset_y, int roundness){//"legacy"
int i, j=0;
double r, g, b;
for(i = 0; i < roundness+2; i++){
r = cos(i*((2*PI/roundness)) - PI/2); r = (r > 0) * r;
g = cos(i*((2*PI/roundness)) - 7*PI/6); g = (g > 0) * g;
b = cos(i*((2*PI/roundness)) - 11*PI/6); b = (b > 0) * b;
glColor3d(r, g, b);
glVertex2d(cos(i*PI/(roundness/2)) * (radius+thi*j) + offset_x,
sin(i*PI/(roundness/2)) * (radius+thi*j) + offset_y);
j = !j;
}
}
void color_wheel(double rad, double thi, double off_x, double off_y, int steps)
{
int i, j=0;
double r, g, b, ang, mult;
for(i = 0; i < steps+2; i++){
ang = i * PI/(steps/2); mult = rad + thi * j;
SET_RGB(r, g, b, ang, value, satur);
glColor3d(r, g, b);
//>For polar-------(<r|g|b>)
glVertex2d(cos(ang) * mult + off_x,
sin(ang) * mult + off_y);
j = !j;
}
}
void inverse_wheel(double rad, double thi, double off_x, double off_y, int steps)
{
int i, j=0;
double r, g, b, ang;
for(i = 0; i < steps+2; i++){
ang = i*PI/(steps/2);
r = 1 - GET_COLOR(hue[0], value, satur);
g = 1 - GET_COLOR(hue[1], value, satur);
b = 1 - GET_COLOR(hue[2], value, satur);
glColor3d(r, g, b);
glVertex2d(cos(ang) * (rad+thi*j) + off_x,
sin(ang) * (rad+thi*j) + off_y);
j = !j;
}
}
void value_slider(double height)
{
simple_quad((CL_POINT){-17.5, height,
max(hue[0], 1 - satur),
max(hue[1], 1 - satur),
max(hue[2], 1 - satur)},
(CL_POINT){-19, -height,
0, 0, 0});
}
void satur_slider(double height)
{
simple_quad((CL_POINT){17.5, height,
hue[0] * value, hue[1] * value, hue[2] * value},
(CL_POINT){19, -height,
1, 1, 1});
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3d(1,0,0);
glBegin(GL_TRIANGLE_STRIP);
//wheel(2, 2, 0, 0, rund);//segunda feira é dia de reinventar a roda.
color_wheel(siz, thik, 0, 0, rund);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
inverse_wheel(siz/5, thik/2, 0, 0, rund);
glEnd();
value_slider(siz+thik);
satur_slider(siz+thik);
glLoadIdentity();
gluOrtho2D(-20, 20, -(double)glutGet(GLUT_WINDOW_HEIGHT)/(double)glutGet(GLUT_WINDOW_WIDTH)*20, (double)glutGet(GLUT_WINDOW_HEIGHT)/(double)glutGet(GLUT_WINDOW_WIDTH)*20);
glutSwapBuffers();
}
void setBG(void)
{
glClearColor( GET_COLOR(hue[0], value, satur),
GET_COLOR(hue[1], value, satur),
GET_COLOR(hue[2], value, satur),0);
}
void pickHue(double x, double y)
{
double incl, angle;
if(y == 0)
{
if(x != 0)//horizontal
angle = (x > 0)? 0: PI;
else//center
{
hue[0] = 0;
hue[1] = 0;
hue[2] = 0;
glutPostRedisplay();
return;
}
}
else if(x == 0)//vertical
angle = (y > 0)? PI/2: 3*PI/2;
else{//any other
incl = y/x;
angle = atan(incl);
if(x < 0)
angle += PI;
}
hue[0] = GET_RED(angle);
hue[1] = GET_GREEN(angle);
hue[2] = GET_BLUE(angle);
}
double pickBar(double x, double range)//pick value on range, centered.
{
return (abs(x) >= range)? (x > 0): ((x / range) + 1)/2;//one-liner ;P
}
void pick(int x, int y)//btw it's matiz in brazillian.
{
PIX_COORD_SCALE = glutGet(GLUT_WINDOW_WIDTH)/39.999;
double rel_x = TRANSFORM_X, rel_y = TRANSFORM_Y;
if((rel_x <= -17.5) && (rel_x >= -19) && (abs(rel_y) <= (siz + thik + 0.25)))//shorten?
value = pickBar(rel_y, siz + thik);
else if((rel_x >= 17.5) && (rel_x <= 19) && (abs(rel_y) <= (siz + thik + 0.25)))
satur = pickBar(rel_y, siz + thik);
else if(sqrt((rel_x*rel_x) + (rel_y*rel_y)) <= (siz/5))
return printColor();
else
pickHue(rel_x, rel_y);//too specific to generalize.
setBG();
//printf("Angle = [%lf]deg\n", angle/PI*180);
glutPostRedisplay();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case '-':
rund--;
break;
case '+':
rund++;
break;
case 'r':
pick((int)(simpleRand()*(double)glutGet(GLUT_WINDOW_WIDTH)), (int)(simpleRand()*(double)glutGet(GLUT_WINDOW_HEIGHT)));//hold r :)
glutPostRedisplay();
return;
case ' ' :
case '\r':
return printColor();
case 27 :
case 'q':
yalclear(function_wheel);
free(function_wheel);
exit(0);
break;
}
pick(x, y);//optional here, but welcome.
glutPostRedisplay();
}
static void mou(int button, int state, int x, int y){
if(state == GLUT_DOWN)
pick(x, y);
}
static void mot(int x, int y){
pick(x, y);
}
static void idle(void)
{
glutPostRedisplay();
}
void registerPolarFunctions(void){
yaladd(function_wheel, (void*)get_color_full, 0);//HECK YE
yaladd(function_wheel, (void*)get_color_fraction, -1);//enqueue from here, I'm just not sure "yet another list's" enqueue is OK
yaladd(function_wheel, (void*)get_color_none, -1);
yaladd(function_wheel, (void*)get_color_none, -1);
yaladd(function_wheel, (void*)get_color_fraction, -1);
yaladd(function_wheel, (void*)get_color_full, -1);
}
int main(int argc, char *argv[])
{
registerPolarFunctions();
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("Color wheel");
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glutMouseFunc(mou);
glutMotionFunc(mot);
//glutPassiveMotionFunc(mot);//for playing around
glClearColor(1,1,1,1);
glutMainLoop();
return EXIT_SUCCESS;
}
|
9f1bc7bdca77f5084697196cba898b3fc832507c
|
fdb54ad118ebdc572ed223dc0f3686d4940c803b
|
/cecservice/cec_manager.cc
|
cca6d9bc8920b85cb0a1a6f4ca1a6ad124d6e8de
|
[
"BSD-3-Clause"
] |
permissive
|
ComputerStudyBoard/chromiumos-platform2
|
6589b7097ef226f811f55f8a4dd6a890bf7a29bb
|
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
|
refs/heads/master
| 2022-03-27T22:35:41.013481
| 2018-12-06T09:08:40
| 2018-12-06T09:08:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,489
|
cc
|
cec_manager.cc
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "cecservice/cec_manager.h"
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <base/bind.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/strings/string_util.h>
namespace cecservice {
namespace {
std::string PowerStatusToString(TvPowerStatus status) {
switch (status) {
case kTvPowerStatusError:
return "error";
case kTvPowerStatusAdapterNotConfigured:
return "adapter not configured";
case kTvPowerStatusNoTv:
return "no TV";
case kTvPowerStatusOn:
return "on";
case kTvPowerStatusStandBy:
return "standby";
case kTvPowerStatusToOn:
return "to on";
case kTvPowerStatusToStandBy:
return "to standby";
case kTvPowerStatusUnknown:
return "unknown";
}
}
std::string PowerStatusVectorToString(
const std::vector<TvPowerStatus>& vector) {
std::vector<std::string> strings;
std::transform(vector.begin(), vector.end(), std::back_inserter(strings),
PowerStatusToString);
return "[" + base::JoinString(strings, ", ") + "]";
}
} // namespace
struct CecManager::TvPowerStatusResult {
// Set to true if the response has been received from the device.
bool received = false;
// The actual power status received.
TvPowerStatus power_status = kTvPowerStatusUnknown;
};
struct CecManager::TvsPowerStatusQuery {
// Callback to invoke when all responses have been received.
GetTvsPowerStatusCallback callback;
// Device nodes the request has been sent to.
std::map<base::FilePath, TvPowerStatusResult> responses;
};
CecManager::CecManager(const UdevFactory& udev_factory,
const CecDeviceFactory& cec_factory)
: cec_factory_(cec_factory) {
udev_ = udev_factory.Create(
base::Bind(&CecManager::OnDeviceAdded, weak_factory_.GetWeakPtr()),
base::Bind(&CecManager::OnDeviceRemoved, weak_factory_.GetWeakPtr()));
LOG_IF(FATAL, !udev_) << "Failed to create udev";
EnumerateAndAddExistingDevices();
}
CecManager::~CecManager() = default;
void CecManager::GetTvsPowerStatus(GetTvsPowerStatusCallback callback) {
LOG(INFO) << "Received get TVs power status request";
if (devices_.empty()) {
std::move(callback).Run({});
return;
}
TvsPowerStatusQuery query{std::move(callback)};
for (auto& kv : devices_) {
query.responses.insert(std::make_pair(kv.first, TvPowerStatusResult()));
}
QueryId id = next_query_id_++;
tv_power_status_queries_.insert(std::make_pair(id, std::move(query)));
for (auto& kv : devices_) {
kv.second->GetTvPowerStatus(base::Bind(&CecManager::OnTvPowerResponse,
weak_factory_.GetWeakPtr(), id,
kv.first));
}
}
void CecManager::SetWakeUp() {
LOG(INFO) << "Received wake up request";
for (auto& kv : devices_) {
kv.second->SetWakeUp();
}
}
void CecManager::SetStandBy() {
LOG(INFO) << "Received standby request";
for (auto& kv : devices_) {
kv.second->SetStandBy();
}
}
void CecManager::OnTvPowerResponse(QueryId id,
base::FilePath device_path,
TvPowerStatus result) {
auto iterator = tv_power_status_queries_.find(id);
CHECK(iterator != tv_power_status_queries_.end());
TvsPowerStatusQuery& query = iterator->second;
query.responses[device_path] = {true, result};
if (MaybeRespondToTvsPowerStatusQuery(query)) {
tv_power_status_queries_.erase(iterator);
}
}
bool CecManager::MaybeRespondToTvsPowerStatusQuery(
const TvsPowerStatusQuery& query) {
std::vector<TvPowerStatus> result;
for (auto& response : query.responses) {
const TvPowerStatusResult& status = response.second;
if (!status.received) {
return false;
}
result.push_back(status.power_status);
}
LOG(INFO) << "Responding to power status request with: "
<< PowerStatusVectorToString(result);
std::move(query.callback).Run(result);
return true;
}
void CecManager::OnDeviceAdded(const base::FilePath& device_path) {
LOG(INFO) << "New device: " << device_path.value();
AddNewDevice(device_path);
}
void CecManager::OnDeviceRemoved(const base::FilePath& device_path) {
LOG(INFO) << "Removing device: " << device_path.value();
devices_.erase(device_path);
auto iterator = tv_power_status_queries_.begin();
while (iterator != tv_power_status_queries_.end()) {
TvsPowerStatusQuery& query = iterator->second;
query.responses.erase(device_path);
if (MaybeRespondToTvsPowerStatusQuery(query)) {
iterator = tv_power_status_queries_.erase(iterator);
} else {
++iterator;
}
}
}
void CecManager::EnumerateAndAddExistingDevices() {
std::vector<base::FilePath> paths;
if (!udev_->EnumerateDevices(&paths)) {
LOG(FATAL) << "Failed to enumerate devices.";
}
for (const auto& path : paths) {
AddNewDevice(path);
}
}
void CecManager::AddNewDevice(const base::FilePath& path) {
std::unique_ptr<CecDevice> device = cec_factory_.Create(path);
if (device) {
LOG(INFO) << "Added new device: " << path.value();
devices_[path] = std::move(device);
} else {
LOG(WARNING) << "Failed to add device: " << path.value();
}
}
} // namespace cecservice
|
04b7e2d68cda457da41539711f5b690e0ade2c1c
|
eb83767e1c8a8ba94b0b736836b5d7f4656f8b87
|
/batle-sim/src/OutputConsole.h
|
6881ab089d206b2d45ab5de46c6351e01d688142
|
[] |
no_license
|
HermanTS/serenity-corp
|
6dd09c2c2249b3f4fc0ac9cb9b3c66e780f4089b
|
26e9710c7cbc4d3ae7d6db18e365c78d27144e6c
|
refs/heads/master
| 2020-12-02T05:16:09.794317
| 2020-02-28T18:09:42
| 2020-02-28T18:09:42
| 230,901,538
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 397
|
h
|
OutputConsole.h
|
/*
* OutputConsole.h
*
* Created on: 21 февр. 2020 г.
* Author: gstsvetkov
*/
#ifndef SRC_OUTPUTCONSOLE_H_
#define SRC_OUTPUTCONSOLE_H_
#include "window-widget.h"
class OutputConsole: public WindowWidget
{
public:
OutputConsole();
virtual ~OutputConsole();
private:
void CustomDraw(struct nkc* nkcHandle);
};
#endif /* SRC_OUTPUTCONSOLE_H_ */
|
d722b72bb420ef9f809880562c8a11cf61ba5124
|
eee0588d6c92b1bc093716ac84969a47a8159e38
|
/Dia/DiaWindow/SystemHandle.h
|
1924b6fa3c89c62025b0c3b698a86d9eb22b557b
|
[] |
no_license
|
LenihanConor/Cluiche
|
bf919ef721d901ba2a23646e70444803e0fe5781
|
1b65c5861a2354a81fbf1ed63fb0e7620b635d0d
|
refs/heads/master
| 2023-06-28T19:45:52.811023
| 2023-06-20T18:20:58
| 2023-06-20T18:20:58
| 37,433,420
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 564
|
h
|
SystemHandle.h
|
////////////////////////////////////////////////////////////////////////////////
// Filename: WindowHandle.h: Define a low-level window handle type, specific to
////////////////////////////////////////////////////////////////////////////////
#pragma once
#if defined(WIN32)
struct HWND__;
#endif
namespace Dia
{
namespace Window
{
#if defined(WIN32)
// Window handle is HWND (HWND__*) on Windows
typedef HWND__* SystemHandle;
#elif defined(ANDROID_OS)
// Window handle is ANativeWindow (void*) on Android
typedef void* SystemHandle;
#endif
}
}
|
4f19731ea6e594d5eb37039c35e4c050f0c266a9
|
a9e682aefdf4fb981f3aecb0b779068b25a2becc
|
/polygonDrawingDemo/polygonDrawingDemo.cpp
|
79d3a29134cc7e31de2d834bccdd78386db0d70e
|
[] |
no_license
|
cdk-king/T2D
|
a528d79036c2c399f4786c6dfb709a46f6bb741b
|
76529a6ddd2fd88368f077e4ebfbd52cd4ca8c96
|
refs/heads/master
| 2020-05-15T18:49:03.778033
| 2019-06-09T18:09:09
| 2019-06-09T18:10:27
| 182,439,705
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,120
|
cpp
|
polygonDrawingDemo.cpp
|
// DEMO4_5.CPP - Polygon drawing demo
// INCLUDES ///////////////////////////////////////////////
#define WIN32_LEAN_AND_MEAN // just say no to MFC
#include <windows.h> // include all the windows headers
#include <windowsx.h> // include useful macros
#include <mmsystem.h> // very important and include WINMM.LIB too!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// DEFINES ////////////////////////////////////////////////
// defines for windows
#define WINDOW_CLASS_NAME "WINCLASS1"
#define WINDOW_WIDTH 400
#define WINDOW_HEIGHT 300
// MACROS /////////////////////////////////////////////////
#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
// GLOBALS ////////////////////////////////////////////////
HWND main_window_handle = NULL; // globally track main window
HINSTANCE hinstance_app = NULL; // globally track hinstance
char buffer[80]; // general printing buffer
// FUNCTIONS //////////////////////////////////////////////
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam)
{
// this is the main message handler of the system
PAINTSTRUCT ps; // used in WM_PAINT
HDC hdc; // handle to a device context
char buffer[80]; // used to print strings
// what is the message
switch (msg)
{
case WM_CREATE:
{
// do initialization stuff here
// return success
return(0);
} break;
case WM_PAINT:
{
// simply validate the window
hdc = BeginPaint(hwnd, &ps);
// end painting
EndPaint(hwnd, &ps);
// return success
return(0);
} break;
case WM_DESTROY:
{
// kill the application, this sends a WM_QUIT message
PostQuitMessage(0);
// return success
return(0);
} break;
default:break;
} // end switch
// process any messages that we didn't take care of
return (DefWindowProc(hwnd, msg, wparam, lparam));
} // end WinProc
// WINMAIN ////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hinstance,
HINSTANCE hprevinstance,
LPSTR lpcmdline,
int ncmdshow)
{
WNDCLASSEX winclass; // this will hold the class we create
HWND hwnd; // generic window handle
MSG msg; // generic message
HDC hdc; // graphics device context
// first fill in the window class stucture
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_DBLCLKS | CS_OWNDC |
CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc = WindowProc;
winclass.cbClsExtra = 0;
winclass.cbWndExtra = 0;
winclass.hInstance = hinstance;
winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winclass.lpszMenuName = NULL;
winclass.lpszClassName = WINDOW_CLASS_NAME;
winclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
// save hinstance in global
hinstance_app = hinstance;
// register the window class
if (!RegisterClassEx(&winclass))
return(0);
// create the window
if (!(hwnd = CreateWindowEx(NULL, // extended style
WINDOW_CLASS_NAME, // class
"Polygon Drawing Demo", // title
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
0, 0, // initial x,y
WINDOW_WIDTH, // initial width
WINDOW_HEIGHT,// initial height
NULL, // handle to parent
NULL, // handle to menu
hinstance,// instance of this application
NULL))) // extra creation parms
return(0);
// save main window handle
main_window_handle = hwnd;
// get the graphics device context
hdc = GetDC(hwnd);
// enter main event loop, but this time we use PeekMessage()
// instead of GetMessage() to retrieve messages
while (TRUE)
{
// test if there is a message in queue, if so get it
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// test if this is a quit
if (msg.message == WM_QUIT)
break;
// translate any accelerator keys
TranslateMessage(&msg);
// send the message to the window proc
DispatchMessage(&msg);
} // end if
// select random colors for polygon
HPEN pen_color = CreatePen(PS_SOLID, 1, RGB(rand() % 256, rand() % 256, rand() % 256));
HBRUSH brush_color = CreateSolidBrush(RGB(rand() % 256, rand() % 256, rand() % 256));
// select them into dc
SelectObject(hdc, pen_color);
SelectObject(hdc, brush_color);
// now create list of random points for polygon
int num_points = 3 + rand() % 8;
// this will hold the point list
POINT point_list[10];
// create array of points
for (int index = 0; index < num_points; index++)
{
// set next random point in list
point_list[index].x = rand() % WINDOW_WIDTH;
point_list[index].y = rand() % WINDOW_HEIGHT;
} // end for index
// draw the polygon
Polygon(hdc, point_list, num_points);
// let user see it
Sleep(500);
// main game processing goes here
if (KEYDOWN(VK_ESCAPE))
SendMessage(hwnd, WM_CLOSE, 0, 0);
} // end while
// release the device context
ReleaseDC(hwnd, hdc);
// return to Windows like this
return(msg.wParam);
} // end WinMain
///////////////////////////////////////////////////////////
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.