hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a2b0ec13c962e69c833e00d65520b8fd008cab14
| 1,204
|
cpp
|
C++
|
semaphore/semA.cpp
|
chengwenwu/IPC
|
2e01f397d15b2d2911f3494fc98c9ca5e8d274a9
|
[
"MIT"
] | null | null | null |
semaphore/semA.cpp
|
chengwenwu/IPC
|
2e01f397d15b2d2911f3494fc98c9ca5e8d274a9
|
[
"MIT"
] | null | null | null |
semaphore/semA.cpp
|
chengwenwu/IPC
|
2e01f397d15b2d2911f3494fc98c9ca5e8d274a9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "sem.hpp"
using namespace std;
int main()
{
// 获取共享内存
int shmId = shmget(ftok(SHM_FILE, PROJ_ID), SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
if (shmId == -1) {
perror("shmget:");
return 0;
}
// 绑定共享内存地址
char *shmMemory = (char *)shmat(shmId, NULL, 0);
// 获取信号量,并设置默认值
int semIdR = CreateSem(A_READ_FILE, 0);
int semIdW = CreateSem(A_WRITE_FILE, 0);
if (semIdR == -1 || semIdW == -1) {
perror("CreateSem:");
return -1;
}
sleep(3);
// 向共享内存写数据
sprintf(shmMemory, "A");
if (SemV(semIdW) == -1) {
perror("SemV w error:");
return 0;
}
cout << "A write success\n";
// 等待进程B,写B进来
if (SemP(semIdR) == -1) {
perror("SemV R error:");
return 0;
}
if (memcmp(shmMemory, "B", strlen("B")) == 0) {
cout << "read from mem: " << shmMemory << endl;
}
if (SemTimerP(semIdR, 5) == -1) {
perror("timer P:");
}
cout << "A End\n";
// 解绑内存
shmdt(shmMemory);
// 释放信号量
semctl(semIdR, 0, IPC_RMID);
semctl(semIdW, 0, IPC_RMID);
// 释放共享内存
shmctl(shmId, IPC_RMID, NULL);
return 0;
}
| 19.737705
| 87
| 0.516611
|
chengwenwu
|
a2b4e7193801736e204ef14cc464d9dae226c518
| 21,840
|
cpp
|
C++
|
src/TextWriter.cpp
|
arielscarpinelli/pianogame
|
abca8a622afa4bb1b63aa1c457a0d36488033b4f
|
[
"MIT"
] | null | null | null |
src/TextWriter.cpp
|
arielscarpinelli/pianogame
|
abca8a622afa4bb1b63aa1c457a0d36488033b4f
|
[
"MIT"
] | null | null | null |
src/TextWriter.cpp
|
arielscarpinelli/pianogame
|
abca8a622afa4bb1b63aa1c457a0d36488033b4f
|
[
"MIT"
] | null | null | null |
// Copyright (c)2007 Nicholas Piegdon
// See license.txt for license information
#include <map>
#include "TextWriter.h"
#include "Renderer.h"
#include "PianoGameError.h"
#include "os_graphics.h"
#ifdef WIN32
// TODO: This should be deleted at shutdown
static std::map<int, HFONT> font_handle_lookup;
static int next_call_list_start = 1;
#else
// TODO: This should be deleted at shutdown
GLuint Texture2DCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pColor,
CGSize& rSize);
#endif
// TODO: This should be deleted at shutdown
static std::map<int, int> font_size_lookup;
TextWriter::TextWriter(int in_x, int in_y, Renderer &in_renderer, bool in_centered, int in_size, std::wstring fontname) :
x(in_x), y(in_y), size(in_size), original_x(0), last_line_height(0), centered(in_centered), renderer(in_renderer)
{
x += renderer.m_xoffset;
original_x = x;
y += renderer.m_yoffset;
#ifdef WIN32
Context c = renderer.m_context;
point_size = MulDiv(size, GetDeviceCaps(c, LOGPIXELSY), 72);
HFONT font = 0;
if (font_size_lookup[in_size] == 0)
{
// Set up the LOGFONT structure
LOGFONT logical_font;
logical_font.lfHeight = get_point_size();
logical_font.lfWidth = 0;
logical_font.lfEscapement = 0;
logical_font.lfOrientation = 0;
logical_font.lfWeight = FW_NORMAL;
logical_font.lfItalic = false;
logical_font.lfUnderline = false;
logical_font.lfStrikeOut = false;
logical_font.lfCharSet = ANSI_CHARSET;
logical_font.lfOutPrecision = OUT_DEFAULT_PRECIS;
logical_font.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logical_font.lfQuality = PROOF_QUALITY;
logical_font.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lstrcpy(logical_font.lfFaceName, fontname.c_str());
font = CreateFontIndirect(&logical_font);
HFONT previous_font = (HFONT)SelectObject(c, font);
wglUseFontBitmaps(c, 0, 128, next_call_list_start);
font_size_lookup[in_size] = next_call_list_start;
font_handle_lookup[in_size] = font;
next_call_list_start += 130;
SelectObject(c, previous_font);
}
#else
// TODO: is this sufficient?
point_size = size;
#endif
}
TextWriter::~TextWriter()
{
}
int TextWriter::get_point_size()
{
return point_size;
}
TextWriter& TextWriter::next_line()
{
y += std::max(last_line_height, get_point_size());
x = original_x;
last_line_height = 0;
return *this;
}
TextWriter& Text::operator<<(TextWriter& tw) const
{
int draw_x;
int draw_y;
// TODO: This isn't Unicode!
std::string narrow(m_text.begin(), m_text.end());
#ifndef WIN32
CGFloat color[4] = {m_color.r / 255.0f, m_color.g / 255.0f, m_color.b / 255.0f, m_color.a / 255.0f};
CGSize size;
GLuint texture = Texture2DCreateFromString(narrow.c_str(), nullptr, tw.size, tw.centered ? kCTTextAlignmentCenter : kCTTextAlignmentLeft, color, size);
draw_x = size.width;
draw_y = size.height;
#endif
calculate_position_and_advance_cursor(tw, &draw_x, &draw_y);
glPushMatrix();
#ifdef WIN32
glBindTexture(GL_TEXTURE_2D, 0);
tw.renderer.SetColor(m_color);
glListBase(font_size_lookup[tw.size]);
glRasterPos2i(draw_x, draw_y + tw.size);
glCallLists(static_cast<int>(narrow.length()), GL_UNSIGNED_BYTE, narrow.c_str());
#else
tw.renderer.DrawTextTextureQuad(texture, draw_x, draw_y, size.width, size.height);
//glDeleteTextures(1, &texture);
#endif
glPopMatrix();
// TODO: Should probably delete these on shutdown.
//glDeleteLists(1000, 128);
return tw;
}
void Text::calculate_position_and_advance_cursor(TextWriter &tw, int *out_x, int *out_y) const
{
#ifdef WIN32
const long options = DT_LEFT | DT_NOPREFIX;
Context c = tw.renderer.m_context;
int previous_map_mode = SetMapMode(c, MM_TEXT);
HFONT font = font_handle_lookup[tw.size];
// Create the font we want to use, and swap it out with
// whatever is currently in there, along with our color
HFONT previous_font = (HFONT)SelectObject(c, font);
// Call DrawText to find out how large our text is
RECT drawing_rect = { tw.x, tw.y, 0, 0 };
tw.last_line_height = DrawText(c, m_text.c_str(), int(m_text.length()), &drawing_rect, options | DT_CALCRECT);
// Return the hdc settings to their previous setting
SelectObject(c, previous_font);
SetMapMode(c, previous_map_mode);
#else
Rect drawing_rect = { tw.y, tw.x, tw.y + *out_y, tw.x + *out_x};
#endif
// Update the text-writer with post-draw coordinates
if (tw.centered) drawing_rect.left -= (drawing_rect.right - drawing_rect.left) / 2;
if (!tw.centered) tw.x += drawing_rect.right - drawing_rect.left;
// Tell the draw function where to put the text
*out_x = drawing_rect.left;
*out_y = drawing_rect.top;
}
TextWriter& operator<<(TextWriter& tw, const Text& t)
{
return t.operator <<(tw);
}
TextWriter& newline(TextWriter& tw)
{
return tw.next_line();
}
TextWriter& operator<<(TextWriter& tw, const std::wstring& s) { return tw << Text(s, White); }
TextWriter& operator<<(TextWriter& tw, const int& i) { return tw << Text(i, White); }
TextWriter& operator<<(TextWriter& tw, const unsigned int& i) { return tw << Text(i, White); }
TextWriter& operator<<(TextWriter& tw, const long& l) { return tw << Text(l, White); }
TextWriter& operator<<(TextWriter& tw, const unsigned long& l) { return tw << Text(l, White); }
// Create a bitmap context from a string, font, justification, and font size
static CGContextRef CGContextCreateFromAttributedString(CFAttributedStringRef pAttrString,
const CFRange& rRange,
CGColorSpaceRef pColorspace,
CGSize& rSize)
{
CGContextRef pContext = nullptr;
if(pAttrString != nullptr)
{
// Acquire a frame setter
CTFramesetterRef pFrameSetter = CTFramesetterCreateWithAttributedString(pAttrString);
if(pFrameSetter != nullptr)
{
// Create a path for layout
CGMutablePathRef pPath = CGPathCreateMutable();
if(pPath != nullptr)
{
CFRange range;
CGSize constraint = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
// Get the CoreText suggested size from our framesetter
rSize = CTFramesetterSuggestFrameSizeWithConstraints(pFrameSetter,
rRange,
nullptr,
constraint,
&range);
// Set path bounds
CGRect bounds = CGRectMake(0.0f,
0.0f,
rSize.width,
rSize.height);
// Bound the path
CGPathAddRect(pPath, nullptr, bounds);
// Layout the attributed string in a frame
CTFrameRef pFrame = CTFramesetterCreateFrame(pFrameSetter, range, pPath, nullptr);
if(pFrame != nullptr)
{
// Compute bounds for the bitmap context
size_t width = size_t(rSize.width);
size_t height = size_t(rSize.height);
size_t stride = sizeof(GLuint) * width;
// No explicit backing-store allocation here. We'll let the
// context allocate the storage for us.
pContext = CGBitmapContextCreate(nullptr,
width,
height,
8,
stride,
pColorspace,
kCGImageAlphaPremultipliedLast);
if(pContext != nullptr)
{
// Use this for vertical reflection
CGContextTranslateCTM(pContext, 0.0, height);
CGContextScaleCTM(pContext, 1.0, -1.0);
// Draw the frame into a bitmap context
CTFrameDraw(pFrame, pContext);
// Flush the context
CGContextFlush(pContext);
} // if
// Release the frame
CFRelease(pFrame);
} // if
CFRelease(pPath);
} // if
CFRelease(pFrameSetter);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Create an attributed string from a CF string, font, justification, and font size
static CFMutableAttributedStringRef CFMutableAttributedStringCreate(CFStringRef pString,
CFStringRef pFontNameSrc,
CGColorRef pComponents,
const CGFloat& rFontSize,
const CTTextAlignment nAlignment,
CFRange *pRange)
{
CFMutableAttributedStringRef pAttrString = nullptr;
if(pString != nullptr)
{
// Paragraph style setting structure
const GLuint nCntStyle = 2;
// For single spacing between the lines
const CGFloat nLineHeightMultiple = 1.0f;
// Paragraph settings with alignment and style
CTParagraphStyleSetting settings[nCntStyle] =
{
{
kCTParagraphStyleSpecifierAlignment,
sizeof(CTTextAlignment),
&nAlignment
},
{
kCTParagraphStyleSpecifierLineHeightMultiple,
sizeof(CGFloat),
&nLineHeightMultiple
}
};
// Create a paragraph style
CTParagraphStyleRef pStyle = CTParagraphStyleCreate(settings, nCntStyle);
if(pStyle != nullptr)
{
// If the font name is nullptr default to Helvetica
CFStringRef pFontNameDst = (pFontNameSrc) ? pFontNameSrc : CFSTR("Helvetica");
// Prepare font
CTFontRef pFont = CTFontCreateWithName(pFontNameDst, rFontSize, nullptr);
if(pFont != nullptr)
{
// Set attributed string properties
const GLuint nCntDict = 3;
CFStringRef keys[nCntDict] =
{
kCTParagraphStyleAttributeName,
kCTFontAttributeName,
kCTForegroundColorAttributeName
};
CFTypeRef values[nCntDict] =
{
pStyle,
pFont,
pComponents
};
// Create a dictionary of attributes for our string
CFDictionaryRef pAttributes = CFDictionaryCreate(nullptr,
(const void **)&keys,
(const void **)&values,
nCntDict,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if(pAttributes != nullptr)
{
// Creating a mutable attributed string
pAttrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
if(pAttrString != nullptr)
{
// Set a mutable attributed string with the input string
CFAttributedStringReplaceString(pAttrString, CFRangeMake(0, 0), pString);
// Compute the mutable attributed string range
*pRange = CFRangeMake(0, CFAttributedStringGetLength(pAttrString));
// Set the attributes
CFAttributedStringSetAttributes(pAttrString, *pRange, pAttributes, 0);
} // if
CFRelease(pAttributes);
} // if
CFRelease(pFont);
} // if
CFRelease(pStyle);
} // if
} // if
return pAttrString;
} // CFMutableAttributedStringCreate
// Create a 2D texture
static GLuint GLUTexture2DCreate(const GLuint& rWidth,
const GLuint& rHeight,
const GLvoid * const pPixels)
{
GLuint nTID = 0;
// Greate a texture
glGenTextures(1, &nTID);
if(nTID)
{
// Bind a texture with ID
glBindTexture(GL_TEXTURE_2D, nTID);
// Set texture properties (including linear mipmap)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Initialize the texture
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
rWidth,
rHeight,
0,
GL_RGBA,
GL_UNSIGNED_INT_8_8_8_8_REV,
pPixels);
// Generate mipmaps
glGenerateMipmap(GL_TEXTURE_2D);
// Discard
glBindTexture(GL_TEXTURE_2D, 0);
} // if
return nTID;
} // GLUTexture2DCreate
// Create a texture from a bitmap context
static GLuint GLUTexture2DCreateFromContext(CGContextRef pContext)
{
GLuint nTID = 0;
if(pContext != nullptr)
{
GLuint nWidth = GLuint(CGBitmapContextGetWidth(pContext));
GLuint nHeight = GLuint(CGBitmapContextGetHeight(pContext));
const GLvoid *pPixels = CGBitmapContextGetData(pContext);
nTID = GLUTexture2DCreate(nWidth, nHeight, pPixels);
// Was there a GL error?
GLenum nErr = glGetError();
if(nErr != GL_NO_ERROR)
{
glDeleteTextures(1, &nTID);
throw PianoGameError(L"OpenGL error trying to create texture");
} // if
} // if
return nTID;
} // GLUTexture2DCreateFromContext
// Create a bitmap context from a core foundation string, font,
// justification, and font size
static CGContextRef CGContextCreateFromString(CFStringRef pString,
CFStringRef pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pComponents,
CGSize &rSize)
{
CGContextRef pContext = nullptr;
if(pString != nullptr)
{
// Get a generic linear RGB color space
CGColorSpaceRef pColorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGBLinear);
if(pColorspace != nullptr)
{
// Create a white color reference
CGColorRef pColor = CGColorCreate(pColorspace, pComponents);
if(pColor != nullptr)
{
// Creating a mutable attributed string
CFRange range;
CFMutableAttributedStringRef pAttrString = CFMutableAttributedStringCreate(pString,
pFontName,
pColor,
rFontSize,
rAlignment,
&range);
if(pAttrString != nullptr)
{
// Create a context from our attributed string
pContext = CGContextCreateFromAttributedString(pAttrString,
range,
pColorspace,
rSize);
CFRelease(pAttrString);
} // if
CFRelease(pColor);
} // if
CFRelease(pColorspace);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Create a bitmap context from a c-string, font, justification, and font size
static CGContextRef CGContextCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pComponents,
CGSize& rSize)
{
CGContextRef pContext = nullptr;
if(pString != nullptr)
{
CFStringRef pCFString = CFStringCreateWithCString(kCFAllocatorDefault,
pString,
kCFStringEncodingASCII);
if(pCFString != nullptr)
{
const GLchar *pFontString = (pFontName) ? pFontName : "Helvetica";
CFStringRef pFontCFString = CFStringCreateWithCString(kCFAllocatorDefault,
pFontString,
kCFStringEncodingASCII);
if(pFontCFString != nullptr)
{
pContext = CGContextCreateFromString(pCFString,
pFontCFString,
rFontSize,
rAlignment,
pComponents,
rSize);
CFRelease(pFontCFString);
} // if
CFRelease(pCFString);
} // if
} // if
return pContext;
} // CGContextCreateFromString
// Generate a texture from a cstring, using a font, at a size,
// with alignment and color
GLuint Texture2DCreateFromString(const GLchar * const pString,
const GLchar * const pFontName,
const CGFloat& rFontSize,
const CTTextAlignment& rAlignment,
const CGFloat * const pColor,
CGSize& rSize)
{
GLuint nTID = 0;
CGContextRef pCtx = CGContextCreateFromString(pString,
pFontName,
rFontSize,
rAlignment,
pColor,
rSize);
if(pCtx != nullptr)
{
nTID = GLUTexture2DCreateFromContext(pCtx);
CGContextRelease(pCtx);
} // if
return nTID;
} // GLUTexture2DCreateFromString
| 37.142857
| 155
| 0.479533
|
arielscarpinelli
|
a2ba91162019f55ab5b9a0e888c613abf75fdb30
| 509
|
cpp
|
C++
|
Vector-Erase.cpp
|
arnav-tandon/HackerRankChallenges
|
4dddbe42044ba1673ceaed6ccfd026df89cdb8dc
|
[
"MIT"
] | null | null | null |
Vector-Erase.cpp
|
arnav-tandon/HackerRankChallenges
|
4dddbe42044ba1673ceaed6ccfd026df89cdb8dc
|
[
"MIT"
] | null | null | null |
Vector-Erase.cpp
|
arnav-tandon/HackerRankChallenges
|
4dddbe42044ba1673ceaed6ccfd026df89cdb8dc
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, x, p, q, r;
cin >> n;
vector<int> a;
for(int i = 0; i < n; ++i){
cin >> x;
a.push_back(x);
}
cin >> p;
a.erase(a.begin() + (p - 1));
cin >> q >> r;
a.erase(a.begin() + (q - 1),a.begin() + (r - 1));
cout << a.size() << "\n";
for(int k = 0; k < a.size(); ++k){
cout << a[k] << ' ';
}
return 0;
}
| 18.851852
| 53
| 0.440079
|
arnav-tandon
|
a2baf8fd519740ff9d83bda7facdefaad64f1177
| 2,629
|
cpp
|
C++
|
src/setshowinfo.cpp
|
mahuifa/DesktopTime
|
067bd36a42d7349d8905c2bf81a74b6a1f895f05
|
[
"Apache-2.0"
] | 1
|
2022-03-20T15:29:15.000Z
|
2022-03-20T15:29:15.000Z
|
src/setshowinfo.cpp
|
mahuifa/DesktopTime
|
067bd36a42d7349d8905c2bf81a74b6a1f895f05
|
[
"Apache-2.0"
] | null | null | null |
src/setshowinfo.cpp
|
mahuifa/DesktopTime
|
067bd36a42d7349d8905c2bf81a74b6a1f895f05
|
[
"Apache-2.0"
] | null | null | null |
#include "setshowinfo.h"
#include "ui_setshowinfo.h"
#include <QFileDialog>
#include <qdebug.h>
#include "head.h"
SetShowInfo::SetShowInfo(QWidget *parent) :
QWidget(parent),
ui(new Ui::SetShowInfo)
{
ui->setupUi(this);
this->setWindowTitle("显示设置");
for(int i = 1; i < 100; i++)
{
ui->comboBox_size->addItem(QString("%1").arg(i), i);
}
}
SetShowInfo::~SetShowInfo()
{
delete ui;
}
/**
* @brief 传入需要设置的字体
* @param time 时间字体
* @param date 日期字体
*/
void SetShowInfo::setFont(const QFont &time, const QFont &date)
{
m_fontDate = date;
m_fontTime = time;
ui->comboBox_size->setCurrentText(QString("%1").arg(time.pointSize()));
ui->fontComboBox->setCurrentFont(time);
}
void SetShowInfo::on_fontComboBox_currentFontChanged(const QFont &f)
{
m_fontTime = f;
m_fontTime.setPointSize(ui->comboBox_size->currentData().toInt());
if(ui->check_time->isChecked())
{
emit newFont(m_fontTime, SetType::Time);
}
if(ui->check_date->isChecked())
{
emit newFont(m_fontTime, SetType::Date);
}
}
void SetShowInfo::on_comboBox_size_activated(int index)
{
on_fontComboBox_currentFontChanged(ui->fontComboBox->font());
}
void SetShowInfo::on_horizontalSlider_space_valueChanged(int value)
{
emit newSpace(value);
}
void SetShowInfo::on_comboBox_activated(const QString &arg1)
{
if(arg1 == "无")
{
emit newBgImage("none");
QColor color(255, 255, 255);
emit newColor(color, SetType::Background);
}
else
{
emit newBgImage(arg1);
}
}
void SetShowInfo::on_but_open_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,
"选择图片!",
"./",
"图片文件(*png *jpg)");
ui->lineEdit_path->setText(fileName);
emit newBgImage(fileName);
}
void SetShowInfo::on_com_time_activated(const QString &arg1)
{
emit newStyle(arg1, SetType::Time);
}
void SetShowInfo::on_com_date_activated(const QString &arg1)
{
emit newStyle(arg1, SetType::Date);
}
void SetShowInfo::on_but_fontColor_clicked()
{
QColor color = QColorDialog::getColor(Qt::white);
if(ui->check_time->isChecked())
{
emit newColor(color, SetType::Time);
}
if(ui->check_date->isChecked())
{
emit newColor(color, SetType::Date);
}
}
void SetShowInfo::on_but_bgColor_clicked()
{
QColor color = QColorDialog::getColor(Qt::white);
emit newColor(color, SetType::Background);
}
| 20.700787
| 75
| 0.617725
|
mahuifa
|
a2bd2cc7f04e5d37e3d0958fb038281b963f26a1
| 7,738
|
cpp
|
C++
|
IOSServer/Decomp.cpp
|
satadriver/GoogleServiceServer
|
7d6e55d2f9a189301dd68821c920d0a0e300322a
|
[
"Apache-2.0"
] | null | null | null |
IOSServer/Decomp.cpp
|
satadriver/GoogleServiceServer
|
7d6e55d2f9a189301dd68821c920d0a0e300322a
|
[
"Apache-2.0"
] | null | null | null |
IOSServer/Decomp.cpp
|
satadriver/GoogleServiceServer
|
7d6e55d2f9a189301dd68821c920d0a0e300322a
|
[
"Apache-2.0"
] | null | null | null |
#include <windows.h>
#include "iosServer.h"
#include "PublicFunction.h"
#include "CryptoUtils.h"
#include "Coder.h"
#include "FileOperator.h"
int DisposePrefixZip(char * filename,char * dstfilename) {
lstrcpyA(dstfilename, filename);
int fnlen = lstrlenA(dstfilename);
for (int i = 0; i < fnlen - 4 + 1; i ++)
{
if (memcmp(dstfilename + i,".zip",4) == 0)
{
*(dstfilename + i) = 0;
return TRUE;
}
}
return FALSE;
}
int DecompressFromFileBlock(char * filename) {
char szdstfilename[MAX_PATH];
DisposePrefixZip(filename, szdstfilename);
HANDLE hf = CreateFileA(filename, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
HANDLE hfdst = CreateFileA(szdstfilename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hfdst == INVALID_HANDLE_VALUE)
{
CloseHandle(hf);
return FALSE;
}
int ret = 0;
DWORD dwcnt = 0;
int filesize = GetFileSize(hf, 0);
int cnt = 0;
do
{
char bdecompsize[4];
char bcompsize[4];
ret = ReadFile(hf, bdecompsize, 4, &dwcnt, 0);
ret = ReadFile(hf, bcompsize, 4, &dwcnt, 0);
int decompsize = *(int*)bdecompsize;
int compsize = *(int*)bcompsize;
char * lpsrcbuf = new char[compsize];
char * lpdstbuf = new char[decompsize + 0x1000];
ret = ReadFile(hf, lpsrcbuf, compsize, &dwcnt, 0);
unsigned long outlen = decompsize;
ret = uncompress((unsigned char*)lpdstbuf, &outlen, (unsigned char*)lpsrcbuf, compsize);
if (ret == 0)
{
ret = WriteFile(hfdst, lpdstbuf, outlen, &dwcnt, 0);
}
delete[] lpsrcbuf;
delete[] lpdstbuf;
cnt += (8 + compsize);
} while (cnt < filesize);
CloseHandle(hf);
DeleteFileA(filename);
CloseHandle(hfdst);
char szcmd[MAX_PATH];
wsprintfA(szcmd, "cmd /c renanme %s %s", filename, szdstfilename);
WinExec(szcmd,SW_HIDE);
return TRUE;
}
int DecryptAndDecompFile(LPDATAPROCESS_PARAM lpparam, char * filename, char * lpdstfn, char * imei, char * username, int withparam, int append,DWORD type) {
DATAPROCESS_PARAM stparam = *lpparam;
char szlog[1024];
char errorbuf[1024];
HANDLE hf = CreateFileA(filename, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
int filesize = GetFileSize(hf, 0);
char * lpdata = new char[filesize];
DWORD dwcnt = 0;
int ret = ReadFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
DeleteFileA(filename);
if ( ((type & PACKET_CRYPT_FLAG) && (type & PACKET_COMPRESS_FLAG)) ||
((type & 1) && (*(unsigned short*)(lpdata + sizeof(int)) != 0x9c78)) )
{
int len = CryptoUtils:: xorCryptData(lpdata, filesize, imei, CRYPT_KEY_SIZE, lpdata, filesize);
if (type & PACKET_COMPRESS_FLAG)
{
;
}
int compresssize = *(int*)(lpdata);
if (compresssize <= 0)
{
delete[] lpdata;
wsprintfA(szlog, "DecryptAndDecompFile uncompress file:%s size 0", filename);
ErrorFormat(&stparam, errorbuf, szlog);
WriteLogFile(errorbuf);
return FALSE;
}
unsigned long unzipbufLen = compresssize + 0x1000;
unsigned char * unzipbuf = (unsigned char*)new char[unzipbufLen];
if (unzipbuf == FALSE)
{
delete[] lpdata;
return FALSE;
}
ret = uncompress((Bytef*)unzipbuf, (uLongf*)&unzipbufLen, (Bytef*)(lpdata + sizeof(DWORD)), (uLongf)(filesize - sizeof(DWORD)));
if (ret != Z_OK) {
delete[]unzipbuf;
delete[] lpdata;
wsprintfA(szlog, "DecryptAndDecompFile uncompress error:%s", filename);
ErrorFormat(&stparam, errorbuf, szlog);
WriteLogFile(errorbuf);
WriteErrorPacket("uncompress error", lpdata, ERRORPACKETSIZE);
return FALSE;
}
*(DWORD*)(unzipbuf + unzipbufLen) = 0;
delete[] lpdata;
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)unzipbuf;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[]unzipbuf;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpbuf, dwfilesize, &dwcnt, 0);
CloseHandle(hf);
}
else {
ret = FileOperator::TripSufixName(filename, lpdstfn, ".tmp");
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[]unzipbuf;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, unzipbuf, unzipbufLen, &dwcnt, 0);
CloseHandle(hf);
}
delete[]unzipbuf;
return TRUE;
}
else {
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)lpdata;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[] lpdata;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpbuf, dwfilesize , &dwcnt, 0);
CloseHandle(hf);
}
else {
ret = FileOperator::TripSufixName(filename, lpdstfn, ".tmp");
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
delete[] lpdata;
return FALSE;
}
ret = SetFilePointer(hf, 0, 0, FILE_END);
ret = WriteFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
}
delete[] lpdata;
return TRUE;
}
return TRUE;
}
int NoneDecryptDataWiHeader(LPDATAPROCESS_PARAM lpparam, char * filename,char * lpdstfn,char * imei,char * username,int withparam,int append) {
DATAPROCESS_PARAM stparam = *lpparam;
//char szlog[1024];
//char errorbuf[1024];
HANDLE hf = CreateFileA(filename, GENERIC_WRITE|GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
int filesize = GetFileSize(hf, 0);
char * lpdata = new char[filesize];
DWORD dwcnt = 0;
int ret = ReadFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
if (withparam)
{
FileOperator::GetPathFromFullName(filename, lpdstfn);
char * lpbuf = (char*)lpdata;
DWORD dwfilenamesize = *(DWORD*)lpbuf;
char szfilename[MAX_PATH] = { 0 };
lpbuf += sizeof(DWORD);
memmove(szfilename, lpbuf, dwfilenamesize);
lpbuf += dwfilenamesize;
DWORD dwfilesize = *(DWORD*)lpbuf;
lpbuf += sizeof(DWORD);
char szgbkfn[MAX_PATH] = { 0 };
ret = Coder::UTF8FNToGBKFN(szfilename, dwfilenamesize, szgbkfn, MAX_PATH);
lstrcatA(lpdstfn, szgbkfn);
hf = CreateFileA(lpdstfn, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
ret = WriteFile(hf, lpbuf, filesize - (lpbuf - lpdata), &dwcnt, 0);
CloseHandle(hf);
DeleteFileA(filename);
}
else {
return TRUE;
hf = CreateFileA(filename, GENERIC_WRITE, 0, 0, append, FILE_ATTRIBUTE_NORMAL, 0);
if (hf == INVALID_HANDLE_VALUE)
{
return FALSE;
}
ret = WriteFile(hf, lpdata, filesize, &dwcnt, 0);
CloseHandle(hf);
lstrcpyA(lpdstfn, filename);
}
return TRUE;
}
| 25.123377
| 156
| 0.676402
|
satadriver
|
a2bdb1e951c5b6a99024734de3fa57d343ca12e4
| 1,780
|
hpp
|
C++
|
include/view/view.hpp
|
modern-cpp-examples/match3
|
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
|
[
"BSL-1.0"
] | 166
|
2016-04-27T19:01:00.000Z
|
2022-03-27T02:16:55.000Z
|
include/view/view.hpp
|
Fuyutsubaki/match3
|
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
|
[
"BSL-1.0"
] | 4
|
2016-05-19T07:47:38.000Z
|
2018-03-22T04:33:00.000Z
|
include/view/view.hpp
|
Fuyutsubaki/match3
|
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
|
[
"BSL-1.0"
] | 17
|
2016-05-18T21:17:39.000Z
|
2022-03-20T22:37:14.000Z
|
//
// Copyright (c) 2016 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "config.hpp"
#include "view/icanvas.hpp"
namespace match3 {
class view {
static constexpr auto grid_size = 38;
static constexpr auto grid_offset = grid_size + 5;
static constexpr auto grids_offset_x = 15;
static constexpr auto grids_offset_y = 50;
public:
view(icanvas& canvas, config conf) : canvas_(canvas), config_(conf) {
grids.reserve(config_.board_colors);
for (auto i = 0; i <= config_.board_colors; ++i) {
grids.emplace_back(
canvas_.load_image("data/images/" + std::to_string(i) + ".png"));
};
match_ = canvas_.load_image("data/images/match.png");
}
void set_grid(int x, int y, int c) {
canvas_.draw(grids[c], grids_offset_x + (x * grid_offset),
grids_offset_y + (y * grid_offset));
}
void update_grid(int x, int y) {
canvas_.draw(match_, grids_offset_x + (x * grid_offset),
grids_offset_y + (y * grid_offset), false /*cleanup*/);
}
auto get_position(int x, int y) const noexcept {
return (((y - grids_offset_y) / grid_offset) * config_.board_width) +
((x - grids_offset_x) / grid_offset);
}
void set_text(const std::string& text, int x, int y, int font_size = 14) {
canvas_.draw(canvas_.create_text(text, "data/fonts/font.ttf", font_size), x,
y);
}
void update() { canvas_.render(); }
void clear() { canvas_.clear(); }
private:
std::vector<std::shared_ptr<void>> grids;
std::shared_ptr<void> match_;
icanvas& canvas_;
config config_;
};
} // match3
| 28.253968
| 80
| 0.651685
|
modern-cpp-examples
|
a2c5c26adb1d42ddc624f3d00c7333a20e7b2e03
| 673
|
cpp
|
C++
|
1128/main.cpp
|
Heliovic/PAT_Solutions
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | 2
|
2019-03-18T12:55:38.000Z
|
2019-09-07T10:11:26.000Z
|
1128/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
1128/main.cpp
|
Heliovic/My_PAT_Answer
|
7c5dd554654045308f2341713c3e52cc790beb59
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <algorithm>
#define MAX_N 1024
using namespace std;
int pos[MAX_N];
int K, N;
int main()
{
scanf("%d", &K);
L1:
while (K--)
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
scanf("%d", &pos[i]);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (i == j)
continue;
if (pos[i] == pos[j] || abs(i - j) == abs(pos[i] - pos[j]))
{
printf("NO\n");
goto L1;
}
}
}
printf("YES\n");
}
return 0;
}
| 16.825
| 75
| 0.325409
|
Heliovic
|
a2c8029c8c782c30b83c0d09ab05553b9cc210a8
| 213
|
cpp
|
C++
|
Recursion/NestedRecursion/main.cpp
|
rsghotra/AbdulBari
|
2d2845608840ddda6e5153ec91966110ca7e25f5
|
[
"Apache-2.0"
] | 1
|
2020-12-02T09:21:52.000Z
|
2020-12-02T09:21:52.000Z
|
Recursion/NestedRecursion/main.cpp
|
rsghotra/AbdulBari
|
2d2845608840ddda6e5153ec91966110ca7e25f5
|
[
"Apache-2.0"
] | null | null | null |
Recursion/NestedRecursion/main.cpp
|
rsghotra/AbdulBari
|
2d2845608840ddda6e5153ec91966110ca7e25f5
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int fun(int n) {
if(n>100) {
return n - 10;
}
return fun(fun(n+11));
}
int main() {
int r;
r = fun(1);
cout << r << endl;
return 0;
}
| 12.529412
| 26
| 0.488263
|
rsghotra
|
a2ca4c13f1112c460ba577ab92c6e14ce5fc2bc8
| 3,982
|
cpp
|
C++
|
src/system/libroot/add-ons/icu/ICUCategoryData.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | 4
|
2016-03-29T21:45:21.000Z
|
2016-12-20T00:50:38.000Z
|
src/system/libroot/add-ons/icu/ICUCategoryData.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | null | null | null |
src/system/libroot/add-ons/icu/ICUCategoryData.cpp
|
axeld/haiku
|
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
|
[
"MIT"
] | 3
|
2018-12-17T13:07:38.000Z
|
2021-09-08T13:07:31.000Z
|
/*
* Copyright 2010-2011, Oliver Tappe, zooey@hirschkaefer.de.
* Distributed under the terms of the MIT License.
*/
#include "ICUCategoryData.h"
#include <string.h>
#include <unicode/uchar.h>
namespace BPrivate {
namespace Libroot {
ICUCategoryData::ICUCategoryData(pthread_key_t tlsKey)
:
fThreadLocalStorageKey(tlsKey)
{
*fPosixLocaleName = '\0';
*fGivenCharset = '\0';
}
ICUCategoryData::~ICUCategoryData()
{
}
status_t
ICUCategoryData::SetTo(const Locale& locale, const char* posixLocaleName)
{
if (!posixLocaleName)
return B_BAD_VALUE;
fLocale = locale;
strlcpy(fPosixLocaleName, posixLocaleName, skMaxPosixLocaleNameLen);
*fGivenCharset = '\0';
// POSIX locales often contain an embedded charset, but ICU does not
// handle these within locales (that part of the name is simply
// ignored).
// We need to fetch the charset specification and lookup an appropriate
// ICU charset converter. This converter will later be used to get info
// about ctype properties.
const char* charsetStart = strchr(fPosixLocaleName, '.');
if (charsetStart) {
++charsetStart;
int l = 0;
while (charsetStart[l] != '\0' && charsetStart[l] != '@')
++l;
snprintf(fGivenCharset, UCNV_MAX_CONVERTER_NAME_LENGTH, "%.*s", l,
charsetStart);
}
if (!strlen(fGivenCharset))
strcpy(fGivenCharset, "utf-8");
return _SetupConverter();
}
status_t
ICUCategoryData::SetToPosix()
{
fLocale = Locale::createFromName("en_US_POSIX");
strcpy(fPosixLocaleName, "POSIX");
strcpy(fGivenCharset, "US-ASCII");
return _SetupConverter();
}
status_t
ICUCategoryData::_ConvertUnicodeStringToLocaleconvEntry(
const UnicodeString& string, char* destination, int destinationSize,
const char* defaultValue)
{
UConverter* converter;
status_t result = _GetConverter(converter);
if (result != B_OK)
return result;
UErrorCode icuStatus = U_ZERO_ERROR;
ucnv_fromUChars(converter, destination, destinationSize, string.getBuffer(),
string.length(), &icuStatus);
if (!U_SUCCESS(icuStatus)) {
switch (icuStatus) {
case U_BUFFER_OVERFLOW_ERROR:
result = B_NAME_TOO_LONG;
break;
case U_INVALID_CHAR_FOUND:
case U_TRUNCATED_CHAR_FOUND:
case U_ILLEGAL_CHAR_FOUND:
result = B_BAD_DATA;
break;
default:
result = B_ERROR;
break;
}
strlcpy(destination, defaultValue, destinationSize);
}
return result;
}
status_t
ICUCategoryData::_GetConverter(UConverter*& converterOut)
{
// we use different converters per thread to avoid concurrent accesses
ICUThreadLocalStorageValue* tlsValue = NULL;
status_t result = ICUThreadLocalStorageValue::GetInstanceForKey(
fThreadLocalStorageKey, tlsValue);
if (result != B_OK)
return result;
if (tlsValue->converter != NULL) {
if (strcmp(tlsValue->charset, fGivenCharset) == 0) {
converterOut = tlsValue->converter;
return B_OK;
}
// charset no longer matches the converter, we need to dump it and
// create a new one
ucnv_close(tlsValue->converter);
tlsValue->converter = NULL;
}
// create a new converter for the current charset
UErrorCode icuStatus = U_ZERO_ERROR;
UConverter* icuConverter = ucnv_open(fGivenCharset, &icuStatus);
if (icuConverter == NULL)
return B_NAME_NOT_FOUND;
// setup the new converter to stop upon any errors
icuStatus = U_ZERO_ERROR;
ucnv_setToUCallBack(icuConverter, UCNV_TO_U_CALLBACK_STOP, NULL, NULL, NULL,
&icuStatus);
if (!U_SUCCESS(icuStatus)) {
ucnv_close(icuConverter);
return B_ERROR;
}
icuStatus = U_ZERO_ERROR;
ucnv_setFromUCallBack(icuConverter, UCNV_FROM_U_CALLBACK_STOP, NULL, NULL,
NULL, &icuStatus);
if (!U_SUCCESS(icuStatus)) {
ucnv_close(icuConverter);
return B_ERROR;
}
tlsValue->converter = icuConverter;
strlcpy(tlsValue->charset, fGivenCharset, sizeof(tlsValue->charset));
converterOut = icuConverter;
return B_OK;
}
status_t
ICUCategoryData::_SetupConverter()
{
UConverter* converter;
return _GetConverter(converter);
}
} // namespace Libroot
} // namespace BPrivate
| 23.151163
| 77
| 0.741336
|
axeld
|
a2cf8e32027366a348ac340ac7a8fb437954ad21
| 709
|
cpp
|
C++
|
src/tests/test_uuids.cpp
|
ondra-novak/couchit
|
10af4464327dcc2aeb470fe2db7fbd1594ff1b0d
|
[
"MIT"
] | 4
|
2017-03-20T22:14:10.000Z
|
2018-03-21T09:24:32.000Z
|
src/tests/test_uuids.cpp
|
ondra-novak/couchit
|
10af4464327dcc2aeb470fe2db7fbd1594ff1b0d
|
[
"MIT"
] | null | null | null |
src/tests/test_uuids.cpp
|
ondra-novak/couchit
|
10af4464327dcc2aeb470fe2db7fbd1594ff1b0d
|
[
"MIT"
] | null | null | null |
/*
* test_uuids.cpp
*
* Created on: 10. 3. 2016
* Author: ondra
*/
#include <iostream>
#include <set>
#include <chrono>
#include <thread>
#include "../couchit/couchDB.h"
#include "test_common.h"
#include "testClass.h"
namespace couchit {
using namespace json;
static void genFastUUIDS(std::ostream &print) {
std::set<String> uuidmap;
CouchDB db(getTestCouch());
for (std::size_t i = 0; i < 50; i++) {
String uuid ( db.genUID("test-"));
std::cout << uuid << std::endl;
uuidmap.insert(uuid);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
print << uuidmap.size();
}
void testUUIDs(TestSimple &tst) {
tst.test("couchdb.genfastuid","50") >> &genFastUUIDS;
}
}
| 16.488372
| 62
| 0.651622
|
ondra-novak
|
a2cfb318bdb4cf5e13a620e544f649b8661f2adc
| 966
|
cpp
|
C++
|
source/vmalloc.cpp
|
EthanArmbrust/snes9xgx
|
4e11dc00b3672fe4f0979317cca35ce97d1c2d09
|
[
"Xnet",
"X11"
] | 294
|
2016-07-09T01:13:19.000Z
|
2022-03-28T02:59:29.000Z
|
source/vmalloc.cpp
|
EthanArmbrust/snes9xgx
|
4e11dc00b3672fe4f0979317cca35ce97d1c2d09
|
[
"Xnet",
"X11"
] | 173
|
2016-07-30T16:20:25.000Z
|
2022-02-20T10:46:45.000Z
|
source/vmalloc.cpp
|
EthanArmbrust/snes9xgx
|
4e11dc00b3672fe4f0979317cca35ce97d1c2d09
|
[
"Xnet",
"X11"
] | 167
|
2016-07-19T20:33:43.000Z
|
2022-03-15T18:09:15.000Z
|
/****************************************************************************
* Snes9x Nintendo Wii/Gamecube Port
*
* emu_kidid 2015-2018
*
* vmalloc.cpp
*
* GC VM memory allocator
***************************************************************************/
#ifdef USE_VM
#include <ogc/machine/asm.h>
#include <ogc/lwp_heap.h>
#include <ogc/system.h>
#include <ogc/machine/processor.h>
#include "utils/vm/vm.h"
static heap_cntrl vm_heap;
static int vm_initialised = 0;
void InitVmManager ()
{
__lwp_heap_init(&vm_heap, (void *)ARAM_VM_BASE, ARAM_SIZE, 32);
vm_initialised = 1;
}
void* vm_malloc(u32 size)
{
if(!vm_initialised) InitVmManager();
return __lwp_heap_allocate(&vm_heap, size);
}
bool vm_free(void *ptr)
{
if(!vm_initialised) InitVmManager();
return __lwp_heap_free(&vm_heap, ptr);
}
int vm_size_free()
{
if(!vm_initialised) InitVmManager();
heap_iblock info;
__lwp_heap_getinfo(&vm_heap,&info);
return info.free_size;
}
#endif
| 19.32
| 77
| 0.610766
|
EthanArmbrust
|
a2d36653fd6175ddc06d4d8b07e6f0e828a579e7
| 1,018
|
hpp
|
C++
|
src/sort_test.hpp
|
loryruta/gpu-radix-sort
|
39a973e46834dd7f06a8855e95aa3b3cc7e1709e
|
[
"MIT"
] | 6
|
2021-11-11T09:12:10.000Z
|
2022-03-05T15:56:16.000Z
|
src/sort_test.hpp
|
rutay/parallel-radix-sort
|
39a973e46834dd7f06a8855e95aa3b3cc7e1709e
|
[
"MIT"
] | null | null | null |
src/sort_test.hpp
|
rutay/parallel-radix-sort
|
39a973e46834dd7f06a8855e95aa3b3cc7e1709e
|
[
"MIT"
] | 1
|
2021-11-09T06:51:18.000Z
|
2021-11-09T06:51:18.000Z
|
#pragma once
#include "generated/radix_sort.hpp"
namespace rgc::radix_sort
{
class array_compare
{
private:
program m_program;
GLuint m_errors_counter;
GLuint m_error_marks_buf;
public:
array_compare(size_t max_arr_len);
~array_compare();
GLuint compare(GLuint arr_1, GLuint arr_2, size_t arr_len);
};
class check_permuted
{
private:
GLuint m_max_val;
array_compare m_array_compare;
program m_count_elements_program;
GLuint m_original_counts_buf;
GLuint m_permuted_counts_buf;
void count_elements(GLuint arr, size_t arr_len, GLuint counts_buf);
public:
check_permuted(GLuint max_val); // min_val = 0
~check_permuted();
void memorize_original_array(GLuint arr, size_t arr_len);
void memorize_permuted_array(GLuint arr, size_t arr_len);
bool is_permuted();
};
class check_sorted
{
private:
program m_program;
GLuint m_errors_counter;
public:
check_sorted();
~check_sorted();
bool is_sorted(GLuint arr, size_t arr_len, GLuint* errors_count);
};
}
| 17.551724
| 69
| 0.753438
|
loryruta
|
a2d42874d1c5b9c1d5f9474430caee9552b111fc
| 3,683
|
cpp
|
C++
|
Algorithm/src/algorithm/leetcode/two_sum.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 15
|
2015-11-04T12:53:23.000Z
|
2021-08-10T09:53:12.000Z
|
Algorithm/src/algorithm/leetcode/two_sum.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | null | null | null |
Algorithm/src/algorithm/leetcode/two_sum.cpp
|
elloop/algorithm
|
5485be0aedbc18968f775cff9533a2d444dbdcb5
|
[
"MIT"
] | 6
|
2015-11-13T10:17:01.000Z
|
2020-05-14T07:25:48.000Z
|
#include <map>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include "inc.h"
#include "valid_parentheses.h"
#include "rotate_array.h"
#include "title_to_number.h"
#include "trailing_zeroes.h"
#include "column_to_title.h"
#include "compare_version.h"
#include "intersection_of_linklist.h"
#include "zig_zag.h"
#include "min_stack.h"
#include "gtest/gtest.h"
NS_BEGIN(elloop);
using std::vector;
using std::map;
class S {
public:
static vector<int> solve(vector<int>& numbers, int target) {
vector<int> result;
vector<int>::size_type i(0);
map<int, int> half;
for (; i<numbers.size(); ++i) {
if (half.find(numbers[i]) != half.end()) {
result.push_back(half.find(numbers[i])->second);
result.push_back(i+1);
return result;
}
else {
half.insert(std::make_pair(target-numbers[i], i+1));
}
}
return result;
}
};
BEGIN_TEST(TwoSum, Test1, @@);
/*
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
vector<int> src;
src.assign(a, a+sizeof a / sizeof a[0]);
int target = a[2] + a[3];
vector<int> result = S::solve(src, target);
for (auto i : result) {
pln(i);
}
*/
// TODO: more solutions.
// valid_parentheses::Solution s;
// string str("()[]}");
// psln(s.isValid(str));
rotate_array::Solution s;
int nums[] = {1, 2, 3, 4, 5};
int k = 6;
s.rotate(nums, sizeof nums/ sizeof nums[0], k);
// TODO: make a summary about memcpy and memmove.
// test memcpy and memmove.
// int a[] = {1, 2, 3, 4};
// int b[] = {0, 0, 0,0,0};
// int n(4);
// // ::memcpy(b+1, (int*)a, sizeof (int) * (n));
// ::memmove(a+1, a, sizeof (int) *(n-1));
// ::memcpy(a+1, a, sizeof (int) *(n-1));
// print_array(a);
// title_to_number::Solution s;
// psln(s.titleToNumber("ZA"));
// trailing_zeroes::Solution s;
// psln(s.trailingZeroes(4));
// psln(s.trailingZeroes(2147483647));
// for (int i=4; i<250; ) {
// p(i); p(": ");
// pln(s.trailingZeroes(i));
// i += 5;
// }
// compare_version::Solution s;
// psln(s.compareVersion("1", "2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.10000.1.1.1.1.1.2.3.4.5.6.7"));
// psln(s.compareVersion("1.1.0", "1.1"));
// string s1("01");
// string s2("1");
// vector<int> x = s.getNumbers(s1);
// vector<int> x2 = s.getNumbers(s2);
// int i = x.size();
// int j = x2.size();
// psln(i);
// psln(j);
// psln(s.compareVersion(s1, s2));
// string v1, v2;
// while (cin >> v1 >> v2) {
// psln(s.compareVersion(v1, v2));
// }
// column_to_title::Solution s;
// s.convertToTitle(52);
// using namespace intersection_of_linklist;
// intersection_of_linklist::Solution s;
// Solution::ListNode * p = new Solution::ListNode[13];
// Solution::ListNode * q = new Solution::ListNode[13];
// psln(s.getIntersectionNode(p, q));
// delete p;
// delete q;
// zig_zag::Solution s;
// psln(s.convert("PAYPALISHIRING", 3));
// char str[] = "hello";
// string s(str, str + 5);
// psln(s);
/* using min_stack::MinStack; */
// MinStack s;
// s.push(10);
// s.push(11);
// s.push(1);
// psln(s.top());
// s.pop();
// psln(s.top());
/* psln(s.getMin()); */
// using min_stack::MinStack2;
// MinStack2 s;
// s.push(2147483646);
// s.push(2147483646);
// s.push(2147483647);
// psln(s.top());
// s.pop();
// psln(s.getMin());
// s.pop();
// psln(s.getMin());
// s.pop();
// s.push(2147483647);
// psln(s.top());
// psln(s.getMin());
// s.push(-2147483648);
// psln(s.top());
// psln(s.getMin());
// s.pop();
// psln(s.getMin());
END_TEST;
NS_END(elloop);
| 22.053892
| 96
| 0.555797
|
elloop
|
a2d8479782400383e3d78a74f87c83433c137a8a
| 5,500
|
cpp
|
C++
|
src/bls12_381/curve.cpp
|
gtfierro/jedi-pairing
|
07791509e7702094118eba34337868a646363dc2
|
[
"BSD-3-Clause"
] | 4
|
2020-10-27T09:38:17.000Z
|
2021-11-01T07:05:34.000Z
|
src/bls12_381/curve.cpp
|
gtfierro/jedi-pairing
|
07791509e7702094118eba34337868a646363dc2
|
[
"BSD-3-Clause"
] | null | null | null |
src/bls12_381/curve.cpp
|
gtfierro/jedi-pairing
|
07791509e7702094118eba34337868a646363dc2
|
[
"BSD-3-Clause"
] | 2
|
2021-08-09T06:27:46.000Z
|
2021-08-09T19:55:07.000Z
|
/*
* Copyright (c) 2018, Sam Kumar <samkumar@cs.berkeley.edu>
* Copyright (c) 2018, University of California, Berkeley
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include "bls12_381/fq.hpp"
#include "bls12_381/fq2.hpp"
#include "bls12_381/curve.hpp"
namespace embedded_pairing::bls12_381 {
extern constexpr Fq g1_b_coeff_var = g1_b_coeff;
extern constexpr Fq2 g2_b_coeff_var = g2_b_coeff;
template <typename Projective, typename Affine, typename BaseField>
void sample_random_generator(Projective& result, void (*get_random_bytes)(void*, size_t)) {
do {
Affine random;
BaseField x;
unsigned char b;
do {
x.random(get_random_bytes);
get_random_bytes(&b, sizeof(b));
} while (!random.get_point_from_x(x, (b & 0x1) == 0x1, true));
result.multiply(random, Affine::cofactor);
} while (result.is_zero());
}
void G1::random_generator(void (*get_random_bytes)(void*, size_t)) {
sample_random_generator<G1, G1Affine, Fq>(*this, get_random_bytes);
}
void G2::random_generator(void (*get_random_bytes)(void*, size_t)) {
sample_random_generator<G2, G2Affine, Fq2>(*this, get_random_bytes);
}
/* Procedures for encoding/decoding. */
template <typename Affine, bool compressed>
void Encoding<Affine, compressed>::encode(const Affine& g) {
if (g.is_zero()) {
memset(this->data, 0x0, sizeof(this->data));
this->data[0] = encoding_flags_infinity;
} else {
g.x.write_big_endian(&this->data[0]);
if constexpr(compressed) {
typename Affine::BaseFieldType negy;
negy.negate(g.y);
if (Affine::BaseFieldType::compare(g.y, negy) == 1) {
this->data[0] |= encoding_flags_greater;
}
} else {
g.y.write_big_endian(&this->data[sizeof(typename Affine::BaseFieldType)]);
}
}
if constexpr(compressed) {
this->data[0] |= encoding_flags_compressed;
}
}
template <typename Affine, bool compressed>
bool Encoding<Affine, compressed>::decode(Affine& g, bool checked) const {
if (checked && is_encoding_compressed(this->data[0]) != compressed) {
return false;
}
if ((this->data[0] & encoding_flags_infinity) != 0) {
if (checked) {
if ((this->data[0] & ~(encoding_flags_compressed | encoding_flags_infinity)) != 0) {
return false;
}
for (int i = 1; i != sizeof(this->data); i++) {
if (this->data[i] != 0) {
return false;
}
}
}
g.copy(Affine::zero);
return true;
}
/* The "read_big_endian" method masks off the three control bits. */
g.x.read_big_endian(&this->data[0]);
bool greater = ((this->data[0] & encoding_flags_greater) != 0);
if constexpr(compressed) {
if (!g.get_point_from_x(g.x, greater, checked)) {
return false;
}
} else {
if (checked && greater) {
return false;
}
g.y.read_big_endian(&this->data[sizeof(typename Affine::BaseFieldType)]);
g.infinity = false;
}
if (checked) {
if constexpr(!compressed) {
if (!g.is_on_curve()) {
return false;
}
}
return g.is_in_correct_subgroup_assuming_on_curve();
}
return true;
}
/* Explicitly instantiate Encoding templates. */
template struct Encoding<G1Affine, false>;
template struct Encoding<G1Affine, true>;
template struct Encoding<G2Affine, false>;
template struct Encoding<G2Affine, true>;
}
| 37.671233
| 100
| 0.613818
|
gtfierro
|
a2d84d1679838c077a221790b77f4531e41ae4a5
| 5,695
|
cpp
|
C++
|
modules/task_3/kudriavtsev_a_radix_sort/main.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_3/kudriavtsev_a_radix_sort/main.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_3/kudriavtsev_a_radix_sort/main.cpp
|
Vodeneev/pp_2020_autumn_math
|
9b7e5ec56e09474c9880810a6124e3e416bb7e16
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2020 Kudriavtsev Alexander
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <algorithm>
#include "./ops_mpi.h"
TEST(Parallel_Operations_MPI, Test_Seq_20) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Seq_2000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Seq_20000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1;
const int n = 20;
if (rank == 0) {
std::vector<int> vec2 = vec1 = getRandomVector(n);
double t_b = MPI_Wtime();
radixSort(vec1.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_20) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 20;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_2000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 2000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_3041) { // Simple Number
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 3041;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_43201) { // Big Simple Number
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 43201;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
std::sort(vec2.begin(), vec2.end());
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_1000000) { // Big Number 1
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 1000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_5000000) { // Big Number 2
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 5000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
TEST(Parallel_Operations_MPI, Test_Par_10000000) { // Big Number 3
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> vec1, vec2;
const int n = 10000000;
if (rank == 0) {
vec2 = vec1 = getRandomVector(n);
}
parallelRadixSort(vec1.data(), n);
if (rank == 0) {
double t_b = MPI_Wtime();
radixSort(vec2.data(), n);
double t_e = MPI_Wtime();
std::cout << "Sequential time: " << t_e - t_b << std::endl;
for (int i = 0; i < n; ++i)
ASSERT_EQ(vec2[i], vec1[i]);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 29.35567
| 78
| 0.565233
|
Vodeneev
|
a2d900c3523fdbbf7d57d2733c2c8c653159e676
| 33,925
|
cpp
|
C++
|
SimpleSvmHook/Logging.cpp
|
zanzo420/SimpleSvmHook
|
7cef39ffad9c15a31615a9b032b910011b3bdb1b
|
[
"MIT"
] | 194
|
2018-07-02T11:43:47.000Z
|
2022-03-24T01:50:07.000Z
|
SimpleSvmHook/Logging.cpp
|
zanzo420/SimpleSvmHook
|
7cef39ffad9c15a31615a9b032b910011b3bdb1b
|
[
"MIT"
] | 7
|
2018-09-18T17:33:25.000Z
|
2022-03-19T04:13:22.000Z
|
SimpleSvmHook/Logging.cpp
|
zanzo420/SimpleSvmHook
|
7cef39ffad9c15a31615a9b032b910011b3bdb1b
|
[
"MIT"
] | 55
|
2018-07-29T19:12:47.000Z
|
2022-01-20T13:09:20.000Z
|
/*!
@file Logging.cpp
@brief Implements interfaces to logging functions.
@details This file is migrated from an old codebase and does not always
align with a coding style used in the rest of files.
@author Satoshi Tanda
@copyright Copyright (c) 2018-2019, Satoshi Tanda. All rights reserved.
*/
#include "Logging.hpp"
#define NTSTRSAFE_NO_CB_FUNCTIONS
#include <ntstrsafe.h>
#pragma prefast(disable : 30030)
#pragma prefast(disable : __WARNING_ERROR, "This is completely bogus.")
EXTERN_C_START
//
// A size for log buffer in NonPagedPool. Two buffers are allocated with this
// size. Exceeded logs are ignored silently. Make it bigger if a buffered log
// size often reach this size.
//
static const ULONG k_LogpBufferSizeInPages = 16;
//
// An actual log buffer size in bytes.
//
static const ULONG k_LogpBufferSize = PAGE_SIZE * k_LogpBufferSizeInPages;
//
// A size that is usable for logging. Minus one because the last byte is kept
// for \0.
//
static const ULONG k_LogpBufferUsableSize = k_LogpBufferSize - 1;
//
// An interval to flush buffered log entries into a log file.
//
static const ULONG k_LogpLogFlushIntervalMsec = 50;
//
// The pool tag.
//
static const ULONG k_LogpPoolTag = 'rgoL';
//
// The mask value to indicate the message was already printed out to debug buffer.
//
static const UCHAR k_MessagePrinted = 0x80;
typedef struct _LOG_BUFFER_INFO
{
//
// A pointer to buffer currently used. It is either LogBuffer1 or LogBuffer2.
//
volatile PSTR LogBufferHead;
//
// A pointer to where the next log should be written.
//
volatile PSTR LogBufferTail;
PSTR LogBuffer1;
PSTR LogBuffer2;
//
// Holds the biggest buffer usage to determine a necessary buffer size.
//
SIZE_T LogMaxUsage;
HANDLE LogFileHandle;
KSPIN_LOCK SpinLock;
ERESOURCE Resource;
BOOLEAN ResourceInitialized;
volatile BOOLEAN BufferFlushThreadShouldBeAlive;
volatile BOOLEAN BufferFlushThreadStarted;
HANDLE BufferFlushThreadHandle;
WCHAR LogFilePath[200];
} LOG_BUFFER_INFO, *PLOG_BUFFER_INFO;
NTKERNELAPI
PCHAR
NTAPI
PsGetProcessImageFileName (
_In_ PEPROCESS Process
);
static DRIVER_REINITIALIZE LogpReinitializationRoutine;
static KSTART_ROUTINE LogpBufferFlushThreadRoutine;
//
// The enabled log level.
//
static ULONG g_LogpDebugFlag;
//
// The log buffer.
//
static LOG_BUFFER_INFO g_LogpLogBufferInfo;
//
// Whether the driver is verified by Driver Verifier.
//
static BOOLEAN g_LogpDriverVerified;
/*!
@brief Tests if the printed bit is on.
@param[in] Message - The log message to test.
@return TRUE if the message has the printed bit; or FALSE.
*/
static
_Check_return_
BOOLEAN
LogpIsPrinted (
_In_ PCSTR Message
)
{
return BooleanFlagOn(Message[0], k_MessagePrinted);
}
/*!
@brief Marks the Message as it is already printed out, or clears the printed
bit and restores it to the original.
@param[in] Message - The log message to set the bit.
@param[in] SetBit - TRUE to set the bit; FALSE t clear the bit.
*/
static
VOID
LogpSetPrintedBit (
_In_ PSTR Message,
_In_ BOOLEAN SetBit
)
{
if (SetBit != FALSE)
{
SetFlag(Message[0], k_MessagePrinted);
}
else
{
ClearFlag(Message[0], k_MessagePrinted);
}
}
/*!
@brief Calls DbgPrintEx() while converting \r\n to \n\0.
@param[in] Message - The log message to print out.
*/
static
VOID
LogpDoDbgPrint (
_In_ PSTR Message
)
{
size_t locationOfCr;
if (BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableDbgPrint))
{
goto Exit;
}
locationOfCr = strlen(Message) - 2;
Message[locationOfCr] = '\n';
Message[locationOfCr + 1] = ANSI_NULL;
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "%s", Message);
Exit:
return;
}
/*!
@brief Sleep the current thread's execution for milliseconds.
@param[in] Millisecond - The duration to sleep in milliseconds.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
LogpSleep (
_In_ LONG Millisecond
)
{
LARGE_INTEGER interval;
PAGED_CODE();
interval.QuadPart = -(10000ll * Millisecond);
(VOID)KeDelayExecutionThread(KernelMode, FALSE, &interval);
}
/*!
@brief Logs the current log entry to and flush the log file.
@param[in] Message - The log message to buffer.
@param[in] Info - Log buffer information.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpWriteMessageToFile (
_In_ PCSTR Message,
_In_ const LOG_BUFFER_INFO* Info
)
{
NTSTATUS status;
IO_STATUS_BLOCK ioStatus;
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
status = ZwWriteFile(Info->LogFileHandle,
nullptr,
nullptr,
nullptr,
&ioStatus,
const_cast<PSTR>(Message),
static_cast<ULONG>(strlen(Message)),
nullptr,
nullptr);
if (!NT_SUCCESS(status))
{
//
// It could happen when you did not register IRP_SHUTDOWN and call
// LogIrpShutdownHandler() and the system tried to log to a file after
// a file system was unmounted.
//
goto Exit;
}
status = ZwFlushBuffersFile(Info->LogFileHandle, &ioStatus);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Exit:
return status;
}
/*!
@brief Buffers the log entry to the log buffer.
@param[in] Message - The log message to buffer.
@param[in,out] Info - Log buffer information.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpBufferMessage (
_In_ PCSTR Message,
_Inout_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
KLOCK_QUEUE_HANDLE lockHandle;
KIRQL oldIrql;
SIZE_T usedBufferSize;
//
// Acquire a spin lock to add the log safely.
//
oldIrql = KeGetCurrentIrql();
if (oldIrql < DISPATCH_LEVEL)
{
KeAcquireInStackQueuedSpinLock(&Info->SpinLock, &lockHandle);
}
else
{
KeAcquireInStackQueuedSpinLockAtDpcLevel(&Info->SpinLock, &lockHandle);
}
NT_ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
//
// Copy the current log to the buffer.
//
usedBufferSize = Info->LogBufferTail - Info->LogBufferHead;
status = RtlStringCchCopyA(const_cast<PSTR>(Info->LogBufferTail),
k_LogpBufferUsableSize - usedBufferSize,
Message);
//
// Update Info.LogMaxUsage if necessary.
//
if (NT_SUCCESS(status))
{
size_t messageLength;
messageLength = strlen(Message) + 1;
Info->LogBufferTail += messageLength;
usedBufferSize += messageLength;
if (usedBufferSize > Info->LogMaxUsage)
{
Info->LogMaxUsage = usedBufferSize;
}
}
else
{
Info->LogMaxUsage = k_LogpBufferSize;
}
*Info->LogBufferTail = ANSI_NULL;
if (oldIrql < DISPATCH_LEVEL)
{
KeReleaseInStackQueuedSpinLock(&lockHandle);
}
else
{
KeReleaseInStackQueuedSpinLockFromDpcLevel(&lockHandle);
}
return status;
}
/*!
@brief Processes all buffered log messages.
@param[in,out] Info - Log buffer information.
@details This function switches the current log buffer, saves the contents
of old buffer to the log file, and prints them out as necessary. This
function does not flush the log file, so code should call
LogpWriteMessageToFile() or ZwFlushBuffersFile() later.
*/
static
_Check_return_
NTSTATUS
LogpFlushLogBuffer (
_Inout_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
KLOCK_QUEUE_HANDLE lockHandle;
PSTR oldLogBuffer;
IO_STATUS_BLOCK ioStatus;
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
status = STATUS_SUCCESS;
//
// Enter a critical section and acquire a reader lock for Info in order to
// write a log file safely.
//
ExEnterCriticalRegionAndAcquireResourceExclusive(&Info->Resource);
//
// Acquire a spin lock for Info.LogBuffer(s) in order to switch its head
// safely.
//
KeAcquireInStackQueuedSpinLock(&Info->SpinLock, &lockHandle);
oldLogBuffer = Info->LogBufferHead;
Info->LogBufferHead = (oldLogBuffer == Info->LogBuffer1) ? Info->LogBuffer2
: Info->LogBuffer1;
Info->LogBufferHead[0] = ANSI_NULL;
Info->LogBufferTail = Info->LogBufferHead;
KeReleaseInStackQueuedSpinLock(&lockHandle);
//
// Write all log entries in old log buffer.
//
for (PSTR currentLogEntry = oldLogBuffer; currentLogEntry[0] != ANSI_NULL; /**/)
{
BOOLEAN printedOut;
size_t entryLength;
//
// Check the printed bit and clear it.
//
printedOut = LogpIsPrinted(currentLogEntry);
LogpSetPrintedBit(currentLogEntry, FALSE);
entryLength = strlen(currentLogEntry);
status = ZwWriteFile(Info->LogFileHandle,
nullptr,
nullptr,
nullptr,
&ioStatus,
currentLogEntry,
static_cast<ULONG>(entryLength),
nullptr,
nullptr);
if (!NT_SUCCESS(status))
{
//
// It could happen when you did not register IRP_SHUTDOWN and call
// LogIrpShutdownHandler() and the system tried to log to a file after
// a file system was unmounted.
//
NOTHING;
}
//
// Print it out if requested and the Message is not already printed out
//
if (printedOut == FALSE)
{
LogpDoDbgPrint(currentLogEntry);
}
currentLogEntry += entryLength + 1;
}
oldLogBuffer[0] = ANSI_NULL;
ExReleaseResourceAndLeaveCriticalRegion(&Info->Resource);
return status;
}
/*!
@brief Returns TRUE when a log file is opened.
@param[in] Info - Log buffer information.
@return TRUE when a log file is opened.
*/
static
_Check_return_
BOOLEAN
LogpIsLogFileActivated (
_In_ const LOG_BUFFER_INFO* Info
)
{
BOOLEAN activated;
if (Info->BufferFlushThreadShouldBeAlive != FALSE)
{
NT_ASSERT(Info->BufferFlushThreadHandle != nullptr);
NT_ASSERT(Info->LogFileHandle != nullptr);
activated = TRUE;
}
else
{
NT_ASSERT(Info->BufferFlushThreadHandle == nullptr);
NT_ASSERT(Info->LogFileHandle == nullptr);
activated = FALSE;
}
return activated;
}
/*!
@brief Returns TRUE when a log file is enabled.
@param[in] Info - Log buffer information.
@return TRUE when a log file is enabled.
*/
static
_Check_return_
BOOLEAN
LogpIsLogFileEnabled (
_In_ const LOG_BUFFER_INFO* Info
)
{
BOOLEAN enabled;
if (Info->LogBuffer1 != nullptr)
{
NT_ASSERT(Info->LogBuffer2 != nullptr);
NT_ASSERT(Info->LogBufferHead != nullptr);
NT_ASSERT(Info->LogBufferTail != nullptr);
enabled = TRUE;
}
else
{
NT_ASSERT(Info->LogBuffer2 == nullptr);
NT_ASSERT(Info->LogBufferHead == nullptr);
NT_ASSERT(Info->LogBufferTail == nullptr);
enabled = FALSE;
}
return enabled;
}
/*!
@brief Returns the function's base name.
@param[in] FunctionName - The function name given by the __FUNCTION__ macro.
@return The function's base name, for example, "MethodName" for
"NamespaceName::ClassName::MethodName".
*/
static
_Check_return_
PCSTR
LogpFindBaseFunctionName (
_In_ PCSTR FunctionName
)
{
PCSTR ptr;
PCSTR name;
name = ptr = FunctionName;
while (*(ptr++) != ANSI_NULL)
{
if (*ptr == ':')
{
name = ptr + 1;
}
}
return name;
}
/*!
@brief Logs the entry according to Attribute and the thread condition.
@param[in] Message - The log message to print or buffer.
@param[in] Attribute - The bit mask indicating how this message should be
printed out.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpPut (
_In_ PSTR Message,
_In_ ULONG Attribute
)
{
NTSTATUS status;
BOOLEAN callDbgPrint;
PLOG_BUFFER_INFO info;
status = STATUS_SUCCESS;
callDbgPrint = ((!BooleanFlagOn(Attribute, k_LogpLevelOptSafe)) &&
(KeGetCurrentIrql() < CLOCK_LEVEL));
//
// Log the entry to a file or buffer.
//
info = &g_LogpLogBufferInfo;
if (LogpIsLogFileEnabled(info) != FALSE)
{
//
// Can we log it to a file now?
//
if (!BooleanFlagOn(Attribute, k_LogpLevelOptSafe) &&
(KeGetCurrentIrql() == PASSIVE_LEVEL) &&
(LogpIsLogFileActivated(info) != FALSE))
{
#pragma warning(push)
#pragma warning(disable : __WARNING_INFERRED_IRQ_TOO_HIGH)
if (KeAreAllApcsDisabled() == FALSE)
{
//
// Yes, we can. Do it.
//
(VOID)LogpFlushLogBuffer(info);
status = LogpWriteMessageToFile(Message, info);
}
#pragma warning(pop)
}
else
{
//
// No, we cannot. Set the printed bit if needed, and then buffer it.
//
if (callDbgPrint != FALSE)
{
LogpSetPrintedBit(Message, TRUE);
}
status = LogpBufferMessage(Message, info);
LogpSetPrintedBit(Message, FALSE);
}
}
//
// Can it safely be printed?
//
if (callDbgPrint != FALSE)
{
LogpDoDbgPrint(Message);
}
return status;
}
/*!
@brief Concatenates meta information such as the current time and a process
ID to the user supplied log message.
@param[in] Level - The level of this log message.
@param[in] FunctionName - The name of the function originating this log message.
@param[in] LogMessage - The user supplied log message.
@param[out] LogBuffer - Buffer to store the concatenated message.
@param[in] LogBufferLength - The size of buffer in characters.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
static
_Check_return_
NTSTATUS
LogpMakePrefix (
_In_ ULONG Level,
_In_ PCSTR FunctionName,
_In_ PCSTR LogMessage,
_Out_writes_z_(LogBufferLength) PSTR LogBuffer,
_In_ SIZE_T LogBufferLength
)
{
NTSTATUS status;
PCSTR levelString;
CHAR time[20];
CHAR functionName[50];
CHAR processorNumber[10];
switch (Level)
{
case k_LogpLevelDebug:
levelString = "DBG\t";
break;
case k_LogpLevelInfo:
levelString = "INF\t";
break;
case k_LogpLevelWarn:
levelString = "WRN\t";
break;
case k_LogpLevelError:
levelString = "ERR\t";
break;
default:
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// Want the current time?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableTime))
{
TIME_FIELDS timeFields;
LARGE_INTEGER systemTime, localTime;
KeQuerySystemTime(&systemTime);
ExSystemTimeToLocalTime(&systemTime, &localTime);
RtlTimeToTimeFields(&localTime, &timeFields);
status = RtlStringCchPrintfA(time,
RTL_NUMBER_OF(time),
"%02hd:%02hd:%02hd.%03hd\t",
timeFields.Hour,
timeFields.Minute,
timeFields.Second,
timeFields.Milliseconds);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
time[0] = ANSI_NULL;
}
//
// Want the function name?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableFunctionName))
{
PCSTR baseFunctionName;
baseFunctionName = LogpFindBaseFunctionName(FunctionName);
status = RtlStringCchPrintfA(functionName,
RTL_NUMBER_OF(functionName),
"%-40s\t",
baseFunctionName);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
functionName[0] = ANSI_NULL;
}
//
// Want the processor number?
//
if (!BooleanFlagOn(g_LogpDebugFlag, k_LogOptDisableProcessorNumber))
{
status = RtlStringCchPrintfA(processorNumber,
RTL_NUMBER_OF(processorNumber),
"#%lu\t",
KeGetCurrentProcessorNumberEx(nullptr));
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
else
{
processorNumber[0] = ANSI_NULL;
}
//
// It uses PsGetProcessId(PsGetCurrentProcess()) instead of
// PsGetCurrentThreadProcessId() because the later sometimes returns
// unwanted value, for example, PID == 4 while its image name is not
// ntoskrnl.exe. The author is guessing that it is related to attaching
// processes but not quite sure. The former way works as expected.
//
status = RtlStringCchPrintfA(LogBuffer,
LogBufferLength,
"%s%s%s%5Iu\t%5Iu\t%-15s\t%s%s\r\n",
time,
levelString,
processorNumber,
reinterpret_cast<ULONG_PTR>(PsGetProcessId(PsGetCurrentProcess())),
reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()),
PsGetProcessImageFileName(PsGetCurrentProcess()),
functionName,
LogMessage);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Exit:
return status;
}
/*!
@brief Terminates a log file related code.
@param[in] Info - Log buffer information.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
LogpCleanupBufferInfo (
_In_ PLOG_BUFFER_INFO Info
)
{
NTSTATUS status;
PAGED_CODE();
//
// Closing the log buffer flush thread.
//
if (Info->BufferFlushThreadHandle != nullptr)
{
Info->BufferFlushThreadShouldBeAlive = FALSE;
status = ZwWaitForSingleObject(Info->BufferFlushThreadHandle, FALSE, nullptr);
NT_ASSERT(NT_SUCCESS(status));
ZwClose(Info->BufferFlushThreadHandle);
Info->BufferFlushThreadHandle = nullptr;
}
//
// Cleaning up other things.
//
if (Info->LogFileHandle != nullptr)
{
ZwClose(Info->LogFileHandle);
Info->LogFileHandle = nullptr;
}
if (Info->LogBuffer2 != nullptr)
{
ExFreePoolWithTag(Info->LogBuffer2, k_LogpPoolTag);
Info->LogBuffer2 = nullptr;
}
if (Info->LogBuffer1 != nullptr)
{
ExFreePoolWithTag(Info->LogBuffer1, k_LogpPoolTag);
Info->LogBuffer1 = nullptr;
}
if (Info->ResourceInitialized != FALSE)
{
ExDeleteResourceLite(&Info->Resource);
Info->ResourceInitialized = FALSE;
}
}
/*!
@brief Initializes a log file and starts a log buffer thread.
@param[in,out] Info - Log buffer information.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
LOGGING_PAGED
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpInitializeLogFile (
_Inout_ PLOG_BUFFER_INFO Info,
_Out_ PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
UNICODE_STRING logFilePathU;
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK ioStatus;
PAGED_CODE();
*ReinitRequired = FALSE;
if (Info->LogFileHandle != nullptr)
{
status = STATUS_SUCCESS;
goto Exit;
}
//
// Initialize a log file.
//
RtlInitUnicodeString(&logFilePathU, Info->LogFilePath);
InitializeObjectAttributes(&objectAttributes,
&logFilePathU,
OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
nullptr,
nullptr);
status = ZwCreateFile(&Info->LogFileHandle,
FILE_APPEND_DATA | SYNCHRONIZE,
&objectAttributes,
&ioStatus,
nullptr,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ,
FILE_OPEN_IF,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE,
nullptr,
0);
if (!NT_SUCCESS(status))
{
goto Exit;
}
//
// Initialize a log buffer flush thread.
//
Info->BufferFlushThreadShouldBeAlive = TRUE;
status = PsCreateSystemThread(&Info->BufferFlushThreadHandle,
THREAD_ALL_ACCESS,
nullptr,
nullptr,
nullptr,
LogpBufferFlushThreadRoutine,
Info);
if (!NT_SUCCESS(status))
{
ZwClose(Info->LogFileHandle);
Info->LogFileHandle = nullptr;
Info->BufferFlushThreadShouldBeAlive = FALSE;
goto Exit;
}
//
// Wait until the thread starts.
//
while (Info->BufferFlushThreadStarted == FALSE)
{
LogpSleep(100);
}
Exit:
if (status == STATUS_OBJECTID_NOT_FOUND)
{
*ReinitRequired = TRUE;
status = STATUS_SUCCESS;
}
return status;
}
/*!
@brief Initializes a log file related code such as a flushing thread.
@param[in] LogFilePath - A log file path.
@param[in,out] Info - Log buffer information.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
LOGGING_INIT
static
_IRQL_requires_max_(PASSIVE_LEVEL)
_Check_return_
NTSTATUS
LogpInitializeBufferInfo (
_In_ PCWSTR LogFilePath,
_Inout_ PLOG_BUFFER_INFO Info,
_Out_ PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
PAGED_CODE();
*ReinitRequired = FALSE;
KeInitializeSpinLock(&Info->SpinLock);
status = RtlStringCchCopyW(Info->LogFilePath,
RTL_NUMBER_OF_FIELD(LOG_BUFFER_INFO, LogFilePath),
LogFilePath);
if (!NT_SUCCESS(status))
{
goto Exit;
}
status = ExInitializeResourceLite(&Info->Resource);
if (!NT_SUCCESS(status))
{
goto Exit;
}
Info->ResourceInitialized = TRUE;
//
// Allocate two log buffers on NonPagedPool.
//
Info->LogBuffer1 = static_cast<PSTR>(ExAllocatePoolWithTag(NonPagedPool,
k_LogpBufferSize,
k_LogpPoolTag));
if (Info->LogBuffer1 == nullptr)
{
LogpCleanupBufferInfo(Info);
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
Info->LogBuffer2 = static_cast<PSTR>(ExAllocatePoolWithTag(NonPagedPool,
k_LogpBufferSize,
k_LogpPoolTag));
if (Info->LogBuffer2 == nullptr)
{
LogpCleanupBufferInfo(Info);
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
//
// Initialize these buffers. For diagnostic, fill them with some
// distinguishable bytes and then, ensure it is null-terminated.
//
RtlFillMemory(Info->LogBuffer1, k_LogpBufferSize, 0xff);
Info->LogBuffer1[0] = ANSI_NULL;
Info->LogBuffer1[k_LogpBufferSize - 1] = ANSI_NULL;
RtlFillMemory(Info->LogBuffer2, k_LogpBufferSize, 0xff);
Info->LogBuffer2[0] = ANSI_NULL;
Info->LogBuffer2[k_LogpBufferSize - 1] = ANSI_NULL;
//
// Buffer should be used is LogBuffer1, and location should be written logs
// is the head of the buffer.
//
Info->LogBufferHead = Info->LogBuffer1;
Info->LogBufferTail = Info->LogBuffer1;
status = LogpInitializeLogFile(Info, ReinitRequired);
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (*ReinitRequired != FALSE)
{
LOGGING_LOG_INFO("The log file needs to be activated later.");
}
Exit:
if (!NT_SUCCESS(status))
{
LogpCleanupBufferInfo(Info);
}
return status;
}
/*!
@brief Initializes the log system.
@param[in] Flag - A OR-ed Flag to control a log level and options. It is an
OR-ed value of kLogPutLevel* and kLogOpt*. For example,
k_LogPutLevelDebug | k_LogOptDisableFunctionName.
@param[in] LogFilePath - A log file path.
@param[out] ReinitRequired - A pointer to receive whether re-initialization
is required. When this parameter returns TRUE, the caller must call
LogRegisterReinitialization() to register re-initialization.
@return STATUS_SUCCESS on success or else on failure.
@details Allocates internal log buffers, initializes related resources,
starts a log flush thread and creates a log file if requested. This
function returns TRUE to ReinitRequired if a file-system is not
initialized yet.
*/
LOGGING_INIT
_Use_decl_annotations_
NTSTATUS
InitializeLogging (
ULONG Flag,
PCWSTR LogFilePath,
PBOOLEAN ReinitRequired
)
{
NTSTATUS status;
PAGED_CODE();
*ReinitRequired = FALSE;
g_LogpDriverVerified = (MmIsDriverVerifyingByAddress(&InitializeLogging) != FALSE);
g_LogpDebugFlag = Flag;
//
// Initialize a log file if a log file path is specified.
//
if (ARGUMENT_PRESENT(LogFilePath))
{
status = LogpInitializeBufferInfo(LogFilePath,
&g_LogpLogBufferInfo,
ReinitRequired);
if (!NT_SUCCESS(status))
{
goto Exit;
}
}
//
// Test the log.
//
status = LOGGING_LOG_INFO("Logger was %sinitialized",
(*ReinitRequired != FALSE) ? "partially " : "");
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (g_LogpDriverVerified != FALSE)
{
LOGGING_LOG_WARN("Driver being verified. All *_SAFE logs will be dropped.");
}
Exit:
if (!NT_SUCCESS(status))
{
if (LogFilePath != nullptr)
{
LogpCleanupBufferInfo(&g_LogpLogBufferInfo);
}
}
return status;
}
/*!
@brief Registers re-initialization.
@param[in] DriverObject - A driver object being loaded
@details A driver must call this function, or call CleanupLogging() and
return non STATUS_SUCCESS from DriverEntry() if InitializeLogging()
returned TRUE to ReinitRequired.If this function is called,
DriverEntry() must return STATUS_SUCCESS.
*/
LOGGING_INIT
_Use_decl_annotations_
VOID
LogRegisterReinitialization (
PDRIVER_OBJECT DriverObject
)
{
PAGED_CODE();
IoRegisterBootDriverReinitialization(DriverObject,
LogpReinitializationRoutine,
&g_LogpLogBufferInfo);
LOGGING_LOG_INFO("The log file will be activated later.");
}
/*!
@brief Initializes a log file at the re-initialization phase.
@param[in] DriverObject - The driver object to initialize.
@param[in] Context - The context pointer passed to the registration function.
@param[in] Count - The number indicating how many time this reinitialization
callback is invoked, starting at 1.
*/
LOGGING_PAGED
static
_Use_decl_annotations_
VOID
LogpReinitializationRoutine (
PDRIVER_OBJECT DriverObject,
PVOID Context,
ULONG Count
)
{
NTSTATUS status;
PLOG_BUFFER_INFO info;
BOOLEAN reinitRequired;
PAGED_CODE();
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(Count);
NT_ASSERT(ARGUMENT_PRESENT(Context));
_Analysis_assume_(ARGUMENT_PRESENT(Context));
info = static_cast<PLOG_BUFFER_INFO>(Context);
status = LogpInitializeLogFile(info, &reinitRequired);
if (!NT_SUCCESS(status))
{
NT_ASSERT(FALSE);
goto Exit;
}
NT_ASSERT(reinitRequired != FALSE);
LOGGING_LOG_INFO("The log file has been activated.");
Exit:
return;
}
/*!
@brief Terminates the log system. Should be called from an IRP_MJ_SHUTDOWN handler.
*/
LOGGING_PAGED
_Use_decl_annotations_
VOID
LogIrpShutdownHandler (
VOID
)
{
PLOG_BUFFER_INFO info;
PAGED_CODE();
LOGGING_LOG_DEBUG("Flushing... (Max log buffer usage = %Iu/%lu bytes)",
g_LogpLogBufferInfo.LogMaxUsage,
k_LogpBufferSize);
LOGGING_LOG_INFO("Bye!");
g_LogpDebugFlag = k_LogPutLevelDisable;
//
// Wait until the log buffer is emptied.
//
info = &g_LogpLogBufferInfo;
while (info->LogBufferHead[0] != ANSI_NULL)
{
LogpSleep(k_LogpLogFlushIntervalMsec);
}
}
/*!
@brief Terminates the log system. Should be called from a DriverUnload routine.
*/
LOGGING_PAGED
_Use_decl_annotations_
VOID
CleanupLogging (
VOID
)
{
PAGED_CODE();
LOGGING_LOG_DEBUG("Finalizing... (Max log buffer usage = %Iu/%lu bytes)",
g_LogpLogBufferInfo.LogMaxUsage,
k_LogpBufferSize);
LOGGING_LOG_INFO("Bye!");
g_LogpDebugFlag = k_LogPutLevelDisable;
LogpCleanupBufferInfo(&g_LogpLogBufferInfo);
}
/*!
@brief Logs a message; use HYPERPLATFORM_LOG_*() macros instead.
@param[in] Level - Severity of a message.
@param[in] FunctionName - A name of a function called this function.
@param[in] Format - A format string.
@return STATUS_SUCCESS on success.
@see LOGGING_LOG_DEBUG.
@see LOGGING_LOG_DEBUG_SAFE.
*/
_Use_decl_annotations_
NTSTATUS
LogpPrint (
ULONG Level,
PCSTR FunctionName,
PCSTR Format,
...
)
{
NTSTATUS status;
va_list args;
CHAR logMessage[412];
ULONG pureLevel;
ULONG attributes;
CHAR message[512];
if (!BooleanFlagOn(g_LogpDebugFlag, Level))
{
status = STATUS_SUCCESS;
goto Exit;
}
if ((g_LogpDriverVerified != FALSE) && BooleanFlagOn(Level, k_LogpLevelOptSafe))
{
status = STATUS_SUCCESS;
goto Exit;
}
va_start(args, Format);
status = RtlStringCchVPrintfA(logMessage,
RTL_NUMBER_OF(logMessage),
Format,
args);
va_end(args);
if (!NT_SUCCESS(status))
{
goto Exit;
}
if (logMessage[0] == ANSI_NULL)
{
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pureLevel = Level & 0xf0;
attributes = Level & 0x0f;
//
// A single entry of log should not exceed 512 bytes. See
// Reading and Filtering Debugging Messages in MSDN for details.
//
static_assert(RTL_NUMBER_OF(message) <= 512,
"One log message should not exceed 512 bytes.");
status = LogpMakePrefix(pureLevel,
FunctionName,
logMessage,
message,
RTL_NUMBER_OF(message));
if (!NT_SUCCESS(status))
{
goto Exit;
}
status = LogpPut(message, attributes);
if (!NT_SUCCESS(status))
{
NT_ASSERT(FALSE);
goto Exit;
}
Exit:
return status;
}
/*!
@brief The entry point of the buffer flush thread.
@param[in] StartContext - The thread context pointer.
@return STATUS_SUCCESS on success; otherwise, an appropriate error code.
@details A thread runs as long as Info.BufferFlushThreadShouldBeAlive is TRUE
and flushes a log buffer to a log file every k_LogpLogFlushIntervalMsec msec.
*/
LOGGING_PAGED
static
_Use_decl_annotations_
VOID
LogpBufferFlushThreadRoutine (
PVOID StartContext
)
{
NTSTATUS status;
PLOG_BUFFER_INFO info;
PAGED_CODE();
status = STATUS_SUCCESS;
info = static_cast<PLOG_BUFFER_INFO>(StartContext);
info->BufferFlushThreadStarted = TRUE;
LOGGING_LOG_DEBUG("Logger thread started");
while (info->BufferFlushThreadShouldBeAlive != FALSE)
{
NT_ASSERT(LogpIsLogFileActivated(info) != FALSE);
if (info->LogBufferHead[0] != ANSI_NULL)
{
NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
NT_ASSERT(KeAreAllApcsDisabled() == FALSE);
status = LogpFlushLogBuffer(info);
//
// Do not flush the file for overall performance. Even a case of
// bug check, we should be able to recover logs by looking at both
// log buffers.
//
}
LogpSleep(k_LogpLogFlushIntervalMsec);
}
PsTerminateSystemThread(status);
}
EXTERN_C_END
| 25.373972
| 100
| 0.608018
|
zanzo420
|
a2d9fb0c35da66d6d5f3f1caf14a1e5def905d43
| 3,820
|
cpp
|
C++
|
core/src/UI/UIFrameConstraint.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 36
|
2015-03-12T10:42:36.000Z
|
2022-01-12T04:20:40.000Z
|
core/src/UI/UIFrameConstraint.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 1
|
2015-12-17T00:25:43.000Z
|
2016-02-20T12:00:57.000Z
|
core/src/UI/UIFrameConstraint.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 6
|
2017-06-17T07:57:53.000Z
|
2019-04-09T21:11:24.000Z
|
/*
* Copyright (c) 2002-present, H. Hernán Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "UIFrameConstraint.hpp"
#include "UIFrame.hpp"
#include "SceneGraph/Node.hpp"
using namespace crimild;
using namespace ui;
UIFrameConstraint::UIFrameConstraint( Type type, crimild::Real32 value )
: _type( type ),
_value( value )
{
}
UIFrameConstraint::UIFrameConstraint( Type type, UIFrame *referenceFrame )
: _type( type ),
_referenceFrame( referenceFrame )
{
}
UIFrameConstraint::~UIFrameConstraint( void )
{
}
void UIFrameConstraint::apply( UIFrame *frame, UIFrame *parentFrame ) const
{
auto rect = frame->getExtensions();
auto ref = _referenceFrame != nullptr ? _referenceFrame->getExtensions() : parentFrame->getExtensions();
crimild::Real32 x = rect.getX();
crimild::Real32 y = rect.getY();
crimild::Real32 w = rect.getWidth();
crimild::Real32 h = rect.getHeight();
switch ( _type ) {
case Type::TOP:
y = ref.getY() + _value;
break;
case Type::LEFT:
x = ref.getX() + _value;
break;
case Type::RIGHT:
if ( _referenceFrame == nullptr ) {
x = ref.getX() + ref.getWidth() - w - _value;
}
else {
w = ref.getX() + ref.getWidth() - x;
}
break;
case Type::BOTTOM:
if ( _referenceFrame == nullptr ) {
y = ref.getY() + ref.getHeight() - h - _value;
}
else {
h = ref.getY() + ref.getHeight() - y;
}
break;
case Type::WIDTH:
w = _value;
break;
case Type::HEIGHT:
h = _value;
break;
case Type::EDGES:
x = 0;
y = 0;
w = ref.getWidth();
h = ref.getHeight();
break;
case Type::CENTER:
break;
case Type::CENTER_X:
x = ref.getX() + 0.5f * ( ref.getWidth() - w );
break;
case Type::CENTER_Y:
y = ref.getY() + 0.5f * ( ref.getHeight() - h );
break;
case Type::AFTER:
x = ref.getX() + ref.getWidth();
break;
case Type::BELOW:
y = ref.getY() + ref.getHeight();
break;
case Type::MARGIN:
x += _value;
y += _value;
w -= 2 * _value;
h -= 2 * _value;
break;
case Type::MARGIN_TOP:
y += _value;
break;
case Type::MARGIN_RIGHT:
w -= _value;
break;
case Type::MARGIN_BOTTOM:
h -= _value;
break;
case Type::MARGIN_LEFT:
x += _value;
break;
default:
break;
}
frame->setExtensions( Rectf( x, y, w, h ) );
}
| 24.33121
| 105
| 0.66466
|
hhsaez
|
a2da62d6cf8d8a0430ec9314853678048dca5350
| 8,973
|
cpp
|
C++
|
src/ofApp.cpp
|
clovistessier/kinect-hand-tracker-osc
|
4dfcfe3e0ed0c625644bb158d83033d5b8dab724
|
[
"MIT"
] | null | null | null |
src/ofApp.cpp
|
clovistessier/kinect-hand-tracker-osc
|
4dfcfe3e0ed0c625644bb158d83033d5b8dab724
|
[
"MIT"
] | null | null | null |
src/ofApp.cpp
|
clovistessier/kinect-hand-tracker-osc
|
4dfcfe3e0ed0c625644bb158d83033d5b8dab724
|
[
"MIT"
] | null | null | null |
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_VERBOSE);
// enable depth->video image calibration
kinect.setRegistration(true);
kinect.init();
//kinect.init(true); // shows infrared instead of RGB video image
//kinect.init(false, false); // disable video image (faster fps)
kinect.open(); // opens first available kinect
//kinect.open(1); // open a kinect by id, starting with 0 (sorted by serial # lexicographically))
//kinect.open("A00366902078051A"); // open a kinect using it's unique serial #
// print the intrinsic IR sensor values
if (kinect.isConnected())
{
ofLogNotice() << "sensor-emitter dist: " << kinect.getSensorEmitterDistance() << "cm";
ofLogNotice() << "sensor-camera dist: " << kinect.getSensorCameraDistance() << "cm";
ofLogNotice() << "zero plane pixel size: " << kinect.getZeroPlanePixelSize() << "mm";
ofLogNotice() << "zero plane dist: " << kinect.getZeroPlaneDistance() << "mm";
}
grayImage.allocate(kinect.width, kinect.height);
grayThreshNear.allocate(kinect.width, kinect.height);
grayThreshFar.allocate(kinect.width, kinect.height);
grayThreshRes.allocate(kinect.width, kinect.height);
ofSetFrameRate(60);
cameraAngle.addListener(this, &ofApp::cameraAngleChanged);
// give ourselves some sliders to adjust the CV params
gui.setup();
gui.add(cameraAngle.set("camera angle", 0, -30, 30));
gui.add(nearThreshold.set("near threshold", 255, 0, 255));
gui.add(farThreshold.set("far threshold", 200, 0, 255));
gui.add(minBlobArea.set("min blob area", 1000, 1, (kinect.width * kinect.height / 2)));
gui.add(maxBlobArea.set("max blob area", 10000, 1, (kinect.width * kinect.height)));
gui.add(nBlobsConsidered.set("blobs to look for", 2, 1, 10));
sender.setup("localhost", SEND_PORT);
// start off by drawing the gui
bDrawGui = true;
left.setup(0.25, 0.5, 0.5, ofColor::red);
right.setup(0.75, 0.5, 0.5, ofColor::blue);
}
//--------------------------------------------------------------
void ofApp::update()
{
kinect.update();
// there is a new frame and we are connected
if (kinect.isFrameNew())
{
// load grayscale image from the kinect source
ofPixels depthPixels = kinect.getDepthPixels();
depthPixels.mirror(false, true);
grayImage.setFromPixels(depthPixels);
// we do two thresholds - for the far plane and one for the near plane
// we then do a cvAnd to get the pixels which are a union of the two thresholds
grayThreshNear = grayImage;
grayThreshFar = grayImage;
grayThreshNear.threshold(nearThreshold.get(), true);
grayThreshFar.threshold(farThreshold.get());
cvAnd(grayThreshNear.getCvImage(), grayThreshFar.getCvImage(), grayThreshRes.getCvImage(), NULL);
// update the cv images
grayImage.flagImageChanged();
grayThreshRes.flagImageChanged();
// find the countours which are between the size of 20 pixels and 1/3 the w*h pixels.
// don't find holes because hands shouldn't have interior contours
contourFinder.findContours(grayThreshRes, minBlobArea.get(), maxBlobArea.get(), nBlobsConsidered.get(), false);
//store all the hand positions we found, normalized 0-1
hands.clear();
for (auto bit = contourFinder.blobs.begin(); bit != contourFinder.blobs.end(); bit++)
{
ofDefaultVec3 hand;
float x = bit->centroid.x;
float y = bit->centroid.y;
float depth = depthPixels.getColor(x, y).getBrightness();
hand.x = ofMap(x, 0, contourFinder.getWidth(), 0.0f, 1.0f, true);
hand.y = ofMap(y, 0, contourFinder.getHeight(), 0.0f, 1.0f, true);
hand.z = ofMap(depth, farThreshold.get(), nearThreshold.get(), 0.0f, 1.0f, true);
hands.push_back(hand);
}
int nPrevMatched = static_cast<int>(left.matched) + static_cast<int>(right.matched);
if (nPrevMatched == 0)
{
// match them to left and right
for (vector<ofDefaultVec3>::iterator itr = hands.begin(); itr != hands.end(); itr++)
{
if (itr->x > 0.5)
{
right.update(*itr);
}
else if (itr->x < 0.5)
{
left.update(*itr);
}
}
}
else if (nPrevMatched == 1)
{
Hand *prev;
Hand *other;
if (left.matched)
{
prev = &left;
other = &right
}
else
{
prev = &right;
other = &left;
}
vector<ofDefaultVec3>::iterator next;
float recordDistance = 10.0;
for (vector<ofDefaultVec3>::iterator itr = hands.begin(); itr != hands.end(); itr++)
{
float distSq = ofDistSquared(prev->pos.x, prev->pos.y, prev->pos.z, itr->x, itr->y, itr->z);
if (distSq < recordDistance)
{
next = itr;
recordDistance = distSq;
}
}
prev->update(*next);
hands.erase(next);
other->update(*(hands.begin()));
prev = nullptr;
other = nullptr;
next = nullptr;
}
}
ofxOscMessage m;
if (right.changed && right.valid)
{
m.setAddress("/kinect/right");
m.addFloatArg(right.pos.x);
m.addFloatArg(right.pos.y);
m.addFloatArg(right.pos.z);
sender.sendMessage(m, false);
right.changed = false;
}
if (left.changed && left.valid)
{
m.clear();
m.setAddress("/kinect/left");
m.addFloatArg(left.pos.x);
m.addFloatArg(left.pos.y);
m.addFloatArg(left.pos.z);
sender.sendMessage(m, false);
left.changed = false;
}
}
//--------------------------------------------------------------
void ofApp::draw()
{
// draw from the live kinect
// kinect.drawDepth(10, 10, 400, 300);
// kinect.draw(420, 10, 400, 300);
// grayImage.draw(10, 320, 400, 300);
// contourFinder.draw(10, 320, 400, 300);
ofSetColor(255, 255, 255);
kinectRGB = kinect.getPixels();
kinectRGB.mirror(false, true);
kinectRGB.draw(0, 0, 640, 480);
grayImage.draw(0, 480, 640, 480);
grayThreshRes.draw(0, 960, 640, 480);
ofSetColor(255, 0, 0);
ofNoFill();
contourFinder.draw(0, 960, 640, 480);
// ofSetColor(255, 0, 0);
// float rRad = ofMap(rh.z, farThreshold.get(), nearThreshold.get(), 5.0, 20.0, true);
// ofDrawCircle(rh.x, rh.y, rRad);
// ofSetColor(0, 0, 255);
// float lRad = ofMap(lh.z, farThreshold.get(), nearThreshold.get(), 5.0, 20.0, true);
// ofDrawCircle(lh.x, lh.y, lRad);
left.draw(0, 0, 640, 480);
right.draw(0, 0, 640, 480);
left.draw(0, 960, 640, 480);
right.draw(0, 960, 640, 480);
if (bDrawGui)
{
gui.draw();
}
}
//--------------------------------------------------------------
void ofApp::exit()
{
cameraAngle = 0;
kinect.setCameraTiltAngle(0);
kinect.close();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
switch (key)
{
case 'g':
bDrawGui = !bDrawGui;
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key)
{
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button)
{
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y)
{
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h)
{
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg)
{
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo)
{
}
void ofApp::cameraAngleChanged(int &cameraAngle)
{
// clamp the angle between -30 and 30 degrees
int new_angle = min(30, max(cameraAngle, -30));
kinect.setCameraTiltAngle(new_angle);
}
| 30.416949
| 119
| 0.513875
|
clovistessier
|
a2dd9ceaf0f037a2a325fdce8675ad0d1eff1c25
| 5,023
|
cpp
|
C++
|
cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
cat/src/v20180409/model/UpdateProbeTaskConfigurationListRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cat/v20180409/model/UpdateProbeTaskConfigurationListRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Cat::V20180409::Model;
using namespace std;
UpdateProbeTaskConfigurationListRequest::UpdateProbeTaskConfigurationListRequest() :
m_taskIdsHasBeenSet(false),
m_nodesHasBeenSet(false),
m_intervalHasBeenSet(false),
m_parametersHasBeenSet(false),
m_cronHasBeenSet(false)
{
}
string UpdateProbeTaskConfigurationListRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_taskIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TaskIds";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_taskIds.begin(); itr != m_taskIds.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_nodesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Nodes";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_nodes.begin(); itr != m_nodes.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_intervalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Interval";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_interval, allocator);
}
if (m_parametersHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Parameters";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_parameters.c_str(), allocator).Move(), allocator);
}
if (m_cronHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Cron";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_cron.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
vector<string> UpdateProbeTaskConfigurationListRequest::GetTaskIds() const
{
return m_taskIds;
}
void UpdateProbeTaskConfigurationListRequest::SetTaskIds(const vector<string>& _taskIds)
{
m_taskIds = _taskIds;
m_taskIdsHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::TaskIdsHasBeenSet() const
{
return m_taskIdsHasBeenSet;
}
vector<string> UpdateProbeTaskConfigurationListRequest::GetNodes() const
{
return m_nodes;
}
void UpdateProbeTaskConfigurationListRequest::SetNodes(const vector<string>& _nodes)
{
m_nodes = _nodes;
m_nodesHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::NodesHasBeenSet() const
{
return m_nodesHasBeenSet;
}
int64_t UpdateProbeTaskConfigurationListRequest::GetInterval() const
{
return m_interval;
}
void UpdateProbeTaskConfigurationListRequest::SetInterval(const int64_t& _interval)
{
m_interval = _interval;
m_intervalHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::IntervalHasBeenSet() const
{
return m_intervalHasBeenSet;
}
string UpdateProbeTaskConfigurationListRequest::GetParameters() const
{
return m_parameters;
}
void UpdateProbeTaskConfigurationListRequest::SetParameters(const string& _parameters)
{
m_parameters = _parameters;
m_parametersHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::ParametersHasBeenSet() const
{
return m_parametersHasBeenSet;
}
string UpdateProbeTaskConfigurationListRequest::GetCron() const
{
return m_cron;
}
void UpdateProbeTaskConfigurationListRequest::SetCron(const string& _cron)
{
m_cron = _cron;
m_cronHasBeenSet = true;
}
bool UpdateProbeTaskConfigurationListRequest::CronHasBeenSet() const
{
return m_cronHasBeenSet;
}
| 27.905556
| 104
| 0.720884
|
suluner
|
a2e3dfa6d740f7f8e49746e83d1d67d011e6d7a9
| 2,977
|
cpp
|
C++
|
src/ecckd/read_spectrum.cpp
|
ecmwf-ifs/ecckd
|
6115f9b8e29a55cb0f48916857bdc77fec41badd
|
[
"Apache-2.0"
] | null | null | null |
src/ecckd/read_spectrum.cpp
|
ecmwf-ifs/ecckd
|
6115f9b8e29a55cb0f48916857bdc77fec41badd
|
[
"Apache-2.0"
] | null | null | null |
src/ecckd/read_spectrum.cpp
|
ecmwf-ifs/ecckd
|
6115f9b8e29a55cb0f48916857bdc77fec41badd
|
[
"Apache-2.0"
] | null | null | null |
// read_spectrum.cpp - Read a profile of spectral optical depth
//
// Copyright (C) 2019- ECMWF.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
//
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Author: Robin Hogan
// Email: r.j.hogan@ecmwf.int
#include "Error.h"
#include "read_spectrum.h"
/// Read a profile of spectral optical depth from a NetCDF file
void
read_spectrum(std::string& file_name, ///< File name containing spectra
int iprof, ///< Index of profile (0 based)
adept::Vector& pressure_hl, ///< Half-level pressure (Pa)
adept::Vector& temperature_hl, ///< Half-level temperature (K)
adept::Vector& wavenumber_cm_1, ///< Wavenumber (cm-1)
adept::Vector& d_wavenumber_cm_1,///< Wavenumber interval (cm-1)
adept::Matrix& optical_depth, ///< Spectral optical depth
std::string& molecule, ///< Chemical formula of molecule
Real& reference_surface_vmr, ///< Reference volume mixing ratio (or -1.0)
adept::Vector& vmr_fl, ///< Volume mixing ratio on full levels
int* ncol ///< Number of columns in file
) {
DataFile file(file_name);
pressure_hl.clear();
wavenumber_cm_1.clear();
d_wavenumber_cm_1.clear();
optical_depth.clear();
if (ncol) {
intVector dims = file.size("pressure_hl");
*ncol = dims(0);
}
file.read(pressure_hl, "pressure_hl", iprof);
if (file.exist("temperature_hl")) {
file.read(temperature_hl, "temperature_hl", iprof);
}
else {
WARNING << "\"temperature_hl\" not present";
ENDWARNING;
}
file.read(wavenumber_cm_1, "wavenumber");
if (file.exist("d_wavenumber")) {
file.read(d_wavenumber_cm_1, "d_wavenumber");
}
else {
d_wavenumber_cm_1.resize(wavenumber_cm_1.size());
d_wavenumber_cm_1(range(1,end-1))
= 0.5 * (wavenumber_cm_1(range(2,end))
-wavenumber_cm_1(range(0,end-2)));
d_wavenumber_cm_1(0) = 0.5*d_wavenumber_cm_1(1);
d_wavenumber_cm_1(end) = 0.5*d_wavenumber_cm_1(end-1);
}
file.read(molecule, DATA_FILE_GLOBAL_SCOPE, "constituent_id");
if (file.exist("reference_surface_mole_fraction")) {
file.read(reference_surface_vmr, "reference_surface_mole_fraction");
}
else {
reference_surface_vmr = -1.0;
}
// Read volume mixing ratio on full levels, or negative value if not
// present (e.g. for hybrid spectra)
if (file.exist("mole_fraction_fl") && file.size("mole_fraction_fl").size() == 2) {
file.read(vmr_fl, "mole_fraction_fl", iprof);
}
else {
vmr_fl.resize(pressure_hl.size()-1);
vmr_fl = -1.0;
}
file.read(optical_depth, "optical_depth", iprof);
file.close();
}
| 33.829545
| 84
| 0.660396
|
ecmwf-ifs
|
a2e5c3e9fe23c448048b9172336d81df9c1b2f02
| 6,313
|
cc
|
C++
|
src/operators/test/operator_advdiff_surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 37
|
2017-04-26T16:27:07.000Z
|
2022-03-01T07:38:57.000Z
|
src/operators/test/operator_advdiff_surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 494
|
2016-09-14T02:31:13.000Z
|
2022-03-13T18:57:05.000Z
|
src/operators/test/operator_advdiff_surface.cc
|
fmyuan/amanzi
|
edb7b815ae6c22956c8519acb9d87b92a9915ed4
|
[
"RSA-MD"
] | 43
|
2016-09-26T17:58:40.000Z
|
2022-03-25T02:29:59.000Z
|
/*
Operators
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
*/
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
// TPLs
#include "Teuchos_RCP.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_ParameterXMLFileReader.hpp"
#include "UnitTest++.h"
// Amanzi
#include "GMVMesh.hh"
#include "MeshFactory.hh"
#include "Mesh_MSTK.hh"
#include "Tensor.hh"
#include "WhetStoneDefs.hh"
// Amanzi::Operators
#include "OperatorDefs.hh"
#include "PDE_Accumulation.hh"
#include "PDE_DiffusionMFD.hh"
#include "PDE_AdvectionUpwind.hh"
#include "Verification.hh"
/* *****************************************************************
* This test replaces tensor and boundary conditions by continuous
* functions. This is a prototype for future solvers.
* **************************************************************** */
TEST(ADVECTION_DIFFUSION_SURFACE) {
using namespace Teuchos;
using namespace Amanzi;
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
using namespace Amanzi::Operators;
auto comm = Amanzi::getDefaultComm();
int MyPID = comm->MyPID();
if (MyPID == 0) std::cout << "\nTest: Advection-duffusion on a surface" << std::endl;
// read parameter list
std::string xmlFileName = "test/operator_advdiff_surface.xml";
ParameterXMLFileReader xmlreader(xmlFileName);
ParameterList plist = xmlreader.getParameters();
// create an MSTK mesh framework
ParameterList region_list = plist.sublist("regions");
Teuchos::RCP<GeometricModel> gm = Teuchos::rcp(new GeometricModel(3, region_list, *comm));
MeshFactory meshfactory(comm,gm);
meshfactory.set_preference(Preference({Framework::MSTK}));
RCP<const Mesh> mesh = meshfactory.create(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 40, 40, 5);
RCP<const Mesh_MSTK> mesh_mstk = rcp_static_cast<const Mesh_MSTK>(mesh);
// extract surface mesh
std::vector<std::string> setnames;
setnames.push_back(std::string("Top surface"));
RCP<Mesh> surfmesh = meshfactory.create(mesh_mstk, setnames, AmanziMesh::FACE);
/* modify diffusion coefficient */
Teuchos::RCP<std::vector<WhetStone::Tensor> > K = Teuchos::rcp(new std::vector<WhetStone::Tensor>());
int ncells_owned = surfmesh->num_entities(AmanziMesh::CELL, AmanziMesh::Parallel_type::OWNED);
int nfaces_wghost = surfmesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::ALL);
for (int c = 0; c < ncells_owned; c++) {
WhetStone::Tensor Kc(2, 1);
Kc(0, 0) = 1.0;
K->push_back(Kc);
}
// create boundary data
Teuchos::RCP<BCs> bc = Teuchos::rcp(new BCs(surfmesh, AmanziMesh::FACE, WhetStone::DOF_Type::SCALAR));
std::vector<int>& bc_model = bc->bc_model();
std::vector<double>& bc_value = bc->bc_value();
for (int f = 0; f < nfaces_wghost; f++) {
const Point& xf = surfmesh->face_centroid(f);
if (fabs(xf[0]) < 1e-6 || fabs(xf[0] - 1.0) < 1e-6 ||
fabs(xf[1]) < 1e-6 || fabs(xf[1] - 1.0) < 1e-6) {
bc_model[f] = OPERATOR_BC_DIRICHLET;
bc_value[f] = xf[1] * xf[1];
}
}
// create diffusion operator
Teuchos::ParameterList olist = plist.sublist("PK operator").sublist("diffusion operator");
auto op_diff = Teuchos::rcp(new PDE_DiffusionMFD(olist, (Teuchos::RCP<const AmanziMesh::Mesh>) surfmesh));
op_diff->Init(olist);
op_diff->SetBCs(bc, bc);
const CompositeVectorSpace& cvs = op_diff->global_operator()->DomainMap();
// set up the diffusion operator
op_diff->Setup(K, Teuchos::null, Teuchos::null);
op_diff->UpdateMatrices(Teuchos::null, Teuchos::null);
// get the global operator
Teuchos::RCP<Operator> global_op = op_diff->global_operator();
// create an advection operator
Teuchos::ParameterList alist;
Teuchos::RCP<PDE_AdvectionUpwind> op_adv = Teuchos::rcp(new PDE_AdvectionUpwind(alist, global_op));
op_adv->SetBCs(bc, bc);
// get a flux field
Teuchos::RCP<CompositeVector> u = Teuchos::rcp(new CompositeVector(cvs));
Epetra_MultiVector& uf = *u->ViewComponent("face");
int nfaces = surfmesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED);
Point vel(4.0, 4.0, 0.0);
for (int f = 0; f < nfaces; f++) {
uf[0][f] = vel * surfmesh->face_normal(f);
}
op_adv->Setup(*u);
op_adv->UpdateMatrices(u.ptr());
// Add an accumulation term.
CompositeVector solution(cvs);
solution.PutScalar(0.0); // solution at time T=0
CompositeVector phi(cvs);
phi.PutScalar(0.2);
double dT = 0.02;
Teuchos::RCP<PDE_Accumulation> op_acc = Teuchos::rcp(new PDE_Accumulation(AmanziMesh::CELL, global_op));
op_acc->AddAccumulationDelta(solution, phi, phi, dT, "cell");
// BCs and assemble
op_diff->ApplyBCs(true, true, true);
op_adv->ApplyBCs(true, true, true);
// Create a preconditioner
ParameterList slist = plist.sublist("preconditioners").sublist("Hypre AMG");
global_op->set_inverse_parameters("Hypre AMG", plist.sublist("preconditioners"));
global_op->InitializeInverse();
global_op->ComputeInverse();
// Test SPD properties of the matrix and preconditioner.
VerificationCV ver(global_op);
ver.CheckMatrixSPD(false, true);
ver.CheckPreconditionerSPD(1e-12, false, true);
// Create a solver and solve the problem
CompositeVector& rhs = *global_op->rhs();
global_op->set_inverse_parameters("Hypre AMG", plist.sublist("preconditioners"), "AztecOO CG", plist.sublist("solvers"));
global_op->InitializeInverse();
global_op->ComputeInverse();
global_op->ApplyInverse(rhs, solution);
int num_itrs = global_op->num_itrs();
CHECK(num_itrs > 5 && num_itrs < 15);
ver.CheckResidual(solution, 1.0e-12);
if (MyPID == 0) {
std::cout << "pressure solver (gmres): ||r||=" << global_op->residual()
<< " itr=" << global_op->num_itrs()
<< " code=" << global_op->returned_code() << std::endl;
// visualization
const Epetra_MultiVector& p = *solution.ViewComponent("cell");
GMV::open_data_file(*surfmesh, (std::string)"operators.gmv");
GMV::start_data();
GMV::write_cell_data(p, 0, "solution");
GMV::close_data_file();
}
}
| 34.124324
| 123
| 0.685728
|
fmyuan
|
a2e7a249e78fa4d3b3edc478f44e4b482371cc90
| 399
|
cpp
|
C++
|
hw4-jasonsie88-master/src/lib/AST/return.cpp
|
jasonsie88/Intro._to_Compiler_Design
|
228205241fcba7eb3407ec72936a52b0266671bb
|
[
"MIT"
] | null | null | null |
hw4-jasonsie88-master/src/lib/AST/return.cpp
|
jasonsie88/Intro._to_Compiler_Design
|
228205241fcba7eb3407ec72936a52b0266671bb
|
[
"MIT"
] | null | null | null |
hw4-jasonsie88-master/src/lib/AST/return.cpp
|
jasonsie88/Intro._to_Compiler_Design
|
228205241fcba7eb3407ec72936a52b0266671bb
|
[
"MIT"
] | null | null | null |
#include "AST/return.hpp"
#include "visitor/AstNodeVisitor.hpp"
ReturnNode::ReturnNode(const uint32_t line, const uint32_t col,ExpressionNode *new_p_ret_val)
:AstNode{line, col}, m_ret_val(new_p_ret_val){}
void ReturnNode::accept(AstNodeVisitor &p_visitor){
p_visitor.visit(*this);
}
void ReturnNode::visitChildNodes(AstNodeVisitor &p_visitor) {
m_ret_val->accept(p_visitor);
}
| 28.5
| 93
| 0.759398
|
jasonsie88
|
0c029c40830e8334546c12956a738db707fc4389
| 604
|
cpp
|
C++
|
testsuite/foreach.cpp
|
mr-j0nes/RaftLib
|
19b2b5401365ba13788044bfbcca0820f48b650a
|
[
"Apache-2.0"
] | 759
|
2016-05-23T22:40:00.000Z
|
2022-03-25T09:05:41.000Z
|
testsuite/foreach.cpp
|
Myicefrog/RaftLib
|
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
|
[
"Apache-2.0"
] | 111
|
2016-05-24T02:30:14.000Z
|
2021-08-16T15:11:53.000Z
|
testsuite/foreach.cpp
|
Myicefrog/RaftLib
|
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
|
[
"Apache-2.0"
] | 116
|
2016-05-31T08:03:05.000Z
|
2022-03-01T00:54:31.000Z
|
#include <cassert>
#include <iostream>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <iterator>
#include <raft>
#include <raftio>
int
main()
{
const auto arr_size( 1000 );
using type_t = std::int32_t;
type_t *arr = (type_t*) malloc( sizeof( type_t ) * arr_size );
for( type_t i( 0 ); i < arr_size; i++ )
{
arr[ i ] = i;
}
using print = raft::print< type_t, '\n' >;
using foreach = raft::for_each< type_t >;
print p;
foreach fe( arr, arr_size, 1 );
raft::map m;
m += fe >> p;
m.exe();
free( arr );
return( EXIT_SUCCESS );
}
| 19.483871
| 65
| 0.577815
|
mr-j0nes
|
0c0be1417faa6d5fce8942a0e43d9fa420df59f7
| 198
|
cpp
|
C++
|
chap01_flow_control/practice03/02.cpp
|
kdzlvaids/problem_solving-pknu-2016
|
6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece
|
[
"MIT"
] | null | null | null |
chap01_flow_control/practice03/02.cpp
|
kdzlvaids/problem_solving-pknu-2016
|
6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece
|
[
"MIT"
] | null | null | null |
chap01_flow_control/practice03/02.cpp
|
kdzlvaids/problem_solving-pknu-2016
|
6a9e64f31f0d17c949e2b640fbd0a7628d1e5ece
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <math.h>
int main(void)
{
int num;
printf("Enter num= ");
scanf("%d", &num);
printf("Result: %d\n", (int)sqrt(num) * (int)sqrt(num));
return 0;
}
| 13.2
| 60
| 0.535354
|
kdzlvaids
|
0c0f57ed3a90897a3ab1010f4959333b6233ef25
| 9,766
|
cpp
|
C++
|
source/housys/test/hou/sys/test_file.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | 2
|
2018-04-12T20:59:20.000Z
|
2018-07-26T16:04:07.000Z
|
source/housys/test/hou/sys/test_file.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | null | null | null |
source/housys/test/hou/sys/test_file.cpp
|
DavideCorradiDev/houzi-game-engine
|
d704aa9c5b024300578aafe410b7299c4af4fcec
|
[
"MIT"
] | null | null | null |
// Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/test.hpp"
#include "hou/sys/test_data.hpp"
#include "hou/sys/file.hpp"
#include "hou/sys/sys_exceptions.hpp"
using namespace hou;
using namespace testing;
namespace
{
class test_file : public Test
{
public:
static const std::string filename;
static const std::string file_content;
public:
test_file();
virtual ~test_file();
};
using test_file_death_test = test_file;
template <typename Container>
bool testFileContents(
const std::string& filename, const Container& expected, file_type type);
const std::string test_file::filename
= get_output_dir() + u8"test_file-\U00004f60\U0000597d-BinaryFile.txt";
const std::string test_file::file_content = u8"This is\na test file";
test_file::test_file()
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(file_content);
}
test_file::~test_file()
{
remove_dir(filename);
}
template <typename Container>
bool testFileContents(
const std::string& filename, const Container& expected, file_type type)
{
file f(filename, file_open_mode::read, type);
Container buffer(f.get_byte_count(), 0);
f.read(buffer);
return expected == buffer;
}
} // namespace
TEST_F(test_file, creation)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_FALSE(f.eof());
EXPECT_FALSE(f.error());
EXPECT_TRUE(f.is_open());
EXPECT_EQ(file_content.size(), f.get_byte_count());
EXPECT_EQ(0, f.tell());
std::string content(f.get_byte_count(), 0);
f.read(content);
EXPECT_EQ(file_content, content);
}
TEST_F(test_file_death_test, creation_error)
{
std::string fake_name = "NotAValidName.txt";
EXPECT_ERROR_N(file f(fake_name, file_open_mode::read, file_type::binary),
file_open_error, fake_name);
}
TEST_F(test_file, move_constructor)
{
file f_dummy(filename, file_open_mode::read, file_type::binary);
file f(std::move(f_dummy));
EXPECT_FALSE(f.eof());
EXPECT_FALSE(f.error());
EXPECT_TRUE(f.is_open());
EXPECT_FALSE(f_dummy.is_open());
EXPECT_EQ(file_content.size(), f.get_byte_count());
EXPECT_EQ(0, f.tell());
std::string content(f.get_byte_count(), 0);
f.read(content);
EXPECT_EQ(file_content, content);
}
TEST_F(test_file, close)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_TRUE(f.is_open());
f.close();
EXPECT_FALSE(f.is_open());
}
TEST_F(test_file, cursor_positioning)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(0, f.tell());
f.seek_set(5);
EXPECT_EQ(5, f.tell());
f.seek_offset(2);
EXPECT_EQ(7, f.tell());
f.seek_offset(-3);
EXPECT_EQ(4, f.tell());
}
TEST_F(test_file_death_test, cursor_positioning_error)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_ERROR_0(f.seek_set(-1), cursor_error);
EXPECT_ERROR_0(f.seek_offset(-2), cursor_error);
// error flag is not set, only for read / write errors!
EXPECT_FALSE(f.error());
}
TEST_F(test_file, file_size)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(19u, f.get_byte_count());
}
TEST_F(test_file, file_size_cursor_position)
{
// Test if the size is correct if the cursor is not at the beginning, and if
// requesting the file size does not change the cursor position.
file f(filename, file_open_mode::read, file_type::binary);
char c;
f.getc(c);
f.getc(c);
long cur_pos = f.tell();
size_t file_size = f.get_byte_count();
EXPECT_EQ(cur_pos, f.tell());
EXPECT_EQ(19u, file_size);
}
TEST_F(test_file, getc_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
char c = 0;
size_t i = 0;
while(f.getc(c))
{
EXPECT_EQ(file_content[i], c);
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, putc_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
for(size_t i = 0; i < to_write.size(); ++i)
{
f.putc(to_write[i]);
}
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, gets_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
// Since a \0 is added, an extra character is needed
std::string s(4u, 'a');
// Gets stop reading at new lines, so we must be careful with that when
// performing the comparisons inside the test.
size_t cursor = 0;
while(size_t count = f.gets(s))
{
EXPECT_EQ(file_content.substr(cursor, count), s.substr(0u, count));
cursor += count;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, puts_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
f.puts(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_buffer_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::vector<char> buf(3u, 0);
size_t i = 0;
while(f.read(buf.data(), buf.size()) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_buffer_binary)
{
std::vector<char> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write.data(), to_write.size());
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_string_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::string buf(3u, 0);
size_t i = 0;
while(f.read(buf) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_string_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, read_container_binary)
{
file f(filename, file_open_mode::read, file_type::binary);
std::vector<char> buf(3u, 0);
size_t i = 0;
while(f.read(buf) == buf.size())
{
EXPECT_ARRAY_EQ(file_content.substr(i * buf.size(), buf.size()).data(),
buf.data(), buf.size());
++i;
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, write_container_binary)
{
std::vector<char> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::write, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(testFileContents(filename, to_write, file_type::binary));
}
TEST_F(test_file, append_binary)
{
std::string to_write = u8"I have\nwritten this";
{
file f(filename, file_open_mode::append, file_type::binary);
f.write(to_write);
}
EXPECT_TRUE(
testFileContents(filename, file_content + to_write, file_type::binary));
}
TEST_F(test_file_death_test, read_from_write_only_file)
{
file f(filename, file_open_mode::write, file_type::binary);
char c;
EXPECT_ERROR_0(f.getc(c), read_error);
std::string buffer(3u, 0);
EXPECT_ERROR_0(f.read(buffer), read_error);
#if defined(HOU_USE_EXCEPTIONS)
// With no exceptions handling, the DEPRECATED_HOU_EXPECT_ERROR macro does
// some magic, so that in the end the error flag is not set for f.
EXPECT_TRUE(f.error());
#endif
}
TEST_F(test_file_death_test, write_to_read_only_file)
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_ERROR_0(f.putc('a'), write_error);
std::string to_write = u8"I have\nwritten this";
EXPECT_ERROR_0(f.write(to_write), write_error);
#ifndef HOU_DISABLE_EXCEPTIONS
// With no exceptions handling, the DEPRECATED_HOU_EXPECT_ERROR macro does
// some magic, so that in the end the error flag is not set for f.
EXPECT_TRUE(f.error());
#endif
}
TEST_F(test_file, eof)
{
file f(filename, file_open_mode::read, file_type::binary);
char c = 0;
while(f.getc(c))
{
}
EXPECT_TRUE(f.eof());
}
TEST_F(test_file, get_size_after_putc)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.putc('a');
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + 1u, f.get_byte_count());
}
}
TEST_F(test_file, get_size_after_puts)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
std::string to_write = u8"New stuff!";
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.puts(to_write);
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + to_write.size(), f.get_byte_count());
}
}
TEST_F(test_file, get_size_after_write)
{
// Note: on some filesystems the size is not immediately updated.
// For this reason it is necessary to open the file again to check the size.
std::vector<uint16_t> to_write{23, 12, 15, 0, 14, 1};
{
file f(filename, file_open_mode::append, file_type::binary);
EXPECT_EQ(file_content.size(), f.get_byte_count());
f.write(to_write);
}
{
file f(filename, file_open_mode::read, file_type::binary);
EXPECT_EQ(file_content.size() + to_write.size() * sizeof(uint16_t),
f.get_byte_count());
}
}
// Test flush.
// Test flush error.
// Test close error.
// Test tell error.
// Tests for text files.
| 21.654102
| 78
| 0.693017
|
DavideCorradiDev
|
0c137e475906bda531b9c20539a798caea1e9b61
| 8,503
|
cpp
|
C++
|
src/cui-1.0.4/FORIS/FORIS.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | 1
|
2021-07-21T00:58:45.000Z
|
2021-07-21T00:58:45.000Z
|
src/cui-1.0.4/FORIS/FORIS.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | null | null | null |
src/cui-1.0.4/FORIS/FORIS.cpp
|
MaiReo/crass
|
11579527090faecab27f98b1e221172822928f57
|
[
"BSD-3-Clause"
] | null | null | null |
#include <windows.h>
#include <tchar.h>
#include <crass_types.h>
#include <acui.h>
#include <cui.h>
#include <package.h>
#include <resource.h>
#include <cui_error.h>
#include <stdio.h>
#include <zlib.h>
#include <utility.h>
/* 接口数据结构: 表示cui插件的一般信息 */
struct acui_information FORIS_cui_information = {
_T("STACK"), /* copyright */
_T(""), /* system */
_T(".GPK .GPK.*"), /* package */
_T("1.0.2"), /* revision */
_T("痴漢公賊"), /* author */
_T("2009-7-21 10:16"), /* date */
NULL, /* notion */
ACUI_ATTRIBUTE_LEVEL_STABLE
};
/* 所有的封包特定的数据结构都要放在这个#pragma段里 */
#pragma pack (1)
typedef struct {
s8 sig0[12];
u32 pidx_length;
s8 sig1[16];
} GPK_sig_t;
// gpk pidx format:
typedef struct {
unsigned short unilen; // unicode string length
unsigned short *unistring; // unicode string exclude NULL
unsigned short sub_version; // same as script.gpk.* suffix
unsigned short version; // major version(always 1)
unsigned short zero; // always 0
unsigned int offset; // pidx data file offset
unsigned int comprlen; // compressed pidx data length
unsigned char dflt[4]; // magic "DFLT" or " "
unsigned int uncomprlen; // raw pidx data length(if magic isn't DFLT, then this filed always zero)
unsigned char comprheadlen; // pidx data header length
unsigned char *comprheaddata; // pidx data
} GPK_pidx_t;
#pragma pack ()
/* .dat封包的索引项结构 */
typedef struct {
s8 name[256];
u32 name_length;
u32 offset;
u32 length;
} dat_entry_t;
static int no_exe_parameter = 1;
static u8 ciphercode[16];
static void GPK_decode(BYTE *buffer, DWORD buffer_len)
{
unsigned int i = 0, k = 0;
while (i < buffer_len) {
buffer[i++] ^= ciphercode[k++];
if (k >= 16)
k = 0;
}
}
/********************* GPK *********************/
/* 封包匹配回调函数 */
static int FORIS_GPK_match(struct package *pkg)
{
if (no_exe_parameter)
return -CUI_EMATCH;
if (pkg->pio->open(pkg, IO_READONLY))
return -CUI_EOPEN;
u32 offset;
pkg->pio->length_of(pkg, &offset);
offset -= sizeof(GPK_sig_t);
if (pkg->pio->seek(pkg, offset, IO_SEEK_SET)) {
pkg->pio->close(pkg);
return -CUI_ESEEK;
}
GPK_sig_t GPK_sig;
if (pkg->pio->read(pkg, &GPK_sig, sizeof(GPK_sig))) {
pkg->pio->close(pkg);
return -CUI_EREAD;
}
#define GPK_TAILER_IDENT0 "STKFile0PIDX"
#define GPK_TAILER_IDENT1 "STKFile0PACKFILE"
if (strncmp(GPK_TAILER_IDENT0, GPK_sig.sig0, strlen(GPK_TAILER_IDENT0))
|| strncmp(GPK_TAILER_IDENT1, GPK_sig.sig1, strlen(GPK_TAILER_IDENT1))) {
pkg->pio->close(pkg);
return -CUI_EMATCH;
}
return 0;
}
/* 封包索引目录提取函数 */
static int FORIS_GPK_extract_directory(struct package *pkg,
struct package_directory *pkg_dir)
{
u32 offset;
pkg->pio->length_of(pkg, &offset);
offset -= sizeof(GPK_sig_t);
GPK_sig_t GPK_sig;
if (pkg->pio->readvec(pkg, &GPK_sig, sizeof(GPK_sig), offset, IO_SEEK_SET))
return -CUI_EREADVEC;
u32 comprlen = GPK_sig.pidx_length;
offset -= comprlen; /* point to pidx segment */
if (pkg->pio->seek(pkg, offset, IO_SEEK_SET))
return -CUI_ESEEK;
BYTE *compr = new BYTE[comprlen];
if (!compr)
return -CUI_EMEM;
if (pkg->pio->read(pkg, compr, comprlen)) {
delete [] compr;
return -CUI_EREAD;
}
GPK_decode(compr, comprlen);
u32 uncomprlen = *(u32 *)compr;
comprlen -= 4;
BYTE *uncompr = new BYTE[uncomprlen];
if (!uncompr) {
delete [] compr;
return -CUI_EMEM;
}
DWORD act_uncomprlen = uncomprlen;
if (uncompress(uncompr, &act_uncomprlen, compr + 4, comprlen) != Z_OK) {
delete [] uncompr;
delete [] compr;
return -CUI_EUNCOMPR;
}
delete [] compr;
BYTE *p = uncompr;
pkg_dir->index_entries = 0;
while (1) {
u16 nlen = *(u16 *)p;
if (!nlen)
break;
p += 2 + nlen * 2 + 22;
p += *p + 1;
pkg_dir->index_entries++;
}
pkg_dir->directory = uncompr;
pkg_dir->directory_length = act_uncomprlen;
pkg_dir->flags = PKG_DIR_FLAG_VARLEN;
return 0;
}
/* 封包索引项解析函数 */
static int FORIS_GPK_parse_resource_info(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *entry = (BYTE *)pkg_res->actual_index_entry;
pkg_res->name_length = *(u16 *)entry;
entry += 2;
wcsncpy((WCHAR *)pkg_res->name, (WCHAR *)entry, pkg_res->name_length);
entry += pkg_res->name_length * 2 + 6;
pkg_res->offset = *(u32 *)entry;
entry += 4;
pkg_res->raw_data_length = *(u32 *)entry;
entry += 4;
/* magic "DFLT" or " ",
* if magic isn't DFLT, this filed always zero
*/
entry += 4;
pkg_res->actual_data_length = *(u32 *)entry;
entry += 4;
BYTE compr_head_len = *entry;
pkg_res->actual_index_entry_length = 2 + pkg_res->name_length * 2
+ 22 + compr_head_len + 1;
pkg_res->flags = PKG_RES_FLAG_UNICODE;
return 0;
}
/* 封包资源提取函数 */
static int FORIS_GPK_extract_resource(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *entry = (BYTE *)pkg_res->actual_index_entry
+ 2 + pkg_res->name_length * 2 + 22;
BYTE compr_head_len = *entry++;
DWORD comprlen = compr_head_len + pkg_res->raw_data_length;
BYTE *compr = new BYTE[comprlen];
if (!compr)
return -CUI_EMEM;
memcpy(compr, entry, compr_head_len);
if (pkg->pio->readvec(pkg, compr + compr_head_len, pkg_res->raw_data_length,
pkg_res->offset, IO_SEEK_SET)) {
delete [] compr;
return -CUI_EREADVEC;
}
BYTE *uncompr;
if (pkg_res->actual_data_length) {
DWORD uncomprlen = pkg_res->actual_data_length;
uncompr = new BYTE[uncomprlen];
if (!uncompr) {
delete [] compr;
return -CUI_EMEM;
}
if (uncompress(uncompr, &uncomprlen, compr, comprlen) != Z_OK) {
delete [] uncompr;
delete [] compr;
return -CUI_EUNCOMPR;
}
} else
uncompr = NULL;
pkg_res->raw_data = compr;
pkg_res->actual_data = uncompr;
return 0;
}
/* 资源保存函数 */
static int FORIS_GPK_save_resource(struct resource *res,
struct package_resource *pkg_res)
{
if (res->rio->create(res))
return -CUI_ECREATE;
if (pkg_res->actual_data && pkg_res->actual_data_length) {
if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
} else if (pkg_res->raw_data && pkg_res->raw_data_length) {
if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
}
res->rio->close(res);
return 0;
}
/* 封包资源释放函数 */
static void FORIS_GPK_release_resource(struct package *pkg,
struct package_resource *pkg_res)
{
if (pkg_res->actual_data) {
delete [] pkg_res->actual_data;
pkg_res->actual_data = NULL;
}
if (pkg_res->raw_data) {
delete [] pkg_res->raw_data;
pkg_res->raw_data = NULL;
}
}
/* 封包卸载函数 */
static void FORIS_GPK_release(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg_dir->directory) {
delete [] pkg_dir->directory;
pkg_dir->directory = NULL;
}
pkg->pio->close(pkg);
}
/* 封包处理回调函数集合 */
static cui_ext_operation FORIS_GPK_operation = {
FORIS_GPK_match, /* match */
FORIS_GPK_extract_directory, /* extract_directory */
FORIS_GPK_parse_resource_info, /* parse_resource_info */
FORIS_GPK_extract_resource, /* extract_resource */
FORIS_GPK_save_resource, /* save_resource */
FORIS_GPK_release_resource, /* release_resource */
FORIS_GPK_release /* release */
};
/* 接口函数: 向cui_core注册支持的封包类型 */
int CALLBACK FORIS_register_cui(struct cui_register_callback *callback)
{
if (callback->add_extension(callback->cui, _T(".GPK"), NULL,
NULL, &FORIS_GPK_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR))
return -1;
if (callback->add_extension(callback->cui, _T(".GPK.*"), NULL,
NULL, &FORIS_GPK_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR))
return -1;
const char *exe_file = get_options("exe");
no_exe_parameter = 1;
if (exe_file) {
HMODULE exe = LoadLibraryA(exe_file);
if ((DWORD)exe > 31) {
HRSRC code = FindResourceA(exe, "CIPHERCODE", "CODE");
if (code) {
DWORD sz = SizeofResource(exe, code);
if (sz == 16) {
HGLOBAL hsrc = LoadResource(exe, code);
if (hsrc) {
LPVOID cipher = LockResource(hsrc);
if (cipher) {
memcpy(ciphercode, cipher, 16);
no_exe_parameter = 0;
}
FreeResource(hsrc);
}
} else if (sz == 20) { // SchoolDays
HGLOBAL hsrc = LoadResource(exe, code);
if (hsrc) {
LPVOID cipher = LockResource(hsrc);
if (cipher && *(u32 *)cipher == 16) {
memcpy(ciphercode, (BYTE *)cipher + 4, 16);
no_exe_parameter = 0;
}
FreeResource(hsrc);
}
}
}
FreeLibrary(exe);
}
}
return 0;
}
}
| 24.363897
| 100
| 0.66553
|
MaiReo
|
0c1a12519fa813eaadd222f93c3a8b005d870d26
| 821
|
cc
|
C++
|
gui/components/gui_colorbox.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | 292
|
2015-01-04T20:33:57.000Z
|
2022-03-21T21:36:25.000Z
|
gui/components/gui_colorbox.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | 32
|
2018-01-31T11:11:16.000Z
|
2022-03-03T14:37:58.000Z
|
gui/components/gui_colorbox.cc
|
BradenButler/simutrans
|
86f29844625119182896e0e08d7b775bc847758d
|
[
"Artistic-1.0"
] | 126
|
2015-01-05T10:27:14.000Z
|
2022-03-05T14:08:50.000Z
|
/*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include "gui_colorbox.h"
#include "../gui_theme.h"
#include "../../display/simgraph.h"
gui_colorbox_t::gui_colorbox_t(PIXVAL c)
{
color = c;
max_size = scr_size(scr_size::inf.w, D_INDICATOR_HEIGHT);
}
scr_size gui_colorbox_t::get_min_size() const
{
return scr_size(D_INDICATOR_WIDTH, D_INDICATOR_HEIGHT);
}
scr_size gui_colorbox_t::get_max_size() const
{
return scr_size(max_size.w, D_INDICATOR_HEIGHT);
}
void gui_colorbox_t::draw(scr_coord offset)
{
offset += pos;
display_ddd_box_clip_rgb(offset.x, offset.y, size.w, D_INDICATOR_HEIGHT, color_idx_to_rgb(MN_GREY0), color_idx_to_rgb(MN_GREY4));
display_fillbox_wh_clip_rgb(offset.x + 1, offset.y + 1, size.w - 2, D_INDICATOR_HEIGHT-2, color, true);
}
| 23.457143
| 130
| 0.752741
|
BradenButler
|
0c30ba7788d872e1aa541f6a0b167b4fb51ea633
| 7,272
|
cpp
|
C++
|
Overlay/src/Loader.cpp
|
narindertamber66/https-github.com-acidicoala-ScreamAPI
|
4f7e0dfae3be99526dc21b3eed91ae2231f1a209
|
[
"0BSD"
] | null | null | null |
Overlay/src/Loader.cpp
|
narindertamber66/https-github.com-acidicoala-ScreamAPI
|
4f7e0dfae3be99526dc21b3eed91ae2231f1a209
|
[
"0BSD"
] | null | null | null |
Overlay/src/Loader.cpp
|
narindertamber66/https-github.com-acidicoala-ScreamAPI
|
4f7e0dfae3be99526dc21b3eed91ae2231f1a209
|
[
"0BSD"
] | null | null | null |
#include "pch.h"
#include "Loader.h"
#include "Overlay.h"
#include <fstream>
#include <future>
#include <Config.h>
// Instructions on how to build libcurl on Windows can be found here:
// https://www.youtube.com/watch?reload=9&v=q_mXVZ6VJs4
#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"Wldap32.lib")
#pragma comment(lib,"Crypt32.lib")
#pragma comment(lib,"Normaliz.lib")
#define CURL_STATICLIB
#include "curl/curl.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#define STBI_ONLY_JPEG
#include "stb_image.h"
namespace Loader{
#define CACHE_DIR ".ScreamApi_Cache"
/**
* Initialize the loader and its dependencies.
* @return true if initialization was successfull
* false if there was an error in initialization
*/
bool init(){
// Init curl first
#pragma warning(suppress: 26812) // Unscoped enum...
CURLcode errorCode = curl_global_init(CURL_GLOBAL_ALL);
if(errorCode != CURLE_OK){
// Something went wrong
Logger::error("Loader: Failed to initialize curl. Error code: %d", errorCode);
return false;
}
// Create directory if it doesn't already exist
auto success = CreateDirectoryA(CACHE_DIR, NULL); // FIXME: Non-unicode function
if(success || GetLastError() == ERROR_ALREADY_EXISTS){
Logger::ovrly("Loader: Successfully initialized");
return true;
} else{
Logger::error("Loader: Failed to create '%s' directory. Error code: %d", CACHE_DIR, GetLastError());
return false;
}
}
void shutdown(){
curl_global_cleanup();
if(!Config::CacheIcons()){
if(!RemoveDirectoryA(CACHE_DIR))
Logger::error("Failed to remove %s directory. Error code: %d", CACHE_DIR, GetLastError());
}
Logger::ovrly("Loader: Shutdown");
}
// Helper utility to generate icon path based on the AchievementID
std::string getIconPath(Overlay_Achievement& achievement){
return CACHE_DIR"\\" + std::string(achievement.AchievementId) + ".png";
}
// Simple helper function to load an image into a DX11 texture with common settings
void loadIconTexture(Overlay_Achievement& achievement){
static std::mutex loadIconMutex;
{ // Code block for lock_guard destructor to release lock
std::lock_guard<std::mutex> guard(loadIconMutex);
Logger::ovrly("Loading icon texure for achievement: %s", achievement.AchievementId);
auto iconPath = getIconPath(achievement);
// Load from disk into a raw RGBA buffer
int image_width = 0;
int image_height = 0;
auto* image_data = stbi_load(iconPath.c_str(), &image_width, &image_height, NULL, 4);
if(image_data == NULL){
Logger::error("Failed to load icon: %s. Failure reason: %s", iconPath.c_str(), stbi_failure_reason());
return;
}
// Create texture
D3D11_TEXTURE2D_DESC desc;
desc.Width = image_width;
desc.Height = image_height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
ID3D11Texture2D* pTexture = nullptr;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = static_cast<UINT>(desc.Width * 4);
subResource.SysMemSlicePitch = 0;
// FIXME: This function call somtimes messes up the Railway Empire. No idea why.
auto result = Overlay::gD3D11Device->CreateTexture2D(&desc, &subResource, &pTexture);
if(SUCCEEDED(result)){
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
memset(&srvDesc, 0, sizeof(srvDesc));
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
result = Overlay::gD3D11Device->CreateShaderResourceView(pTexture, &srvDesc, &achievement.IconTexture);
pTexture->Release();
if(FAILED(result))
Logger::error("Failed to create shader resource view. Error code: %x", result);
} else {
Logger::error("Failed to load the texture. Error code: %x", result);
}
stbi_image_free(image_data);
}
}
// Downloads the online icon into local cache folder
void downloadFile(const char* url, const char* filename){
FILE* file_handle;
CURL* curl_handle = curl_easy_init();
Logger::ovrly("Downloading icon to: %s", filename);
errno_t err = fopen_s(&file_handle, filename, "wb");
if(!err && file_handle != NULL){
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, file_handle);
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_perform(curl_handle);
fclose(file_handle);
} else{
Logger::error("Failed to open file for writing: %s", filename);
}
curl_easy_cleanup(curl_handle);
}
int getLocalFileSize(WIN32_FILE_ATTRIBUTE_DATA& fileInfo){
LARGE_INTEGER size;
size.HighPart = fileInfo.nFileSizeHigh;
size.LowPart = fileInfo.nFileSizeLow;
return (int) size.QuadPart;
}
// Downloads only the file headers and retuns the size of the file
int getOnlineFileSize(const char* url){
CURL* curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1);
curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1);
curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_perform(curl_handle);
curl_off_t contentLength;
curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &contentLength);
curl_easy_cleanup(curl_handle);
return (int) contentLength;
}
void downloadIconIfNecessary(Overlay_Achievement& achievement){
auto iconPath = getIconPath(achievement);
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
auto fileAttributes = GetFileAttributesExA(iconPath.c_str(), GetFileExInfoStandard, &fileInfo);
if(fileAttributes){
if(Config::ValidateIcons()){
// File exists
if(getLocalFileSize(fileInfo) == getOnlineFileSize(achievement.UnlockedIconURL)) {
Logger::ovrly("Using cached icon: %s", iconPath.c_str());
} else{
// Download the file again if the local version is different from online one
downloadFile(achievement.UnlockedIconURL, iconPath.c_str());
}
} else {
Logger::ovrly("Using cached icon: %s", iconPath.c_str());
}
} else if(GetLastError() == ERROR_FILE_NOT_FOUND){
// File doesn't exist
downloadFile(achievement.UnlockedIconURL, iconPath.c_str());
} else{
// File exists, but we could not read it's attributes.
Logger::error("Failed to read file attributes. Error code: %d", GetLastError());
// TODO: Use FormatMessage to print user-friendly error message?
return;
}
loadIconTexture(achievement);
if(!Config::CacheIcons()){
if(!DeleteFileA(iconPath.c_str()))
Logger::error("Failed to remove %s file. Error code: %d", iconPath.c_str(), GetLastError());
}
}
// Asynchronously downloads the icons and loads them into textures in order to keep UI responsive
void AsyncLoadIcons(){
if(Config::LoadIcons() && init()){
static std::vector<std::future<void>>asyncJobs;
for(auto& achievement : *Overlay::achievements){
asyncJobs.emplace_back(std::async(std::launch::async, downloadIconIfNecessary, std::ref(achievement)));
}
static auto awaitFuture = std::async(std::launch::async, [&](){
for(auto& job : asyncJobs){
// Asynchronously wait for all other async jobs to be completed
job.wait();
}
asyncJobs.clear();
shutdown();
});
}
}
}
| 32.609865
| 106
| 0.738036
|
narindertamber66
|
0c35d1e8e44f5d8b9e7bd8c00e97fe10fc7c2e6a
| 1,325
|
cpp
|
C++
|
test/result.cpp
|
elpescado/core-jsonrpc
|
12f85727168086a0a964aa9b934cd62f360c4cc3
|
[
"MIT"
] | null | null | null |
test/result.cpp
|
elpescado/core-jsonrpc
|
12f85727168086a0a964aa9b934cd62f360c4cc3
|
[
"MIT"
] | null | null | null |
test/result.cpp
|
elpescado/core-jsonrpc
|
12f85727168086a0a964aa9b934cd62f360c4cc3
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "result.h"
#include <json/value.h>
using namespace core::jsonrpc;
TEST(ResultTest, TestConstructor)
{
Json::Value id(5);
Result res(id);
ASSERT_EQ(id, res.id());
ASSERT_EQ(ResultState::None, res.state());
ASSERT_THROW(res.result(), std::invalid_argument);
}
TEST(ResultTest, TestSetResult)
{
Json::Value id(6);
Json::Value result("A Test Result");
Result res(id);
res.set_result(result);
ASSERT_EQ(ResultState::Result, res.state());
ASSERT_EQ(result, res.result());
}
TEST(ResultTest, TestSetResultTwice)
{
Json::Value id(6);
Json::Value result("A Test Result");
Result res(id);
res.set_result(result);
ASSERT_THROW(res.set_result(result), std::invalid_argument);
}
TEST(ResultTest, TestSignalStateChanged)
{
bool fired = false;
Json::Value id(7);
Json::Value result("A Test Result");
Result res(id);
res.signal_state_changed.connect([&fired](){
fired = true;
});
res.set_result(result);
ASSERT_EQ(true, fired);
}
TEST(ResultTest, TestSetError)
{
bool fired = false;
Json::Value id("8");
Result res(id);
res.signal_state_changed.connect([&fired](){
fired = true;
});
res.set_error(Error(42, "Malfunction"));
ASSERT_EQ(true, fired);
Error e = res.error();
ASSERT_EQ(42, e.code());
ASSERT_EQ(std::string("Malfunction"), e.message());
}
| 18.150685
| 61
| 0.693585
|
elpescado
|
0c38056fb841e231d209450010e13fbe78092b17
| 764
|
cpp
|
C++
|
Projects/CoX/Servers/MapServer/MapTemplate.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/CoX/Servers/MapServer/MapTemplate.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/CoX/Servers/MapServer/MapTemplate.cpp
|
teronis84/Segs
|
71ac841a079fd769c3a45836ac60f34e4fff32b9
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Super Entity Game Server Project
* http://segs.sf.net/
* Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt)
* This software is licensed! (See License.txt for details)
*
*/
#include "MapTemplate.h"
#include "MapInstance.h"
MapTemplate::MapTemplate(const std::string &/*template_filename*/)
{
}
MapInstance * MapTemplate::get_instance()
{
if(m_instances.size()==0)
{
m_instances.push_back(new MapInstance("City_00_01")); // should be replaced with proper cloning of map structure
m_instances.back()->activate(THR_NEW_LWP|THR_JOINABLE|THR_INHERIT_SCHED,1);
m_instances.back()->start();
}
return m_instances.front();
}
size_t MapTemplate::num_instances()
{
return m_instances.size();
}
| 25.466667
| 120
| 0.697644
|
teronis84
|
0c3b4d5e2326499867cf563347d0eeb19a0658e8
| 558
|
cpp
|
C++
|
src/cricketer.cpp
|
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
|
8a324462d93db49a6a2c88fb382bca110c7ec611
|
[
"MIT"
] | null | null | null |
src/cricketer.cpp
|
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
|
8a324462d93db49a6a2c88fb382bca110c7ec611
|
[
"MIT"
] | null | null | null |
src/cricketer.cpp
|
tomdodd4598/UCL-PHAS0100-CandamirTilesExample1
|
8a324462d93db49a6a2c88fb382bca110c7ec611
|
[
"MIT"
] | null | null | null |
#include "cricketer.hpp"
#include "equipment.hpp"
#include <string>
namespace cricket {
std::string Cricketer::equipment_string() const {
std::string str = "[";
bool begin = true;
for (auto& e : equipment_list) {
if (begin) {
begin = false;
}
else {
str += ", ";
}
str += e->type_string();
str += ": {";
str += e->to_string();
str += '}';
}
str += ']';
return str;
}
}
| 19.241379
| 53
| 0.399642
|
tomdodd4598
|
0c41a2e57c2817dfdfec15bff79f24721e569092
| 171,616
|
cpp
|
C++
|
AIPDebug/Display-Interface/w_conf.cpp
|
Bluce-Song/Master-AIP
|
1757ab392504d839de89460da17630d268ff3eed
|
[
"Apache-2.0"
] | null | null | null |
AIPDebug/Display-Interface/w_conf.cpp
|
Bluce-Song/Master-AIP
|
1757ab392504d839de89460da17630d268ff3eed
|
[
"Apache-2.0"
] | null | null | null |
AIPDebug/Display-Interface/w_conf.cpp
|
Bluce-Song/Master-AIP
|
1757ab392504d839de89460da17630d268ff3eed
|
[
"Apache-2.0"
] | null | null | null |
#include "w_conf.h"
#include "ui_w_conf.h"
static bool Clicked = true;
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 设置界面初始化
******************************************************************************/
w_Conf::w_Conf(QWidget *parent) :
QWidget(parent),
ui(new Ui::w_Conf)
{
this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); // 去掉标题栏
ui->setupUi(this);
WDLR = NULL; // -电阻界面为空
WMAG = NULL; // -反嵌界面为空
WIR = NULL; // -绝缘界面为空
WACW = NULL; // -交耐界面为空
WDCW = NULL; // -直耐界面为空
WIMP = NULL; // -匝间界面为空
WPWR = NULL; // -功率界面为空
WINDL = NULL; // -电感界面为空
WBLOCK = NULL; // -堵转界面为空
WLVS = NULL; // -低启界面为空
WPG = NULL; // -霍尔界面为空
WLOAD = NULL; // -负载界面为空
WNoLoad = NULL; // -空载界面为空
WBEMF = NULL; // -BEMF界面为空
btnGroup_function = new QButtonGroup; // -配置按钮
btnGroup_function->addButton(ui->Key_A, Qt::Key_A);
btnGroup_function->addButton(ui->Key_B, Qt::Key_B);
btnGroup_function->addButton(ui->Key_C, Qt::Key_C);
btnGroup_function->addButton(ui->Key_D, Qt::Key_D); ui->Key_D->hide();
btnGroup_function->addButton(ui->Key_E, Qt::Key_E); ui->Key_E->hide();
connect(btnGroup_function, SIGNAL(buttonClicked(int)), \
this, SLOT(SlOT_Button_Function_Judge(int)));
btnGroup_Color = new QButtonGroup; // -颜色按键
connect(btnGroup_Color, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_Button_Color_Judge(int)));
btnGroup_Conf = new QButtonGroup; // -测试项目
btnGroup_Conf->addButton(ui->Button_ALL, Qt::Key_0);
btnGroup_Conf->addButton(ui->Button_DLR, Qt::Key_1); ui->Button_DLR->hide();
btnGroup_Conf->addButton(ui->Button_MAG, Qt::Key_2); ui->Button_MAG->hide();
btnGroup_Conf->addButton(ui->Button_IR, Qt::Key_3); ui->Button_IR->hide();
btnGroup_Conf->addButton(ui->Button_ACW, Qt::Key_4); ui->Button_ACW->hide();
btnGroup_Conf->addButton(ui->Button_DCW, Qt::Key_5); ui->Button_DCW->hide();
btnGroup_Conf->addButton(ui->Button_IMP, Qt::Key_6); ui->Button_IMP->hide();
btnGroup_Conf->addButton(ui->Button_PWR, Qt::Key_7); ui->Button_PWR->hide();
btnGroup_Conf->addButton(ui->Button_INDL, Qt::Key_8); ui->Button_INDL->hide();
btnGroup_Conf->addButton(ui->Button_BLOCK, Qt::Key_9); ui->Button_BLOCK->hide();
btnGroup_Conf->addButton(ui->Button_LVS, 58); ui->Button_LVS->hide();
btnGroup_Conf->addButton(ui->Button_Hall, 59); ui->Button_Hall->hide();
btnGroup_Conf->addButton(ui->Button_Load, 60); ui->Button_Load->hide();
btnGroup_Conf->addButton(ui->Button_NoLoad, 61); ui->Button_NoLoad->hide();
btnGroup_Conf->addButton(ui->Button_BEMF, 61); ui->Button_BEMF->hide();
connect(btnGroup_Conf, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_Button_Conf_Judge(int)));
int i = 0;
Item_Widget = new QWidget(this); // -建立弹出项目
Item_Widget->setGeometry(450, 10, 250, 571);
Item_Widget->setWindowFlags(Qt::WindowStaysOnTopHint);
QStringList Item_Text, Item_Id;
Item_Text.clear();
Count_Item = 14;
Item_Text << tr("取消") << tr("设置") << tr("电阻") << tr("电感") << tr("反嵌") << tr("绝缘")\
<< tr("交耐") << tr("直耐") << tr("匝间") << tr("电参")\
<< tr("堵转") << tr("低启")\
<< tr("HALL") << tr("负载") << tr("空载") << tr("BEMF");
Item_Id << tr("0") << tr("20") << tr("1") << tr("8") << tr("2") << tr("3")\
<< tr("4") << tr("5") << tr("6") << tr("7")\
<< tr("9") << tr("10")\
<< tr("11") << tr("12") << tr("13") << tr("14");
int position[] = {00, 10, 30, 40, 50, 60, \
70, 80, 90, 31, \
41, 51, \
61, 71, 81, 91};
QGridLayout *Item_all = new QGridLayout;
btnGroup_Item = new QButtonGroup; // -进行设置按键的增加
for (i = 0; i < Item_Text.size(); i++) {
Item_Putton.append(new QPushButton(this));
btnGroup_Item->addButton(Item_Putton[i], Item_Id.at(i).toInt());
Item_Putton[i]->setText(Item_Text.at(i));
Item_Putton[i]->setMinimumHeight(40);
Item_Putton[i]->setMinimumWidth(90);
Item_all->addWidget(Item_Putton[i], position[i]/10, position[i]%10);
}
for (i = 2; i < Item_Text.size(); i++) {
Item_Putton[i]->hide(); // 功能隐藏
}
connect(btnGroup_Item, SIGNAL(buttonClicked(int)), this, SLOT(SlOT_ButtonProj(int)));
Item_Putton[0]->setStyleSheet("background-color: gray;");
Item_Putton[1]->setStyleSheet("background-color: green;");
QLabel *Item_Lable_padding = new QLabel;
Item_Lable_padding->setStyleSheet("background-color: #191919;");
Item_Lable_padding->setMinimumHeight(50);
Item_all->addWidget(Item_Lable_padding, 2, 0);
Item_all->setAlignment(Qt::AlignTop);
Item_Chose_Box = new QCheckBox(this);
Item_Chose_Box->setStyleSheet
("QCheckBox::indicator {image: url(:/image/053.png);"\
"width: 50px;height: 55px;}"\
"QCheckBox::indicator:checked {image: url(:/image/051.png);}");
Item_Chose_Box->setChecked(false);
connect(Item_Chose_Box, SIGNAL(stateChanged(int)), \
this, SLOT(Item_Chose_Box_stateChanged(int)));
Item_all->addWidget(Item_Chose_Box, 0, 1);
Item_Widget->setStyleSheet(".QWidget{background-color: #191919;border: 2px solid #447684;}");
Item_Widget->setLayout(Item_all);
Item_Widget->hide();
btnGroup_IMP_Sample = new QButtonGroup;
btnGroup_IMP_Sample->addButton(ui->imp_button_add, 0); ui->imp_button_add->hide();
btnGroup_IMP_Sample->addButton(ui->imp_button_cancel, 1); ui->imp_button_cancel->hide();
btnGroup_IMP_Sample->addButton(ui->imp_button_finsh, 2); ui->imp_button_finsh->hide();
connect(btnGroup_IMP_Sample, SIGNAL(buttonClicked(int)), \
this, SLOT(SlOT_Button_IMP_Sample(int)));
Test_Item.clear();
Test_Item.append(tr("清除")); // 0
Test_Item.append(tr("电阻")); // 1
Test_Item.append(tr("反嵌")); // 2
Test_Item.append(tr("绝缘")); // 3
Test_Item.append(tr("交耐")); // 4
Test_Item.append(tr("直耐")); // 5
Test_Item.append(tr("匝间")); // 6
Test_Item.append(tr("电参")); // 7
Test_Item.append(tr("电感")); // 8
Test_Item.append(tr("堵转")); // 9
Test_Item.append(tr("低启")); // 10
Test_Item.append(tr("HALL")); // 11
Test_Item.append(tr("负载")); // 12
Test_Item.append(tr("空载")); // 13
Test_Item.append(tr("BEMF")); // 14
Test_Item.append(tr("PG")); // 11
ui->fileTab->horizontalHeader()->setStyleSheet
("QHeaderView::section{background-color:#191919;"\
"color: white;padding-left: 4px;border: 1px solid #447684;}");
ui->fileTab->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
ui->test->horizontalHeader()->setStyleSheet
("QHeaderView::section{background-color:#191919;"\
"color: white;padding-left: 4px;border: 1px solid #447684;}");
Mouse.Time = new QTimer(this);
connect(Mouse.Time, SIGNAL(timeout()), this, SLOT(test_mouse_check()));
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Flag = false;
Conf_User = User_Operator; // -默认设置为操作员
TabWidget_Changed = true; // -默认设置为页面改变
remove_row = 0; // -移除的项目
Quick_Set = false; // -默认非快速设置
index_c = 0; // -当前页面的序列号, 默认为0
parameter.clear();
parameter.append(QString(tr("Conf")));
parameter.append(QString(tr("DLR")));
parameter.append(QString(tr("MAG")));
parameter.append(QString(tr("IR")));
parameter.append(QString(tr("ACW")));
parameter.append(QString(tr("DCW")));
parameter.append(QString(tr("IMP")));
parameter.append(QString(tr("PWR")));
parameter.append(QString(tr("INDL")));
parameter.append(QString(tr("BLOCK")));
parameter.append(QString(tr("LVS")));
parameter.append(QString(tr("HALL")));
parameter.append(QString(tr("LOAD")));
parameter.append(QString(tr("NOLOAD")));
parameter.append(QString(tr("BEMF")));
Conf_label_Hide = new QLabel(ui->W_All);
Conf_label_Hide->setGeometry(0, 0, 700, 600);
Conf_label_Hide->hide();
conf_Waring = false;
label_Waring = new QLabel(this);
label_Waring->setGeometry(0, 0, 800, 600);
label_Waring->hide();
Beep.Time = new QTimer(this);
connect(Beep.Time, SIGNAL(timeout()), this, SLOT(beep_stop()));
Beep.Flag = false;
QString path = ("/mnt/nandflash/AIP/Model/"); // -读取全部型号, 建立文件类型列表--model_Type
QDir *dir = new QDir(path);
QStringList filter; filter << "*.jpg";
QString FileName;
QString FileNameInter;
dir->setNameFilters(filter);
QList<QFileInfo> *fileInfo = new QList<QFileInfo>(dir->entryInfoList(filter));
ui->MotorType->clear();
for (i = 0; i < fileInfo->count(); i++) {
FileName = fileInfo->at(i).fileName();
FileNameInter = FileName.mid(0, FileName.indexOf("."));
ui->MotorType->addItem(FileNameInter, i);
model_Type.append(FileNameInter);
}
// FILE *SD_Exist;
// SD_Exist = fopen("/dev/mmcblk0", "r"); // 查看SD卡是否进行挂载
// if (SD_Exist != NULL) {
// sdcard_exist = true;
// sql.openSql("/mnt/sdcard/aip.db"); // 打开 sdcard 数据库
// } else {
// sdcard_exist = false;
// sql.openSql("/mnt/nandflash/aip.db"); // 打开 nandflash 数据库
// }
same_ip_address = false;
NetSQL_OpenOk = false;
// if (Get_Ip_Address()) // 判断IP是否处在同一个网段
{
same_ip_address = true;
}
isopend = false;
label_Set = new QLabel(this);
label_Set->setGeometry(720, 10, 66, 571);
label_Set->setText(tr("设\n置\n中\n,\n请\n稍\n候"));
label_Set->setStyleSheet("color: white;font: Bold 30pt Ubuntu;");
label_Set->setAlignment(Qt::AlignCenter);
label_Set->hide();
lable_Zero = new QLabel(this);
lable_Zero->setGeometry(0, 0, 800, 600);
lable_Zero->setStyleSheet("color: white;font: Bold 30pt Ubuntu;");
lable_Zero->setText(tr("正在清零,请稍后"));
lable_Zero->setAlignment(Qt::AlignCenter);
lable_Zero->hide();
Ini_Power_Chose = 0; // -功率板的电源初始化为0
Ini_Mag_Hide = 0;
Ini_Udp_Enable = false;
Ini_ACW_And_IR = false;
Ini_System.clear();
Ini_Number = 0;
Ini_Proj_Real.clear();
Ini_Proj.clear();
SQL_Init = true;
SQL_Widget = new QWidget(this);
SQL_Widget->setGeometry(150, 100, 500, 400);
SQL_Widget->setWindowFlags(Qt::WindowStaysOnTopHint);
SQL_Widget->setStyleSheet
("border-radius: 10px;padding:2px 4px;background-color: gray;"\
"color: black;border-color: black;");
QGridLayout *SQL_upside = new QGridLayout;
QString SQL_table[5]={tr("生产线:"), tr("生产任务号:"), \
tr("计划数量:"), tr("生产部门:"), tr("产品型号:")};
for (i = 0; i < 5; i++) {
SQL_lable.append(new QLabel(this));
SQL_lable[i]->setText(SQL_table[i]);
SQL_lable[i]->setMaximumHeight(35); SQL_lable[i]->setMaximumWidth(135);
SQL_lable[i]->setAlignment(Qt::AlignCenter);
SQL_upside->addWidget(SQL_lable[i], i, 0);
if (i > 1) {
SQL_Line_Text.append(new QLineEdit(this));
SQL_Line_Text[i-2]->setMaximumHeight(35); SQL_Line_Text[i-2]->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Line_Text[i-2], i, 1);
}
}
SQL_Produce_Plan = new QComboBox(this);
SQL_Produce_Plan->setMaximumHeight(35); SQL_Produce_Plan->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Produce_Plan, 0, 1);
connect(SQL_Produce_Plan, SIGNAL(currentIndexChanged(const QString &)), \
this, SLOT(SQL_Produce_Plan_textChanged(const QString &)));
SQL_Produce_Number = new QComboBox(this);
SQL_Produce_Number->setMaximumHeight(35); SQL_Produce_Number->setMaximumWidth(255);
SQL_upside->addWidget(SQL_Produce_Number, 1, 1);
connect(SQL_Produce_Number, SIGNAL(currentIndexChanged(const QString &)), \
this, SLOT(SQL_Produce_Number_textChanged(const QString &)));
QPushButton *button_quit_SQL = new QPushButton;
button_quit_SQL->setText(tr("退出"));
button_quit_SQL->setMinimumHeight(50);
button_quit_SQL->setMinimumWidth(90);
button_quit_SQL->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);");
SQL_upside->addWidget(button_quit_SQL, 0, 5);
connect(button_quit_SQL, SIGNAL(clicked()), this, SLOT(SQL_Widget_autoquit()));
QVBoxLayout *Histogram_Widget_layout_SQL = new QVBoxLayout;
Histogram_Widget_layout_SQL->addLayout(SQL_upside);
SQL_Widget->setLayout(Histogram_Widget_layout_SQL);
SQL_Widget->hide();
SQL_Init = false;
PWR_Test_Usart = false;
SQL_Error = false;
strTest.clear(); // -测试项目清除
strParam.clear(); // -测试参数清除
Result_indl.dat[0] = 0;
Result_indl.dat[1] = 0;
Result_indl.dat[2] = 0;
Result_indl.dat[3] = 0;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 析构
******************************************************************************/
w_Conf::~w_Conf()
{
delete btnGroup_function;
delete ui;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.1.15
* brief: 获取ip地址,并且与数据库ip做对比
******************************************************************************/
int w_Conf::Get_Ip_Address()
{
int sock_get_ip = 0;
int i = 0;
bool ip_same = 0;
char ipaddr[50];
struct sockaddr_in *sin;
struct ifreq ifr_ip;
if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1) {
//
} else {
//
}
memset(&ifr_ip, 0, sizeof(ifr_ip));
strncpy(ifr_ip.ifr_name, "eth0", sizeof(ifr_ip.ifr_name) - 1);
if (ioctl(sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0) {
//
}
sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
strcpy(ipaddr, inet_ntoa(sin->sin_addr));
QStringList ip_split = QString(ipaddr).split(".");
QSettings set_odbc("/usr/local/arm/unixODBC/etc/odbc.ini", QSettings::IniFormat); // 数据库 ip
QString sql_net_ip = set_odbc.value("testodbc/Server", "1,1,1,1").toString();
QStringList sql_net_ip_split = QString(sql_net_ip).split(".");
for (i = 0; i < sql_net_ip_split.size() - 1; i++) {
if (ip_split.at(i) == sql_net_ip_split.at(i)) {
ip_same = 1;
} else {
ip_same = 0;
break;
}
}
return ip_same;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 处理鼠标被按下事件
******************************************************************************/
void w_Conf::mousePressEvent(QMouseEvent *event)
{
handleMousePressEvent(event);
Item_Widget->hide();
Conf_label_Hide->hide();
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Time->start(1);
Mouse.Flag = false;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 处理鼠标离开事件
******************************************************************************/
void w_Conf::mouseReleaseEvent(QMouseEvent *event)
{
Mouse.Time->stop();
if ((Mouse.Ms >= 2) && (!conf_Waring)) {
Singal_Conf_to_Main(QStringList(""), QString(""), wHelp_Surface, 2);
}
Mouse.Ms = 0; Mouse.Us = 0;
Mouse.Flag = false;
event->x();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 长按计时功能
******************************************************************************/
void w_Conf::test_mouse_check()
{
Mouse.Us++;
if (Mouse.Us >= 1000) {
Mouse.Us = 0;
Mouse.Ms++;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 点击页面操作
******************************************************************************/
bool w_Conf::handleMousePressEvent(QMouseEvent *event)
{
QPoint topLeftUser(0, 30); // left top
QPoint rightBottomUser(711, 600);
QRect rectUser(topLeftUser, rightBottomUser);
if (rectUser.contains(event->pos())) {
if ((Conf_User == User_Operator) && (!conf_Waring)) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
}
}
return true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: 蜂鸣器停止
******************************************************************************/
void w_Conf::beep_stop()
{
Beep_PWM_Stop();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.31
* brief: 蜂鸣器的报警状态
******************************************************************************/
void w_Conf::Beep_State()
{
if (Beep.Flag) {
return;
}
Beep.Flag = true;
Beep.Time->setSingleShot(TRUE); Beep.Time->start(80); Beep_PWM_Start(99);
Beep.Flag = false;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.31
* brief: 匝间进行采样
******************************************************************************/
void w_Conf::SlOT_Button_IMP_Sample(int id)
{
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
} else {
WIMP->Pub_Conf_GetSample(id);
if (id == 2) {
SlOT_Button_Function_Judge(Qt::Key_B);
} else {
//
}
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 可选项目 按键功能 // 已屏蔽
******************************************************************************/
void w_Conf::SlOT_ButtonProj(int id)
{
int i = 0;
qDebug() << "SlOT_ButtonProj";
Item_Widget->hide();
Conf_label_Hide->hide();
if (remove_row < (test_Inifile.size())) {
switch (id) {
case 0: // -清除
test_Inifile.removeAt(remove_row);
break;
case 20: // -设置
SlOT_Button_Conf_Judge(test_Inifile.at(remove_row).toInt()+48);
break;
default: // -取代 (电阻 反嵌 绝缘 交耐 直耐 匝间 电参 电感 堵转 低启)
test_Inifile.replace(remove_row, (QString::number(id)));
break;
}
} else {
if ((id != 0) && (id != 20)) { // -去除(清除和取消)
test_Inifile.append(QString::number(id));
}
}
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + (ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget(); // -初始化测试项目
for (i = 1; i <= Count_Item; i++) { // -设置显示, 锁定端子号
btnGroup_Item->button(i)->hide();
}
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
for (i = 1; i < Ini_Proj.size(); i++) {
btnGroup_Item->button(Ini_Proj.at(i).toInt())->show();
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 在操作页面获取焦点
******************************************************************************/
void w_Conf::Usart_GetFcous()
{
switch (index_c) {
case 0:
//
break;
case 1:
WDLR->Pub_Conf_Set_DLR("", 8);
break;
case 2:
WMAG->Pub_Conf_Set_MAG("", 8);
break;
case 3:
//
break;
case 4:
//
break;
case 5:
//
break;
case 6:
WIMP->Pub_Conf_Set_IMP("", 9);
break;
case 7:
//
break;
case 8:
//
break;
case 9:
//
break;
case 10:
//
break;
case 11: // 霍尔
//
break;
case 12: // 负载
//
break;
case 13: // 空载
//
break;
case 14: // 反电动势
//
break;
default:
//
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 进入测试项目的设置界面
******************************************************************************/
void w_Conf::SlOT_Button_Conf_Judge(int id)
{
qDebug() << id - 48 << index_c;
if (((id - 48) != index_c) && (!Quick_Set)) {
Save_Hint();
}
ui->Key_A->show(); ui->Key_B->setText(tr("测试主页"));
ui->Key_B->show(); ui->Key_B->setText(tr("保存设置"));
ui->Button_ALL->show(); ui->Button_ALL->setText(tr("设置首页"));
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide(); ui->Key_E->setText("补偿");
ui->Key_D->setStyleSheet("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,"\
"stop: 1 #27405A); color:rgb(255, 255, 255);");
ui->Key_E->setStyleSheet("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,"\
"stop: 1 #27405A); color:rgb(255, 255, 255);");
switch (id) {
case Qt::Key_0:
ui->label_User->setGeometry(299, 0, 401, 600);
ui->stackedWidget->setCurrentIndex(0);
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
ui->Key_C->show(); ui->Key_C->setText(tr("快速设置"));
break;
case Qt::Key_1: // -电阻
WDLR->Pub_Conf_Set_DLR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WDLR));
ui->Key_D->show(); ui->Key_D->setText(tr("左清零"));
ui->Key_E->show(); ui->Key_E->setText(tr("右清零"));
if (WDLR->DLR_Compensate_Left) {
ui->Key_D->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_D->setText(tr("左OK")); // -已清零
} else {
ui->Key_D->setText(tr("左清零")); // -未清零
}
if (WDLR->DLR_Compensate_Right) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("右OK")); // -已清零
} else {
ui->Key_E->setText(tr("右清零")); // -未清零
}
break;
case Qt::Key_2: // -反嵌
if (WMAG != NULL) {
WMAG->Pub_Conf_Set_MAG(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WMAG));
Board_DLR = 1;
ui->Key_D->show(); ui->Key_D->setText(tr("采集"));
WMAG->Pub_Conf_Set_MAG("", 9);
break;
} else if (WPWR != NULL) {
id = 0x37;
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPWR));
WPWR->setFocus();
break;
} else {
//
}
break;
case Qt::Key_3: // -绝缘
WIR->Pub_Conf_Set_IR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WIR));
if (Ini_ACW_And_IR) {
ui->Key_E->hide();
} else {
ui->Key_E->show();
}
if (WIR->IR_Back_Key_E()) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else {
ui->Key_E->setText(tr("未补偿"));
}
break;
case Qt::Key_4: // -交耐
WACW->Pub_Conf_Set_ACW(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WACW));
if (Ini_ACW_And_IR) {
ui->Key_E->hide();
} else {
ui->Key_E->show();
}
if (WACW->ACW_Back_Key_E()) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else {
ui->Key_E->setText(tr("未补偿"));
}
break;
case Qt::Key_5: // -直耐
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WDCW));
break;
case Qt::Key_6: // -匝间
WIMP->Pub_Conf_Set_IMP(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WIMP));
WIMP->Pub_Conf_Set_IMP("", 3);
ui->Key_D->show(); ui->Key_D->setText(tr("采集"));
ui->imp_button_add->show();
ui->imp_button_cancel->show();
ui->imp_button_finsh->show();
break;
case Qt::Key_7:
WPWR->Pub_Conf_Set_PWR(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPWR));
WPWR->setFocus();
break;
case Qt::Key_8:
WINDL->Pub_Conf_Set_INDL(QString::number(Out_Channel_6), 100, 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WINDL));
WINDL->setFocus();
break;
case Qt::Key_9:
WBLOCK->Pub_Conf_Set_BLOCK(QString::number(Out_Channel_6), 100, 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WBLOCK));
WBLOCK->setFocus();
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 6);
break;
case 58:
WLVS->Pub_Conf_Set_LVS(QString::number(Out_Channel_6), 100);
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WLVS));
WLVS->setFocus();
break;
case 59: // 霍尔
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WPG));
WPG->setFocus();
break;
case 60: // 负载
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WLOAD));
WLOAD->setFocus();
break;
case 61: // 空载
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WNoLoad));
WNoLoad->setFocus();
break;
case 62: // 反电动势
ui->stackedWidget->setCurrentIndex(ui->stackedWidget->indexOf(WBEMF));
WBEMF->setFocus();
break;
default:
ui->Key_C->show();
ui->stackedWidget->setCurrentIndex(0);
break;
}
if (Quick_Set) {
ui->Key_A->hide();
ui->Key_B->hide();
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide();
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
}
qApp->processEvents();
index_c = (id - 48)%16; // -获取保存序列号-16
TabWidget_Changed = true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 配置页面的键盘操作
******************************************************************************/
void w_Conf::Usart_Button(int Usart_number)
{
if (Usart_number == 26) {
SlOT_Button_Function_Judge(Qt::Key_A);
} else if (Usart_number == 27) {
SlOT_Button_Function_Judge(Qt::Key_B);
} else if (Usart_number == 24) {
switch (index_c) {
case 0:
SlOT_Button_Function_Judge(Qt::Key_C);
break;
case 1:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 2:
SlOT_Button_Function_Judge(Qt::Key_D);
break;
case 3:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 4:
SlOT_Button_Function_Judge(Qt::Key_E);
break;
case 5:
//
break;
case 6:
SlOT_Button_Function_Judge(Qt::Key_D);
break;
case 7:
//
break;
case 8:
//
break;
case 9:
//
break;
case 10:
//
break;
case 11: // 霍尔
//
break;
case 12: // 负载
//
break;
case 13: // 空载
//
break;
case 14: // 反电动势
//
break;
default:
//
break;
}
} else if (Usart_number == 25) {
SlOT_Button_Conf_Judge(Qt::Key_0);
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 颜色设置
******************************************************************************/
void w_Conf::SlOT_Button_Color_Judge(int id)
{
if (id >= 12) {
return;
}
iColorBtn = id;
Singal_Conf_to_Main(QStringList(""), QString(""), wColr_Surface, 2);
}
void w_Conf::PC_Test_Param_connect() {
QStringList netdata;
QStringList strParam_c;
strParam_c.clear();
netdata.clear();
netdata.append(strTest);
strParam_c = strParam;
for (int i = 0; i < strParam.size(); i++) {
strParam_c.replace(i, QString(strParam_c.at(i)).replace(QRegExp("\\,"), " "));
}
netdata.append(strParam_c);
PC_Test_Param_Data(netdata);
}
void w_Conf::FG_bound_Item() {
int i = 0;
qDebug() << "FG_bound_Item();";
qDebug() << test_Inifile;
if (test_Inifile.contains(tr("11"))) {
qDebug() << "2018-3-22 Hall---->" << WPG->Copy_BLDCPG_List.at(3);
// (0 空载) (1 负载) (2 BEMF)
// (13 空载) (12 负载) (14 BEMF)
switch (WPG->Copy_BLDCPG_List.at(3).toInt()) {
case 0:
if (Ini_Proj.contains(tr("13"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("13")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("13")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
case 1:
if (Ini_Proj.contains(tr("12"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("12")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("12")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
case 2:
if (Ini_Proj.contains(tr("14"))) {
test_Inifile.removeAt(test_Inifile.indexOf(tr("14")));
test_Inifile.insert(test_Inifile.indexOf(tr("11")),QString(tr("14")));
}
else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("11")));// 删除FG
}
break;
default:
break;
}
qDebug() << test_Inifile;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + (ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
ui->test->item((test_Inifile.indexOf(tr("1"))),0)->setTextColor(QColor("green"));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 按钮功能-功能选择 (测试主页 保存设置 快速设置 采集波形 补偿)
******************************************************************************/
void w_Conf::SlOT_Button_Function_Judge(int id)
{
int i = 0;
bool Exist_Pwr;
Exist_Pwr = false;
switch (id) {
case Qt::Key_A: {
if (Conf_User == User_Administrators) { // -管理员(进行保存提示)
Save_Hint();
}
TabWidget_Changed = true;
/*判断是否存在功率的测试项目,若存在在功率前添加电阻*/
if ((test_Inifile.contains(tr("7"))) || \
(test_Inifile.contains(tr("9"))) || \
(test_Inifile.contains(tr("10")))|| \
(test_Inifile.contains(tr("13")))) {
Exist_Pwr = true;
WDLR->Pub_Conf_Set_DLR("0", 4); // -WDLR->DLR_TestNumber的总数
if ((test_Inifile.indexOf(tr("1"))) == 0) {
//
} else {
test_Inifile.removeAt(test_Inifile.indexOf(tr("1")));
test_Inifile.insert(0, "1");
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
}
if ((test_Inifile.contains(tr("1")))) {
if (WDLR->DLR_TestNumber == 0) {
WDLR->Pub_Conf_Set_DLR("", 12);
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14 + \
(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents(); // 立即显示生效
}
} else if (WDLR != NULL) {
test_Inifile.insert(0, "1");
WDLR->Pub_Conf_Set_DLR("", 12);
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget();
qApp->processEvents();
} else {
//
}
ui->test->item((test_Inifile.indexOf(tr("1"))),0)->setTextColor(QColor("green"));
}
FG_bound_Item();
for (i = 0; i < test_Inifile.size(); i++) {
switch (test_Inifile[i].toInt()) {
case 1:
qDebug() << "Test RES ";
WDLR->Pub_Conf_Set_DLR("0", 4);
break;
case 2:
qDebug() << "Test OPP ";
WMAG->Pub_Conf_Set_MAG(" ", 7);
break;
case 3:
qDebug() << "Test INS ";
WIR->Pub_Conf_Set_IR(QString::number(Ini_IRHostJudge), 5);
break;
case 4:
qDebug() << "Test ACV ";
WACW->Pub_Conf_Set_ACW(" ", 5);
break;
case 5:
qDebug() << "Test DCV ";
break;
case 6:
qDebug() << "Test_IMP ";
break;
case 7: qDebug() << "Test_PWR ";
WPWR->Pub_Conf_Set_PWR("0", 3);
break;
case 8:
qDebug() << "Test_INDL";
WINDL->Pub_Conf_Set_INDL("0", 1, 3);
break;
case 9: qDebug() << "Test_BLOCK";
break;
case 10:
qDebug() << "Test_LVS";
WLVS->Pub_Conf_Set_LVS("0", 3);
break;
case 11:
qDebug() << "Test_PG";
break;
case 12:
qDebug() << "Test_LOAD";
break;
case 13:
qDebug() << "Test_NOLOAD";
break;
case 14:
qDebug() << "Test_BEMF";
break;
default:
//
break;
}
}
Sync_Test_Widget();
QStringList Main_Data; Main_Data.clear();
Main_Data.append(Ini_ActiveFile);
Main_Data.append(QString::number(Test_Occur_Debug));
Main_Data.append(serial_number);
Main_Data.append(SQL_Line_Text.at(0)->text());
Main_Data.append(QString::number(Exist_Pwr));
Main_Data.append(QString::number(strTest.size()));
Main_Data.append(QString::number(strParam.size()));
Main_Data.append(strTest);
Main_Data.append(strParam);
PC_Test_Param_connect();
Singal_Conf_to_Main(Main_Data, QString(""), wTest_Surface, 1);
break;
}
case Qt::Key_B:
Beep_State(); // -蜂鸣器提醒
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
qDebug() << "Qt::Key_B";
TabWidget_Changed = false;
switch (Ini_Proj.at(ui->stackedWidget->currentIndex()).toInt()) {
case 0:
qDebug() << "CONF";
Save_ConfData();
conf_c = CONF;
break;
case 1:
qDebug() << "RES";
WDLR->Pub_Conf_Set_DLR("", 3);
RES = WDLR->Copy_DLR_List;
break;
case 2:
qDebug() << "OPP";
WMAG->Pub_Conf_Set_MAG("", 2);
OPP = WMAG->Copy_MAG_List;
break;
case 3:
qDebug() << "INS";
WIR->Pub_Conf_Set_IR("", 2);
INS = WIR->Copy_IR_List;
break;
case 4:
qDebug() << "ACV";
WACW->Pub_Conf_Set_ACW("", 2);
ACV = WACW->Copy_ACW_List;
break;
case 5:
qDebug() << "DCV";
WDCW->Save_DCW_Data();
DCV = WDCW->Copy_DCW_List;
break;
case 6:
qDebug() << "ITT";
WIMP->Pub_Conf_Set_IMP("", 4);
ITT = WIMP->Copy_IMP_List;
break;
case 7:
WPWR->Pub_Conf_Set_PWR("", 2);
PWR = WPWR->Copy_PWR_List;
qDebug() << "PWR";
break;
case 8:
WINDL->Pub_Conf_Set_INDL("", 1, 2);
INDL = WINDL->Copy_INDL_List;
qDebug() << "INDL";
break;
case 9:
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 2);
BLOCK = WBLOCK->Copy_BLOCK_List;
qDebug() << "BLOCK";
break;
case 10:
WLVS->Pub_Conf_Set_LVS("", 2);
LVS = WLVS->Copy_LVS_List;
qDebug() << "LVS";
break;
case 11:
WPG->Pub_Conf_Set_PG(QStringList(""), 2);
BLDCPG = WPG->Copy_BLDCPG_List;
qDebug() << "BLDCPG-save";
break;
case 12:
WLOAD->Pub_Conf_Set_LOAD("", 2);
qDebug() << "LOAD 1";
LOAD = WLOAD->Copy_LOAD_List;
qDebug() << "LOAD 2";
qDebug() << "LOAD";
break;
case 13:
WNoLoad->Pub_Conf_Set_NOLOAD(QStringList(""), 2);
NOLOAD = WNoLoad->Copy_NOLOAD_List;
qDebug() << "NOLOAD";
break;
case 14:
WBEMF->Pub_Conf_Set_BEMF(QString(""), 2);
BEMF = WBEMF->Copy_BEMF_List;
qDebug() << "BEMF";
break;
default: break;
}
Save_SqlData();
TabWidget_Changed = true;
qDebug() << "Start All OK";
break;
case Qt::Key_C:
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
Item_Widget->hide();
if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 0) && \
(ui->MotorType->currentText() != "None")) { // 在 None型号时,不能进行快速设置
QMessageBox Quick_Set_Ask;
Quick_Set_Ask.setWindowFlags(Qt::FramelessWindowHint);
Quick_Set_Ask.setStyleSheet("QMessageBox{border:3px groove gray;}"\
"background-color: rgb(209, 209, 157);");
Quick_Set_Ask.setText(tr(" 确定进行快速设置 \n "));
Quick_Set_Ask.addButton(QMessageBox::Ok)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
Quick_Set_Ask.addButton(QMessageBox::Cancel)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
Quick_Set_Ask.setButtonText(QMessageBox::Ok, QString(tr("确 定")));
Quick_Set_Ask.setButtonText(QMessageBox::Cancel, QString(tr("取 消")));
Quick_Set_Ask.setIcon(QMessageBox::Warning);
int ret = Quick_Set_Ask.exec();
if (ret == QMessageBox::Ok) {
Quick_Set_Function();
}
if (ret == QMessageBox::Cancel) {
//
}
}
break;
case Qt::Key_D:
qDebug() << "Qt::Key_D";
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 1) { // 电阻
if (WDLR->Pub_Conf_Station(QString(tr("Left")))) {
ui->Key_D->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零"));
}
} else if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 2) && (Board_DLR)) {
Board_DLR = 0;
label_Waring_MAG = new QLabel(this);
label_Waring_MAG->setGeometry(700, 0, 800, 600);
label_Waring_MAG->show();
WMAG->Pub_Conf_Set_MAG("3", 3);
WMAG->Pub_Conf_Set_MAG(" ", 6);
label_Waring_MAG->hide();
} else if ((Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 6)) {
label_Waring_MAG = new QLabel(this);
label_Waring_MAG->setGeometry(700, 0, 800, 600);
label_Waring_MAG->show();
WIMP->Pub_Conf_Set_IMP("", 7);
label_Waring_MAG->hide();
} else {
//
}
break;
case Qt::Key_E:
qDebug() << "Qt::Key_E";
if (Conf_User == User_Operator) {
Pri_Conf_WMessage(tr(" 当前用户模式为操作员 \n"\
"无权限进行保存和修改 "));
break;
}
SlOT_Button_Function_Judge(Qt::Key_B); // -进行保存
TabWidget_Changed = true; // -触发没有保存
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 1) { // -电阻
if (WDLR->Pub_Conf_Station(QString(tr("Right")))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零"));
}
} else if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 3) { // -绝缘
IRACW_Compensate = TestIW_IR;
if (WIR->IR_If_Compensate(QString::number(Ini_ACW_And_IR))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("未补偿"));
}
} else if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 4) { // -交耐
qDebug() << "交耐";
IRACW_Compensate = TestIW_ACW;
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
if (WACW->ACW_If_Compensate(QString::number(Ini_ACW_And_IR))) {
ui->Key_E->setStyleSheet
("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"\
"stop: 0 #5B5F5F, stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("未补偿"));
}
} else {
//
}
break;
default:
//
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 快速设置
******************************************************************************/
void w_Conf::Quick_Set_Function()
{
int i = 0, j = 0, x = 0;
Quick_Set = true; label_Waring->show();
label_Set->show();
ui->Key_A->hide();
ui->Key_B->hide();
ui->Key_C->hide();
ui->Key_D->hide();
ui->Key_E->hide();
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
ui->Button_ALL->hide();
for (i = 0; i < test_List.size(); i++) { // -快速设置选择项目
if (i != test_List.indexOf(test_List.at(i))) { // -去除重复选项
continue;
}
SlOT_Button_Conf_Judge(48+Test_Item.indexOf(test_List.at(i))); // -页面切换
if (Test_Item.indexOf(test_List.at(i)) == 1) { // -电阻
qDebug() << "DLR Quick_Set";
WDLR->Pub_Conf_Set_DLR(Ini.DLR, 6);
// if (WDLR->DLR_Compensate_Left) {
// WDLR->DLR_Compensate_Left = false;
ui->Key_D->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零"));
// }
// if (WDLR->DLR_Compensate_Right) {
// WDLR->DLR_Compensate_Right = false;
ui->Key_E->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零"));
// }
for (j = 7; j > 0; j--) { // 档位选择
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
WDLR->Pub_Conf_Set_DLR(QString::number(j), 4);
WDLR->Pub_Conf_Set_DLR("", 5);
Board_DLR = 0;
QEventLoop DLRloop; // 进行延时等待结果
for (x = 0; x < 10; x++) {
QTimer::singleShot(300, &DLRloop, SLOT(quit()));
DLRloop.exec();
if (Board_DLR == 1) { // 设置电阻
x = 21;
}
}
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
usleep(50000);
}
QEventLoop DLRloop;
QTimer::singleShot(300, &DLRloop, SLOT(quit()));
DLRloop.exec();
for (j = 0; j < 8; j++) {
if (!(AutoSet[j].isEmpty())) {
WDLR->on_AutoSet(AutoSet[j]);
AutoSet[j].clear();
}
}
WDLR->Pub_Conf_Set_DLR("", 9);
} else if (Test_Item.indexOf(test_List.at(i)) == 2) { // -反嵌
qDebug() << "MAG Quick_Set";
int cutt; cutt = 0;
WMAG->Pub_Conf_Set_MAG("19", 10);
WMAG->Pub_Conf_Set_MAG(Ini.MAG, 5);
SlOT_Button_Function_Judge(Qt::Key_D);
QEventLoop eventloop;
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_DLR == 1) {
cutt++;
if (cutt == (Ini.MAG.size()/2)) {
j = 101;
}
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 3) { // -绝缘
qDebug() << "IR Quick_Set";
WIR->Pub_Conf_Set_IR("", 3);
ui->Key_E->setText(tr("未补偿"));
} else if (Test_Item.indexOf(test_List.at(i)) == 4) { // -交耐
qDebug() << "ACW Quick_Set";
WACW->Pub_Conf_Set_ACW("", 3);
ui->Key_E->setText(tr("未补偿"));
} else if (Test_Item.indexOf(test_List.at(i)) == 5) { // -直耐
qDebug() << "DCW Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 6) { // -匝间
qDebug() << "IMP Quick_Set";
WIMP->Pub_Conf_Set_IMP("19", 13);
WIMP->Pub_Conf_Set_IMP(Ini.IMP, 6); // 匝间-设置电压数值
SlOT_Button_Function_Judge(Qt::Key_D); // 匝间-采集波形
QEventLoop eventloop;
for (j = 0; j < 300; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (WIMP->Pub_Conf_GetSample(3)) {
j = 301;
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 7) { // -电参
qDebug() << "PWR Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 8) { // -电感
qDebug() << "INDL Quick_Set";
WINDL->Pub_Conf_Set_INDL(Ini.IINDL, 1, 6); // 电感设置数值
WINDL->Pub_Conf_Set_INDL("", 1, 8);
WINDL->Pub_Conf_Set_INDL("", 1, 4);
Board_INDL = 0;
QEventLoop eventloop;
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_INDL == 1) {
Board_INDL = 0;
j = 98;
}
}
Board_INDL = 0;
WINDL->Pub_Conf_Set_INDL("", 1, 3);
WINDL->Pub_Conf_Set_INDL("", 1, 4);
for (j = 0; j < 100; j++) {
QTimer::singleShot(100, &eventloop, SLOT(quit()));
eventloop.exec();
if (Board_INDL == 1) {
Board_INDL = 0;
j = 101;
}
}
} else if (Test_Item.indexOf(test_List.at(i)) == 9) { // -堵转
qDebug() << "BLOCK Quick_Set";
} else if (Test_Item.indexOf(test_List.at(i)) == 10) { // -低启
qDebug() << "LVS Quick_Set";
}
QEventLoop eventloop;
QTimer::singleShot(600, &eventloop, SLOT(quit())); // -延时等待,暂留视觉
eventloop.exec();
qApp->processEvents();
SlOT_Button_Function_Judge(Qt::Key_B); // -快速设置保存
}
Quick_Set = false;
label_Waring->hide();
label_Set->hide();
SlOT_Button_Conf_Judge(Qt::Key_0); // 设置完成后返回设置首页
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 同步数据库与设置界面
******************************************************************************/
void w_Conf::Sync_Conf()
{
int i = 0, j = 0;
QStringList BLDC_Noload_Data;
QStringList BLDC_PG_Data;
Get_SqlData(); // -读取数据库文件
Init_Conf_Interface(); // -初始化设置界面
for (i = 0; i < Ini_Proj.size(); i++) {
Conf_ProjKey(Ini_Proj.at(i).toInt(), true);
}
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile); // -初始化文件名称
qApp->processEvents();
if (ui->stackedWidget->count() > 1) {
for (i = ui->stackedWidget->count(); i >= 1; i--) {
switch (Ini_Proj.at(i-1).toInt()) {
case 1:
qDebug() << "removeWidget(WDLR)";
ui->stackedWidget->removeWidget(WDLR);
break;
case 2:
qDebug() << "removeWidget(WMAG)";
ui->stackedWidget->removeWidget(WMAG);
break;
case 3:
qDebug() << "removeWidget(WIR)";
ui->stackedWidget->removeWidget(WIR);
break;
case 4:
qDebug() << "removeWidget(WACW)";
ui->stackedWidget->removeWidget(WACW);
break;
case 5:
qDebug() << "removeWidget(WDCW)";
ui->stackedWidget->removeWidget(WDCW);
break;
case 6:
qDebug() << "removeWidget(WIMP)";
ui->stackedWidget->removeWidget(WIMP);
break;
case 7:
qDebug() << "removeWidget(WPWR)";
ui->stackedWidget->removeWidget(WPWR);
break;
case 8:
qDebug() << "removeWidget(WINDL)";
ui->stackedWidget->removeWidget(WINDL);
break;
case 9:
qDebug() << "removeWidget(WBLOCK)";
ui->stackedWidget->removeWidget(WBLOCK);
break;
case 10:
qDebug() << "removeWidget(LVS)";
ui->stackedWidget->removeWidget(WLVS);
case 11:
qDebug() << "removeWidget(WPG)";
ui->stackedWidget->removeWidget(WPG);
case 12:
qDebug() << "removeWidget(WLOAD)";
ui->stackedWidget->removeWidget(WLOAD);
case 13:
qDebug() << "removeWidget(WNoLoad)";
ui->stackedWidget->removeWidget(WNoLoad);
case 14:
qDebug() << "removeWidget(WBEMF)";
ui->stackedWidget->removeWidget(WBEMF);
break;
default:
qDebug() << "removeWidget(----NULL)";
break;
}
}
}
// struct timeval start, stop, dif f;
for (i = 1; i < Ini_Proj.size(); i++) {
// gettimeofday(&start, 0);
switch (Ini_Proj.at(i).toInt()) {
case 1:
qDebug() << "Init_DLR";
WDLR = new Widget_DLR(this);
ui->stackedWidget->addWidget(WDLR);
if (RES.size() < 153) {
qDebug() << "RES Error" << RES.size();
for (j = RES.size(); j < 153; j++) {
RES.append("0");
}
} else {
qDebug() << "RES Ok";
}
WDLR->Copy_DLR_List = RES; // DLR数据 复制
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR15), 1);
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR_Balance), 13);
connect(WDLR, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 2:
qDebug() << "Init_MAG";
WMAG = new Widget_MAG(this);
ui->stackedWidget->addWidget(WMAG);
if (OPP.size() < 6560) {
qDebug() << "OPP Error" << OPP.size();
for (j = OPP.size(); j < 6560; j++) {
OPP.append("0");
}
} else {
qDebug() << "OPP Ok";
}
WMAG->Copy_MAG_List = OPP; // MAG数据 复制
WMAG->Pub_Conf_Set_MAG(QString::number(Ini_Mag_Hide), 1);
connect(WMAG, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 3:
qDebug() << "Init_IR";
WIR = new Widget_IR(this);
ui->stackedWidget->addWidget(WIR);
if (INS.size() < 100) { // 增加相间绝缘
QStringList list;
for (j = 0; j < 200; j++) {
list.append("0");
}
INS.append(list);
}
if (INS.size() < 229) {
qDebug() << "INS Error" << INS.size();
for (j = INS.size(); j < 229; j++) {
INS.append("0");
}
} else {
qDebug() << "INS Ok";
}
WIR->Copy_IR_List = INS; // IR数据 复制
WIR->Pub_Conf_Set_IR(QString::number(Ini_ACW_And_IR), 1);
connect(WIR, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 4:
qDebug() << "Init_ACW";
WACW = new Widget_ACW(this);
ui->stackedWidget->addWidget(WACW);
if (ACV.size() < 100) { // 增加相间耐压
QStringList list;
for (j = 0; j < 200; j++) {
list.append("0");
}
ACV.append(list);
}
if (ACV.size() < 226) {
qDebug() << "ACV Error" << ACV.size();
for (j = ACV.size(); j < 226; j++) {
ACV.append("0");
}
} else {
qDebug() << "ACV Ok";
}
WACW->Copy_ACW_List = ACV; // ACW数据 复制
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
WACW->Pub_Conf_Set_ACW(QString::number(Ini_ACW_And_IR), 1);
connect(WACW, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 5:
qDebug() << "Init_DCW";
WDCW = new Widget_DCW(this);
ui->stackedWidget->addWidget(WDCW);
WDCW->Copy_DCW_List = DCV; // DCW数据 复制
WDCW->Init_DCW();
connect(WDCW, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 6:
qDebug() << "Init_IMP";
WIMP = new Widget_IMP(this);
ui->stackedWidget->addWidget(WIMP);
if (ITT.size() < 6561) {
qDebug() << "ITT Error" << ITT.size();
ITT.clear();
for (j = ITT.size(); j < 6561; j++) {
ITT.append("0");
}
} else {
qDebug() << "ITT Ok";
}
WIMP->Copy_IMP_List = ITT; // IMP数据 复制
WIMP->Pub_Conf_Set_IMP(QString::number(Ini_IMP5000), 101);
WIMP->Pub_Conf_Set_IMP(Ini_ActiveFile, 1);
if (Ini_Set_ImpVolt == QString(tr("noback"))) { // 匝间初始化-反馈-不反馈-
WIMP->Pub_Conf_Set_IMP("", 12);
}
connect(WIMP, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 7:
qDebug() << "Init_WPWR";
WPWR = new Widget_PWR(this);
ui->stackedWidget->addWidget(WPWR);
if (PWR.size() < 495) {
qDebug() << "PWR Error" << PWR.size();
for (j = PWR.size(); j < 495; j++) {
PWR.append("0");
}
} else {
qDebug() << "PWR Ok";
}
WPWR->Copy_PWR_List = PWR;
WPWR->Pub_Conf_Set_PWR(Ini_Motor, 1);
connect(WPWR, SIGNAL(canSend(can_frame, int)), this, SLOT(SlOT_CanSendFrame_PWR(can_frame, int)));
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Power_Chose), 4);
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Pwr_Turn), 6);
break;
case 8:
qDebug() << "Init_WINDL";
WINDL = new Widget_INDL(this);
ui->stackedWidget->addWidget(WINDL);
if (INDL.size() < 495) {
qDebug() << "INDL Error" << INDL.size();
for (j = INDL.size(); j < 495; j++) {
INDL.append("0");
}
} else {
qDebug() << "INDL Ok";
}
WINDL->Copy_INDL_List = INDL;
WINDL->Pub_Conf_Set_INDL("", 1, 1);
connect(WINDL, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
connect(WINDL, SIGNAL(Lable_Display()), this, SLOT(SlOT_Lable_Display()));
break;
case 9:
qDebug() << "Init_WBLOCK";
WBLOCK = new Widget_BLOCK(this);
ui->stackedWidget->addWidget(WBLOCK);
if (BLOCK.size() < 495) {
qDebug() << "BLOCK Error" << BLOCK.size();
for (j = BLOCK.size(); j < 495; j++) {
BLOCK.append("0");
}
} else {
qDebug() << "BLOCK Ok";
}
WBLOCK->Copy_BLOCK_List = BLOCK;
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 1);
connect(WBLOCK, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
WBLOCK->Pub_Conf_Set_BLOCK(QString::number(Ini_Power_Chose), 1, 4);
break;
case 10:
qDebug() << "Init_WLVS";
WLVS = new Widget_LVS(this);
ui->stackedWidget->addWidget(WLVS);
if (LVS.size() < 495) {
qDebug() << "LVS Error" << LVS.size();
for (j = LVS.size(); j < 495; j++) {
LVS.append("0");
}
} else {
qDebug() << "LVS Ok";
}
WLVS->Copy_LVS_List = LVS;
WLVS->Pub_Conf_Set_LVS(QString(""), 1);
connect(WLVS, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
WLVS->Pub_Conf_Set_LVS(QString::number(Ini_Power_Chose), 4);
break;
case 11:
qDebug() << "Init_WHALL";
WPG = new Widget_BLDC_PG(this);
ui->stackedWidget->addWidget(WPG);
if (BLDCPG.size() < 300) {
qDebug() << "BLDCPG Error" << BLDCPG.size();
for (j = BLDCPG.size(); j < 300; j++) {
BLDCPG.append("0");
}
} else {
qDebug() << "BLDCPG Ok";
}
BLDC_PG_Data.clear();
BLDC_PG_Data.append(QString::number(Ini_BLDC_PG_Chose));
WPG->Copy_BLDCPG_List = BLDCPG;
WPG->Pub_Conf_Set_PG(BLDC_PG_Data, 1);
connect(WPG, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 12:
qDebug() << "Init_WLOAD";
WLOAD = new Widget_Load(this);
ui->stackedWidget->addWidget(WLOAD);
if (LOAD.size() < 200) {
qDebug() << "LOAD Error" << LOAD.size();
for (j = LOAD.size(); j < 200; j++) {
LOAD.append("0");
}
} else {
qDebug() << "LOAD Ok";
}
WLOAD->Copy_LOAD_List = LOAD;
WLOAD->Pub_Conf_Set_LOAD(QString(""), 1);
connect(WLOAD, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 13:
qDebug() << "Init_WNoLoad";
WNoLoad = new Widget_Noload(this);
ui->stackedWidget->addWidget(WNoLoad);
if (NOLOAD.size() < 200) {
qDebug() << "NOLOAD Error" << NOLOAD.size();
for (j = NOLOAD.size(); j < 200; j++) {
NOLOAD.append("0");
}
} else {
qDebug() << "NOLOAD Ok";
}
BLDC_Noload_Data.clear();
BLDC_Noload_Data.append(QString::number(Ini_BLDC_Start_Mode));
BLDC_Noload_Data.append(QString::number(Ini_BLDC_Start_Item));
WNoLoad->Copy_NOLOAD_List = NOLOAD;
WNoLoad->Pub_Conf_Set_NOLOAD(BLDC_Noload_Data, 1);
connect(WNoLoad, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
case 14:
qDebug() << "Init_WBEMF";
WBEMF = new Widget_BEMF(this);
ui->stackedWidget->addWidget(WBEMF);
if (BEMF.size() < 200) {
qDebug() << "BEMF Error" << BEMF.size();
for (j = BEMF.size(); j < 200; j++) {
BEMF.append("0");
}
} else {
qDebug() << "BEMF Ok";
}
WBEMF->Copy_BEMF_List = BEMF;
WBEMF->Pub_Conf_Set_BEMF(QString(""), 1);
connect(WBEMF, SIGNAL(canSend(can_frame)), this, SLOT(SlOT_CanSendFrame(can_frame)));
break;
default:
//
break;
}
// gettimeofday(&stop, 0);
// timeval_subtract(&dif f, &start, &stop);
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 计时操作
******************************************************************************/
int w_Conf::timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
{
if (x->tv_sec > y->tv_sec )
return -1;
if ((x->tv_sec == y->tv_sec) && (x->tv_usec > y->tv_usec) )
return -1;
result->tv_sec = (y->tv_sec-x->tv_sec);
result->tv_usec = (y->tv_usec-x->tv_usec);
if (result->tv_usec < 0) {
result->tv_sec--;
result->tv_usec += 1000000;
}
return 0;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 同步测试界面参数
******************************************************************************/
void w_Conf::Sync_Test_Widget()
{
signed int i = 0;
int j = 0;
QString name_list;
QStringList Back_Data;
strTest.clear(); // -测试项目
strParam.clear(); // -测试参数
sql_Test.clear(); // -测试数据库保存项目
for (i = 0; i < test_Inifile.size(); i++) {
for (j = 1; j < Ini_Proj.size(); j++) {
if (test_Inifile.at(i).toInt() == Ini_Proj[j].toInt()) {
break;
qDebug() << "break";
}
if (j == (Ini_Proj.size()-1)) {
test_Inifile.removeAt(i);
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, test_Inifile);
i--;
}
}
}
Test_Occur_Debug = CONF.at(12).toInt();
serial_number = CONF.at(14);
Conf_Test = test_Inifile;
int remove_number = 0;
int size = Conf_Test.size();
for (i = 0; i < size; i++) {
remove_number++;
qDebug() << "1111111" << ui->test->item(i, 0)->textColor().name();
if (ui->test->item(i, 0)->textColor().name() != "#008000") {
// 绿色字体的下发
Conf_Test.removeAt(remove_number-1);
remove_number--;
}
}
for (i = 0; i < Conf_Test.size(); i++) {
switch (Conf_Test.at(i).toInt()) {
case 1: // 电阻
strRES = RES;
Back_Data = WDLR->DCR_Test_Param();
strTest.append(Back_Data.mid(4, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(4 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
strDLR_UpDown = Back_Data.mid(4 + Back_Data.at(0).toInt() + \
Back_Data.at(1).toInt(), Back_Data.at(2).toInt());
sql_Test.append(Back_Data.mid(4 + Back_Data.at(0).toInt() + \
Back_Data.at(1).toInt() + Back_Data.at(2).toInt()));
break;
case 2: // 反嵌
strOPP = OPP;
Back_Data = WMAG->MAG_Test_Param(Ini_Mag_Hide);
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 3: // 绝缘
strIR = INS;
Back_Data = WIR->IR_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 4: // 交耐
strACW = ACV;
Back_Data = WACW->ACW_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 5: // 直耐
//
break;
case 6: // 匝间
strITT = ITT;
Back_Data = WIMP->IMP_Test_Param(Ini_imp_min);
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
strIMP_Param = Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt());
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 7: // 电参
strPWR = PWR;
Back_Data = WPWR->PWR_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 8: // 电感
strINDL = INDL;
Back_Data = WINDL->INDL_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 9: // -堵转
strBLOCK = BLOCK;
Back_Data = WBLOCK->BLOCK_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 10: // -低启
strLVS = LVS;
Back_Data = WLVS->LVS_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 11: // -霍尔
strPG = BLDCPG;
Back_Data = WPG->PG_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 12: // -负载
strLOAD = LOAD;
Back_Data = WLOAD->LOAD_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 13: // -空载
strNOLOAD = NOLOAD;
Back_Data = WNoLoad->NOLOAD_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
case 14: // -反电动势
strBEMF = BEMF;
Back_Data = WBEMF->BEMF_Test_Param();
strTest.append(Back_Data.mid(3, Back_Data.at(0).toInt()));
strParam.append(Back_Data.mid(3 + Back_Data.at(0).toInt(), Back_Data.at(1).toInt()));
sql_Test.append(Back_Data.mid(3 + Back_Data.at(0).toInt() + Back_Data.at(1).toInt()));
break;
default:
//
break;
}
}
QString Check_strTest; // -建立字符串, 字符串列表转化为字符串
for (i = 0; i < strTest.size(); i++) {
Check_strTest += strTest.at(i);
}
signed int si;
qDebug() << "2018-7-11 Conf_Test" << Check_strTest <<Conf_Test;
for (si = 0; si < Conf_Test.size(); si++) {
switch (Conf_Test.at(si).toInt()) {
case 1:
if (Check_strTest.indexOf(QString(tr("电阻"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 2:
if ((Check_strTest.indexOf(QString(tr("反嵌"))) < 0) && \
(Check_strTest.indexOf(QString(tr("磁旋"))) < 0)) {
Conf_Test.removeAt(si);
si--;
}
break;
case 3:
if (Check_strTest.indexOf(QString(tr("绝缘"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 4:
if (Check_strTest.indexOf(QString(tr("交耐"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 5:
//
break;
case 6:
if (Check_strTest.indexOf(QString(tr("匝间")), 0, Qt::CaseInsensitive) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 7:
//
break;
case 8:
if (Check_strTest.indexOf(QString(tr("电感"))) < 0) {
Conf_Test.removeAt(si);
si--;
}
break;
case 9:
//
break;
case 10:
//
break;
case 11:
//
break;
case 12:
//
break;
case 13:
//
break;
case 14:
//
break;
default:
break;
}
}
qDebug() << "2018-7-11 Conf_Test" << Conf_Test;
qDebug() << "sql_Test--------" << sql_Test;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.7.19
* brief: 保存配置Ini文件
******************************************************************************/
void w_Conf::Save_Ini_DateFile()
{
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.setValue("DateFile/datefile", DateFile);
set_Test_File.setValue("DateFile/currentfile", currentFile);
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 从配置文件中,读取设置数据
******************************************************************************/
void w_Conf::Get_SqlData()
{
int i = 0;
QStringList Allocation_list; // -默认 Allocation/Item
Allocation_list.clear();
Allocation_list.append("13");
Allocation_list.append("14");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("0");
Allocation_list.append("1");
QStringList Password_list; // -默认 Password/Text
Password_list.clear();
Password_list.append("6");
Password_list.append("456");
Password_list.append("789");
QStringList System_list; // 默认 System/Text
System_list.clear();
System_list.append("9"); // -蜂鸣器的档位
System_list.append("0.1"); // -合格时间
System_list.append("0.3"); // -不合格时间
System_list.append("9"); // -Led档位
System_list.append("0"); // -启动模式
System_list.append("1"); // -管理员
QString parameter_set;
QSettings *set_Sys = new QSettings(Sys_path, QSettings::IniFormat);
set_Sys->setIniCodec("GB18030");
Ini_Number = set_Sys->value("Allocation/All", "7").toString().toInt();
Ini_Proj_Real = set_Sys->value("Allocation/Item", Allocation_list).toStringList();
// Ini_Proj_Real.append(tr("14"));
Ini_Proj = set_Sys->value("Allocation/Item",
Allocation_list).toStringList().mid(5, Ini_Number);
// Ini_Proj.append(tr("14"));
Ini_Password = set_Sys->value("Password/Text", Password_list).toStringList();
Ini_SQL_Enable = set_Sys->value("Sql/Text", "disable").toString();
Ini_Factory = set_Sys->value("Factory/text", "V-0.0.0").toString();
Ini_Set_ImpVolt = set_Sys->value("impvolt/text", "noback").toString();
Ini_IRHostJudge = set_Sys->value("IRHostJudge/text", "0").toInt();
Ini_Motor = set_Sys->value("System/PG", "Common").toString();
Ini_DCR_Balance = set_Sys->value("System/Unbalance", "1").toInt();
Ini_Task_Table = set_Sys->value("Sql/Task_Table", "1").toString();
Ini_Pwr_Turn = set_Sys->value("System/Shan_Turn", "0").toInt();
Ini_Power_Chose = set_Sys->value("power/Text", "0").toInt();
// -电源选择方式-默认为0
Ini_Mag_Hide = set_Sys->value("magshapehide/text", "0").toInt();
// -反嵌的波形是否隐藏-默认为0
Ini_Udp_Enable = set_Sys->value("UDP/text", "0").toInt();
// -UDP上传-默认为0
Ini_ACW_And_IR = set_Sys->value("commonACW/text", "0").toInt();
// -设置相间耐压和普通耐压的转换-默认为0
Ini_System = set_Sys->value("System/Text", System_list).toStringList();
Ini_ActiveFile = set_Sys->value("ActiveFile/file", "Base_File").toString();
// 获取当前文件
Ini_imp_min = set_Sys->value("imp_min/area_diff", "0").toInt();
// -设置匝间下限
Ini_BLDC_Start_Mode = set_Sys->value("BLDC/Start_Mode", "0").toInt();
Ini_BLDC_Start_Item = set_Sys->value("BLDC/Start_Item", "0").toInt();
Ini_BLDC_PG_Chose = set_Sys->value("BLDC/PG_Chose", "0").toInt();
Out_Channel_6 = set_Sys->value("System/out6", "0").toInt();
Ini_IMP5000 = set_Sys->value("System/IMP5000", "0").toInt();
Ini_IR5000 = set_Sys->value("System/IR5000", "0").toInt();
Ini_DCR15 = set_Sys->value("System/dcr_Disable", "0").toInt();
system("sync");
delete set_Sys;
qDebug() << "Ini_Proj---------------------------->" << Ini_Proj;
Conf_User = Ini_System.at(5).toInt(); // 2017.6.7 添加使用用户
Ini_Factory = "A"+Ini_Factory;
ui->label_Text->setText(QString(tr("当前文件:")) + Ini_ActiveFile);
if ((Ini_SQL_Enable == "enable") && (same_ip_address) && (!isopend)) {
isopend = true;
if (sql_net.open_net_Sql("testodbc")) {
Singal_Conf_to_Main(QStringList(""), QString(""), 1, 3);
NetSQL_OpenOk = true;
SQL_Init = true;
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo); qDebug() << "Sql Init";
if (sql_net.dbtwo.tables().contains(Ini_Factory)) {
// -查询是否存在表,若不存在进行创建数据库
//
} else {
QString create = (QString(tr("create table %1 (id integer primary key, "\
"项目 nvarchar(50), 参数 nvarchar(50), 结果 nvarchar(50), "\
"判定 nvarchar(50), 配置 nvarchar(50), 项目1 nvarchar(50), "\
"项目2 nvarchar(50))")).arg(Ini_Factory));
query_net.exec(create);
} qDebug() << "Sql Init Finsh";
QString net_str = QString(tr("Select 生产线, 生产任务编号 from %1 "))\
.arg(Ini_Task_Table); //
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
SQL_Task.append(query_net.value(1).toString().trimmed());
}
for (i = 0; i < SQL_Task.size()/2; i++) {
SQL_Produce_Plan->addItem(QWidget::tr("%1").arg(SQL_Task.at(i*2+0)));
SQL_Produce_Number->addItem(QWidget::tr("%1").arg(SQL_Task.at(i*2+1)));
}
SQL_Init = false;
SQL_Produce_Plan_textChanged(SQL_Produce_Plan->currentText());
} else {
NetSQL_OpenOk = false;
}
} else {
qDebug() << "SQL Disable";
}
QString Filename;
Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").arg(Ini_ActiveFile);
QSettings set_File(Filename, QSettings::IniFormat);
for (i = 0; i < parameter.size(); i++) {
parameter_set = QString("%1/value").arg(parameter[i]);
strList[i] = set_File.value(parameter_set).toStringList();
}
QSettings Add_File("/mnt/nandflash/AIP/AddFile.ini", QSettings::IniFormat);
Add_File.setIniCodec("UTF-8");
if (PWR == QStringList()) {
qDebug() << "PWR == NULL";
strList[7] = Add_File.value("PWR/value").toStringList();
}
if (INDL == QStringList()) {
qDebug() << "INDL == NULL";
strList[8] = Add_File.value("INDL/value").toStringList();
}
if (BLOCK == QStringList()) {
qDebug() << "BLOCK == NULL";
strList[9] = Add_File.value("BLOCK/value").toStringList();
}
if (LVS == QStringList()) {
qDebug() << "LVS == NULL";
strList[10] = Add_File.value("LVS/value").toStringList();
}
if (CONF.size() < 100) {
qDebug() << "CONF Error" << CONF.size();
for (i = CONF.size(); i < 150; i++) {
CONF.append("0");
}
} else {
qDebug() << "CONF Ok";
}
conf_c = CONF;
// 获取Test_File.ini文件(若不存在,建立ini文件)
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
QString name_list; name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setIniCodec("UTF-8");
test_Inifile = set_Test_File.value(name_list).toStringList();
qDebug() << "test_Inifile" << test_Inifile;
// -2016-12-9 在修改配置后,以前的测试文件必须删除,比如之前的-<测试项目>-有电参,
// 现在配置里面取消电参配置,在测试文件-<测试项目>-取消电参
for (i = 0; i < test_Inifile.size(); i++) {
if (Ini_Proj.indexOf(test_Inifile.at(i)) >= 0) {
//
} else {
test_Inifile.removeAt(i);
i--;
}
}
DateFile = set_Test_File.value("DateFile/datefile").toStringList();
currentFile = set_Test_File.value("DateFile/currentfile").toStringList();
/* QSqlQuery query(sql.db);
sql.db.transaction();
if (sql.isTabExst("TestDa", sql.db)) { // 若TestDa存在,必要时进行删除操作
} else {
QString create=tr("create table TestDa (id integer primary key,"\
"项目 Text,参数 Text,结果 Text,判定 Text,配置 Text,"\
"项目1 Text,项目2 Text)");
query.exec(create);
if (sdcard_exist) {
system("chmod +x /mnt/sdcard/aip.db");
} else {
system("chmod +x /mnt/nandflash/aip.db");
}
} */
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 初始化文件名称
******************************************************************************/
void w_Conf::Init_Conf_file(int row, QStringList file)
{
int i = 0;
ui->fileTab->setRowCount(0);
ui->fileTab->setColumnWidth(0, 135); // -初始化文件名称
if (row > 9) { // -设置文件和型号行数
ui->fileTab->setRowCount(row);
for (i = 0; i < row; i++) {
ui->fileTab->setRowHeight(i, 39);
}
} else {
ui->fileTab->setRowCount(9);
for (i = 0; i < 9; i++) {
ui->fileTab->setRowHeight(i, 39);
}
}
for (i = 0; i < row; i++) {
QTableWidgetItem *pItem = new QTableWidgetItem(file.at(i));
pItem->setTextAlignment(Qt::AlignCenter);
ui->fileTab->setItem(i, 0, pItem);
}
ui->fileTab->verticalScrollBar()->setValue(0);
checked_File = file;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.6.6
* brief: 可选项目 按键使能
******************************************************************************/
void w_Conf::Conf_ProjKey(int i, bool judge)
{
if (judge == false) {
btnGroup_Item->button(i)->hide();
} else {
btnGroup_Item->button(i)->show();
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 初始化设置界面
******************************************************************************/
void w_Conf::Init_Conf_Interface()
{
int i = 0;
ui->combConf1->setCurrentIndex(CONF[12].toInt()); // 遇不合格测试项目是否继续
ui->file_number->setText(CONF[14]);
if (model_Type.indexOf(CONF[13]) >= 0) {
if (CONF[13] == ui->MotorType->currentText()) {
on_MotorType_currentIndexChanged(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
}
} else {
on_MotorType_currentIndexChanged(0);
}
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
if ((test_Inifile.size()) >= 13) {
if (test_Inifile.size() <= 15) {
ui->test->setRowCount(test_Inifile.size()+1);
for (i = 0; i < (test_Inifile.size() + 1); i++) {
ui->test->setRowHeight(i, 39);
}
} else {
ui->test->setRowCount(16);
for (i = 0; i < (test_Inifile.size() + 1); i++) {
ui->test->setRowHeight(i, 39);
}
}
} else {
ui->test->setRowCount(13);
for (i = 0; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
}
Init_test_TableWidget();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 初始化测试项目
******************************************************************************/
void w_Conf::Init_test_TableWidget()
{
int i = 0;
test_List.clear();
for (i = 0; i < test_Inifile.size(); i++) {
int item = test_Inifile[i].toInt();
test_List.append(Test_Item[item]);
QTableWidgetItem *pItem = new QTableWidgetItem;
pItem->setTextAlignment(Qt::AlignCenter);
pItem->setText(Test_Item[item]);
pItem->setTextColor(QColor("green"));
ui->test->setItem(i, 0, pItem);
}
qApp->processEvents();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.12.30
* brief: 将数据存入数据库
******************************************************************************/
void w_Conf::Save_SqlData()
{
qDebug() << "ui->stackedWidget->currentIndex()" << ui->stackedWidget->currentIndex();
qDebug() << Ini_Proj;
int num = Ini_Proj[ui->stackedWidget->currentIndex()].toInt();
QString Filename;
Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").arg(Ini_ActiveFile);
QSettings set_File(Filename, QSettings::IniFormat);
set_File.setValue(QString("%1/value").arg(parameter[num]), strList[num]);
}
/******************************************************************************
* version: 1.0
* author: SL
* date: 2016.4.15
* brief: 将配置数据存入数据库
******************************************************************************/
void w_Conf::Save_SystemConf_Data(int choose)
{
QSettings *configIniWrite = new QSettings(Sys_path, QSettings::IniFormat);
configIniWrite->setIniCodec("GB18030");
switch (choose) {
case 1:
configIniWrite->beginGroup("Allocation"); // -配置数据
configIniWrite->setValue("All", QString::number(Ini_Number));
configIniWrite->setValue("Item", QStringList(Ini_Proj_Real));
break;
case 2:
configIniWrite->beginGroup("System"); //系统数据
configIniWrite->setValue("Text", QStringList(Ini_System.mid(0, 6)));
break;
case 3:
configIniWrite->beginGroup("Password"); // -密码数据
configIniWrite->setValue("Text", QStringList(Ini_Password));
break;
default:
//
break;
}
system("sync");
configIniWrite->endGroup();
delete configIniWrite;
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 保存配置数据
******************************************************************************/
void w_Conf::Save_ConfData()
{
int i = 0; // -更新设置数据
Item_Widget->hide();
Conf_label_Hide->hide();
for (i = 0; i < 8; i++) {
CONF.replace(i, colorIdList[i]);
}
CONF.replace(12, QString::number(ui->combConf1->currentIndex()));
CONF.replace(13, ui->MotorType->currentText());
CONF.replace(14, ui->file_number->text());
}
void w_Conf::Set_Color(QString colr)
{
QString str;
colorIdList.replace(iColorBtn, colr);
colorIdList_C.replace(iColorBtn, colr);
if (colr == "#000000") {
str = QString("height:120px;width:95px;background-color:%1;color:white;").arg((colr));
} else {
str = QString("height:120px;width:95px;background-color:%1").arg((colr));
}
qColor_BtnList[iColorBtn]->setStyleSheet(str);
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2015.5.11
* brief: 设置提示保存
******************************************************************************/
void w_Conf::Save_Hint()
{
int i = 0, SetAddress = 0; // -初始状态 0
if (!TabWidget_Changed) {
return;
}
for (i = 0; i < (Ini_Number-5); i++) {
if ((Ini_Proj.at(i).toInt()) == index_c) {
SetAddress = i;
break;
}
}
if (SetAddress > Ini_Proj.size()) {
SetAddress = 0;
}
switch (Ini_Proj.at(SetAddress).toInt()) {
case 0:
qDebug() << "配置首页";
Save_ConfData();
if (CONF != conf_c) {
conf_c = CONF;
if (model_Type.indexOf(CONF[13]) >= 0) {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(0); // -设定文件
}
Init_Conf_Interface();
}
break;
case 1:
qDebug() << "电阻";
WDLR->Pub_Conf_Set_DLR("", 3);
if (RES != WDLR->Copy_DLR_List) {
TabWidget_Changed = false;
}
break;
case 2:
qDebug() << "反嵌";
WMAG->Pub_Conf_Set_MAG("", 2);
if (OPP != WMAG->Copy_MAG_List) {
TabWidget_Changed = false;
}
break;
case 3:
qDebug() << "绝缘";
WIR->Pub_Conf_Set_IR("", 2);
if (INS != WIR->Copy_IR_List) {
TabWidget_Changed = false;
}
break;
case 4:
qDebug() << "交耐";
WACW->Pub_Conf_Set_ACW("", 2);
if (ACV != WACW->Copy_ACW_List) {
TabWidget_Changed = false;
}
break;
case 5:
qDebug() << "直耐";
WDCW->Save_DCW_Data();
if (DCV != WDCW->Copy_DCW_List) {
TabWidget_Changed = false;
}
break;
case 6:
qDebug() << "匝间";
WIMP->Pub_Conf_Set_IMP("", 4);
if (ITT != WIMP->Copy_IMP_List) {
TabWidget_Changed = false;
}
break;
case 7:
qDebug() << "电参";
WPWR->Pub_Conf_Set_PWR("", 2);
if (PWR != WPWR->Copy_PWR_List) {
TabWidget_Changed = false;
}
break;
case 8:
qDebug() << "电感";
WINDL->Pub_Conf_Set_INDL("", 1, 2);
if (INDL != WINDL->Copy_INDL_List) {
TabWidget_Changed = false;
}
qDebug() << "电感";
break;
case 9:
qDebug() << "堵转";
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 2);
if (BLOCK != WBLOCK->Copy_BLOCK_List) {
TabWidget_Changed = false;
}
break;
case 10:
qDebug() << "低启";
WLVS->Pub_Conf_Set_LVS("", 2);
if (LVS != WLVS->Copy_LVS_List) {
TabWidget_Changed = false;
}
break;
case 11:
qDebug() << "霍尔";
WPG->Pub_Conf_Set_PG(QStringList(""), 2);
if (BLDCPG != WPG->Copy_BLDCPG_List) {
qDebug() << BLDCPG;
qDebug() << WPG->Copy_BLDCPG_List;
TabWidget_Changed = false;
}
break;
case 12:
qDebug() << "负载";
WLOAD->Pub_Conf_Set_LOAD("", 2);
if (LOAD != WLOAD->Copy_LOAD_List) {
TabWidget_Changed = false;
}
break;
case 13:
qDebug() << "空载";
WNoLoad->Pub_Conf_Set_NOLOAD(QStringList(""), 2);
if (NOLOAD != WNoLoad->Copy_NOLOAD_List) {
TabWidget_Changed = false;
}
break;
case 14:
WBEMF->Pub_Conf_Set_BEMF(QString(""), 2);
if (BEMF != WBEMF->Copy_BEMF_List) {
TabWidget_Changed = false;
}
qDebug() << "反电动势";
break;
default:
//
break;
}
if (TabWidget_Changed) { // -数据有改动
return;
}
ui->stackedWidget->setCurrentIndex(SetAddress); // 11.11 更改设置
QMessageBox message; //= new QMessageBox(this);
message.setWindowFlags(Qt::FramelessWindowHint);
message.setStyleSheet("QMessageBox{border:3px groove gray;}"\
"background-color: rgb(209, 209, 157);");
message.setText(tr(" 是否进行保存 \n "));
message.addButton(QMessageBox::Ok)->setStyleSheet
("border:none;height:30px;width:65px;"\
"border:5px groove gray;border-radius:10px;padding:2px 4px;");
message.addButton(QMessageBox::Cancel)->setStyleSheet
("border:none;height:30px;width:65px;border:5px groove gray;"\
"border-radius:10px;padding:2px 4px;");
message.setButtonText(QMessageBox::Ok, QString(tr("确 定")));
message.setButtonText(QMessageBox::Cancel, QString(tr("取 消")));
message.setIcon(QMessageBox::Warning);
int ret = message.exec();
if (ret == QMessageBox::Ok) {
SlOT_Button_Function_Judge(Qt::Key_B); // -触发保存
}
if (ret == QMessageBox::Cancel) {
switch (Ini_Proj.at(SetAddress).toInt()) {
case 0:
CONF = conf_c;
if (model_Type.indexOf(CONF[13]) >= 0) {
ui->MotorType->setCurrentIndex(model_Type.indexOf(CONF[13]));
} else {
ui->MotorType->setCurrentIndex(0); // -设定文件
}
Init_Conf_Interface();
break;
case 1:
WDLR->Copy_DLR_List = RES;
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR15), 1);
WDLR->Pub_Conf_Set_DLR(QString::number(Ini_DCR_Balance), 13);
break;
case 2:
WMAG->Copy_MAG_List = OPP;
WMAG->Pub_Conf_Set_MAG(QString::number(Ini_Mag_Hide), 1);
break;
case 3:
WIR->Copy_IR_List = INS;
WIR->Pub_Conf_Set_IR(QString::number(Ini_ACW_And_IR), 1);
break;
case 4:
WACW->Copy_ACW_List = ACV;
WACW->Pub_Conf_Set_ACW(QString::number(Ini_IR5000), 101);
WACW->Pub_Conf_Set_ACW(QString::number(Ini_ACW_And_IR), 1);
break;
case 5:
WDCW->Copy_DCW_List = DCV;
WDCW->Init_DCW();
break;
case 6:
WIMP->Copy_IMP_List = ITT;
WIMP->Pub_Conf_Set_IMP(QString::number(Ini_IMP5000), 101);
WIMP->Pub_Conf_Set_IMP(Ini_ActiveFile, 1);
break;
case 7:
qDebug() << "电参 保存";
WPWR->Copy_PWR_List = PWR;
WPWR->Pub_Conf_Set_PWR(Ini_Motor, 1);
WPWR->Pub_Conf_Set_PWR(QString::number(Ini_Pwr_Turn), 6);
break;
case 8:
WINDL->Copy_INDL_List = INDL;
WINDL->Pub_Conf_Set_INDL("", 1, 1);
qDebug() << "电感 保存";
break;
case 9:
qDebug() << "堵转 保存";
WBLOCK->Copy_BLOCK_List = BLOCK;
WBLOCK->Pub_Conf_Set_BLOCK("", 1, 1);
break;
case 10:
qDebug() << "低启 保存";
WLVS->Copy_LVS_List = LVS;
WLVS->Pub_Conf_Set_LVS(QString(""), 1);
break;
case 11:
qDebug() << "霍尔 保存";
break;
case 12:
qDebug() << "负载 保存";
break;
case 13:
qDebug() << "空载 保存";
break;
case 14:
qDebug() << "反电动势 保存";
break;
default:
//
break;
}
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.6.6
* brief: 选定 测试项目
******************************************************************************/
void w_Conf::on_test_clicked(const QModelIndex &index)
{
int i = 0;
btnGroup_Item->button(0)->hide();
btnGroup_Item->button(20)->hide();
Item_Chose_Box->hide();
Item_Chose_Box->setChecked(true);
if ((index.row() + 1) <= (test_Inifile.size())) {
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
Item_Chose_Box->show();
if (ui->test->item(index.row(), 0)->textColor().name() != "#008000") {
Item_Chose_Box->setChecked(false);
}
}
for (i = 1; i <= 10; i++) { // -设置组不能超过--两组
if (test_Inifile.indexOf(QString::number(i)) < 0) {
continue;
}
if (test_Inifile.indexOf(QString::number(i), \
(1+test_Inifile.indexOf(QString::number(i)))) >= 0) {
btnGroup_Item->button(i)->hide();
}
}
remove_row = index.row();
Conf_label_Hide->show();
Item_Widget->show(); Item_Widget->raise();
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 添加文件
******************************************************************************/
void w_Conf::on_fileBtnAdd_clicked()
{
int i = 0;
char copystr[256];
QString currentDateTime = QDateTime::currentDateTime().toString\
("yyyy-MM-dd hh:mm:ss"); // -设置显示格式
if (ui->fileEdit1->text() != NULL) {
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileEdit1->text() == currentFile.at(i)) {
ui->label_Text->setText(tr("型号名称重復"));
break;
}
}
if (i == currentFile.size()) {
currentFile.append(ui->fileEdit1->text());
DateFile.append(currentDateTime);
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile);
ui->fileTab->verticalScrollBar()->setValue(ui->fileTab->rowCount());
//更新数据
sprintf(copystr, "touch /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(ui->fileEdit1->text()).toUtf8().data());
system(copystr);
sprintf(copystr, "chmod +x /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(ui->fileEdit1->text()).toUtf8().data());
system(copystr);
QString Filename; Filename = QString("/mnt/nandflash/AIP/ConfFile/%1.ini").\
arg(ui->fileEdit1->text());
QSettings set_File(Filename, QSettings::IniFormat);
qDebug() << "11";
for (i = 0; i < parameter.size(); i++) {
set_File.setValue(QString("%1/value").arg(parameter[i]), strList[i]);
}
qDebug() << "22";
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.setValue(QString("Test_File/%1").arg \
(ui->fileEdit1->text()), test_Inifile);
ui->label_Text->setText(QString(tr("当前文件:")) + Ini_ActiveFile);
qDebug() << "33";
on_fileTab_cellClicked(currentFile.size()-1, 0);
}
ui->fileEdit1->clear();
} else {
Pri_Conf_WMessage(QString(tr("请输入型号名称")));
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 删除文件
******************************************************************************/
void w_Conf::on_fileBtnDel_clicked()
{
char copystr[256];
ui->fileTab->currentRow();
if (currentFile.at(0) != "Base_File") {
currentFile.removeAt(0); DateFile.removeAt(0);
Save_Ini_DateFile();
sprintf(copystr, "rm /mnt/nandflash/AIP/ConfFile/%s.ini", \
QString(Ini_ActiveFile).toUtf8().data());
system(copystr);
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
set_Test_File.remove(QString("Test_File/%1").arg(Ini_ActiveFile));
Init_Conf_file(currentFile.size(), currentFile);
on_fileTab_cellClicked(0, 0);
} else if (currentFile.at(0) == "Base_File") {
Pri_Conf_WMessage(QString(tr("Base_File不能删除 ")));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.1
* brief: Can发送数据 触发
******************************************************************************/
void w_Conf::SlOT_CanSendFrame(can_frame frame)
{
emit canSend(frame, 88); // -总触发
}
void w_Conf::SlOT_CanSendFrame_PWR(can_frame frame,int Usart) {
if (Usart==1) {
PWR_Test_Usart = true;
}
else {
}
emit canSend(frame,88); // 总触发
qDebug()<<"下发";
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 电感清0
******************************************************************************/
void w_Conf::SlOT_Lable_Display()
{
lable_Zero->show();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.8
* brief: 温度进行补偿
******************************************************************************/
void w_Conf::DLR_Compensate_Back(QStringList list)
{
int DLR_Compensate = 0;
DLR_Compensate = WDLR->Pub_Conf_DLR_Compensate(list);
if (DLR_Compensate == 1) {
ui->Key_D->setStyleSheet("background:#00FF00; color:rgb(0, 0, 0);");
ui->Key_D->setText(tr("左OK")); // -已补偿
} else if (DLR_Compensate == 2) {
ui->Key_D->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_D->setText(tr("左清零")); // -未补偿
Pri_Conf_WMessage(tr(" 左工位补偿错误 "));
} else if (DLR_Compensate == 3) {
ui->Key_E->setStyleSheet("background:#00FF00; color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("右OK")); // -已补偿
} else if (DLR_Compensate == 4) {
ui->Key_E->setStyleSheet("background: qlineargradient"\
"(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #5B5F5F, "\
"stop: 0.5 #0C2436,stop: 1 #27405A);color:rgb(255, 255, 255);");
ui->Key_E->setText(tr("右清零")); // -未补偿
Pri_Conf_WMessage(tr(" 右工位补偿错误 "));
} else {
//
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.10
* brief: 设置操作员和管理者
******************************************************************************/
void w_Conf::Conf_Set_User(int value)
{
int id = value/1000;
int changer_number = value%1000;
if (Conf_User == User_Administrators) {
ui->label_User->hide(); // -可以设置
ui->fileEdit1->setEnabled(true);
ui->fileBtnAdd->setEnabled(true);
ui->fileBtnCheck->setEnabled(true);
ui->fileBtnDel->setEnabled(true);
} else {
//
}
if ((Conf_User == User_Operator) && (!conf_Waring)) {
ui->label_User->show(); // -不可以设置
ui->label_User->raise();
ui->fileEdit1->setDisabled(true);
ui->fileBtnAdd->setDisabled(true);
ui->fileBtnCheck->setDisabled(true);
ui->fileBtnDel->setDisabled(true);
} else {
//
}
if (changer_number != 0) {
on_fileTab_cellClicked(changer_number, 0);
} else {
//
}
ui->imp_button_add->hide();
ui->imp_button_cancel->hide();
ui->imp_button_finsh->hide();
if (id < 100) {
if((Conf_User==User_Operator)&&(!conf_Waring)) {
qDebug()<<"进行移动";
ui->label_User->setGeometry(0,0,721,600);
ui->label_User->move(0,0);
}
SlOT_Button_Conf_Judge(48+id); // -进入到设置首页
} else {
ui->label_User->setGeometry(299,0,401,600);
SlOT_Button_Conf_Judge(48); // -进入到设置首页
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 配置查询文件和型号
******************************************************************************/
void w_Conf::on_fileBtnCheck_clicked()
{
int i = 0;
int Error_Flag = 0;
QStringList Check_File;
if (ui->fileEdit1->text() == "") {
Error_Flag = 1;
} else if (ui->fileEdit1->text() != "") {
Check_File.clear();
for (i = 0; i < currentFile.size(); i++) {
if (!(ui->fileTab->item(i, 0) == NULL)) {
if (ui->fileTab->item(i, 0)->text().contains\
(ui->fileEdit1->text(), Qt::CaseInsensitive)) {
Check_File.append(ui->fileTab->item(i, 0)->text());
Error_Flag = 2;
}
}
}
if (Error_Flag == 2) {
Init_Conf_file(Check_File.size(), Check_File);
}
} else {
//
}
if (Error_Flag == 0) {
Pri_Conf_WMessage(tr(" 当前查询不存在 "));
}
if (Error_Flag == 1) {
Save_Ini_DateFile();
Init_Conf_file(currentFile.size(), currentFile);
}
ui->fileEdit1->clear(); // -文件和型号清空
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 设置警告弹出框
******************************************************************************/
void w_Conf::Pri_Conf_WMessage(QString Waring_Text)
{
conf_Waring = true; label_Waring->show();
QMessageBox *message = new QMessageBox(this);
message->setWindowFlags(Qt::FramelessWindowHint);
message->setStyleSheet("QMessageBox{border: gray;border-radius: 10px;"\
"padding:2px 4px;background-color: gray;height:390px;width:375px;}");
message->setText("\n"+Waring_Text+"\n");
message->addButton(QMessageBox::Ok)->setStyleSheet("height:39px;width:75px;"\
"border:5px groove;border:none;border-radius:10px;padding:2px 4px;");
message->setButtonText(QMessageBox::Ok, QString(tr("确 定")));
message->setIcon(QMessageBox::Warning);
message->exec();
conf_Waring = false; label_Waring->hide();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.5.19
* brief: 单击文件列表 更换数据管理型号
******************************************************************************/
void w_Conf::on_fileTab_cellClicked(int row, int column)
{
int i = 0, Count = 0;
if (!Clicked) {
return;
}
column = 0;
label_Waring->show();
Clicked = false;
if (Ini_Proj[ui->stackedWidget->currentIndex()].toInt() == 0) {
if (row < 0) {
label_Waring->hide();
Clicked = true;
return;
}
if (row >= (checked_File.size())) {
label_Waring->hide();
Clicked = true;
return;
}
if (checked_File.at(row) == Ini_ActiveFile) {
label_Waring->hide();
Clicked = true;
return;
}
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(row, 0)->text() == currentFile.at(i)) { // -设置背景
Count = i;
break;
}
}
QSettings *set_Sys = new QSettings(Sys_path, QSettings::IniFormat);
set_Sys->setIniCodec("GB18030");
set_Sys->setValue("ActiveFile/file", ui->fileTab->item(row, 0)->text());
system("sync");
delete set_Sys;
currentFile.removeAt(i);
currentFile.insert(0, ui->fileTab->item(row, 0)->text());
DateFile.removeAt(i);
DateFile.insert(0, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
Save_Ini_DateFile();
Sync_Conf();
}
label_Waring->hide();
Clicked = true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 测试界面和配置界面传递信息
******************************************************************************/
void w_Conf::Slot_test_to_conf(QStringList list, QString str, int value)
{
str.clear();
switch (value) {
case 1:
Save_Test_Data(list);
break;
case 2:
WIR->Pub_Conf_Set_IR(QString::number(Ini_IRHostJudge), 5); // -测试绝缘启动
break;
case 3:
WACW->Pub_Conf_Set_ACW(" ", 5); // -测试交耐启动
break;
default:
break;
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 测试数据的保存
******************************************************************************/
void w_Conf::Save_Test_Data(QStringList all_data)
{
int i = 0;
QStringList Result, Judge, Get_Set;
Result = all_data.mid(3, all_data.at(0).toInt()); // -结果
Judge = all_data.mid(3+all_data.at(0).toInt(), all_data.at(1).toInt()); // -判定
Get_Set = all_data.mid(3+all_data.at(0).toInt()+all_data.at(1).toInt(), \
all_data.at(2).toInt()); // -数据
/* QStringList_No_OK = all_data.mid(4+all_data.at(0).toInt()+ \
all_data.at(1).toInt()+all_data.at(2).toInt(),all_data.at(3).toInt()); // -不合格项目
QSqlQuery query(sql.db);
sql.db.transaction(); */
if (strTest.size() != Judge.size()) { // -补齐判定数据
for (i = Judge.size(); i < strTest.size(); i++) {
Judge.append("");
}
}
if (strTest.size() != Result.size()) { // -补齐结果数据
for (i = Result.size(); i < strTest.size(); i++) {
Result.append("");
}
}
for (i = 0; i < strTest.size(); i++) { // -判断测试结果中是否包含"," ","替换为 ","
if ((strTest.at(i).contains(tr("绝缘"))) || \
(strTest.at(i).contains(tr("交耐"))) || \
(strTest.at(i).contains(tr("匝间"))) || \
(strTest.at(i).contains(tr("电感"))) || \
(strTest.at(i).contains(tr("堵转"))) || \
(strTest.at(i).contains(tr("电参"))) || \
(strTest.at(i).contains(tr("低启"))) || \
(strTest.at(i).contains(tr("PG"))) || \
(strTest.at(i).contains(tr("空载"))) || \
(strTest.at(i).contains(tr("HALL")))) { // 绝缘 交耐 匝间
strParam.replace(i, QString(strParam.at(i)).replace(QRegExp("\\,"), " "));
// 2017 3 10 印度问题改变","--" "
}
if ((strTest.at(i).contains(tr("电阻"))) || \
(strTest.at(i).contains(tr("绝缘")))) {
strParam.replace(i, QString(strParam.at(i)).replace(QRegExp("\\Ω"), " "));
}
}
for (i = 0; i < Judge.size(); i++) {
if (strTest.at(i).contains(tr("电阻"))) { // -电阻参数
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\Ω"), ""));
} else if (strTest.at(i).contains(tr("绝缘"))) { // -绝缘
Result.replace(i, QString(Result.at(i)).mid \
(QString(Result.at(i)).indexOf(",")+1, QString(Result.at(i)).length()));
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\MΩ"), ""));
} else if (strTest.at(i).contains(tr("交耐"))) { // -交耐
Result.replace(i, QString(Result.at(i)).mid \
(QString(Result.at(i)).indexOf(",")+1, QString(Result.at(i)).length()));
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\mA"), ""));
} else if (strTest.at(i).contains(tr("匝间"))) { // -匝间 若没有(电晕,相位)时进行补齐
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).append(", , "));
} else if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 3) {
//
} else {
Result.replace(i, " , , , ");
}
} else if (strTest.at(i).contains(tr("电感"))) { // -电感 若没有(Q值)时进行补齐
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 0) {
Result.replace(i, QString(Result.at(i)).append(", "));
} else {
//
}
} else if (strTest.at(i).contains(tr("电参"))) { // -电参
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 2) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
qDebug() << Result.at(i);
} else {
Result.replace(i, " , , ");
}
} else if (strTest.at(i).contains(tr("堵转"))) { // -堵转
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
} else {
Result.replace(i, " , ");
}
} else if (strTest.at(i).contains(tr("低启"))) { // -低启
if ((QStringList(QString(Result.at(i)).split(",")).size()-1) == 1) {
Result.replace(i, QString(Result.at(i)).replace(QRegExp("[A-Z]"), " "));
} else {
Result.replace(i, " , ");
}
} else if (strTest.at(i).contains(tr("PG"))) { // -PG
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else if (strTest.at(i).contains(tr("空载"))) { // -空载
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else if (strTest.at(i).contains(tr("HALL"))) { // -HALL
Result.replace(i, QString(Result.at(i)).replace(QRegExp("\\,"), " "));
} else {
//
}
}
QStringList SQL_Item, SQL_Param, SQL_Result, SQL_Judge;
SQL_Item.append("ITEM-1"); // -ITEM-1
SQL_Item.append("ITEM-2"); // -ITEM-2
SQL_Item.append("ITEM-3"); // -ITEM-3
SQL_Param.append(Get_Set.at(3)); // -date
SQL_Param.append(Get_Set.at(2)); // -时间
SQL_Param.append(Get_Set.at(5)); // -编号
SQL_Result.append(Ini_ActiveFile); // -当前型号
SQL_Result.append(Get_Set.at(4)); // -温度
SQL_Result.append(Get_Set.at(6)); // -用户
SQL_Judge.append(Get_Set.at(1)); // -总结果
SQL_Judge.append(Get_Set.at(0)); // -工位
SQL_Judge.append(QString::number(Judge.size())); // -总测试项目
SQL_Item.append(strTest);
SQL_Param.append(strParam);
SQL_Result.append(Result);
SQL_Judge.append(Judge);
QString QStringList_OK, QStringList_No_OK;
QStringList_OK.clear();
QStringList_No_OK.clear();
QString s;
for (i = 0; i < 19; i++) { // 柱状图的测试数据进行清空
Error_Item[i] = 0;
Error_Item_Count[i] = 0;
}
for (i = 0; i < strTest.size(); i++) {
if (strTest.at(i) == (tr("磁旋"))) {
if (Judge[i] == "OK") {
QStringList_OK += tr("磁旋 ");
} else {
QStringList_No_OK += tr("磁旋 ");
}
continue;
} else if (strTest.at(i) == (tr("转向"))) {
if (Judge[i] == "OK") {
QStringList_OK += (tr("转向 "));
} else {
QStringList_No_OK += (tr("转向 "));
}
continue;
} else if (strTest.at(i).contains(tr("PG"))) {
if (Judge[i] == "OK") {
QStringList_OK += tr("PG ");
} else {
QStringList_No_OK += tr("PG ");
}
continue;
} else {
//
}
if (Judge[i] == "OK") {
continue;
}
int k = 0;
for (int t = 0; t < Test_Item.size(); t++) {
if (strTest.at(i).contains(Test_Item.at(t))) {
k = t;
break;
}
}
if (k <= 16) {
Error_Item_Count[k]++;
if (Error_Item_Count[k] == 1) {
QStringList_No_OK += ((Test_Item.at(k))+" ");
Error_Item[k]++;
} else {
//
}
} else {
//
}
}
qDebug() << "Test_Item" << Test_Item;
qDebug() << "QStringList_OK" << QStringList_OK;
qDebug() << "QStringList_No_OK" << QStringList_No_OK;
qDebug() << "Conf_Test" << Conf_Test;
for (i = 0; i < Conf_Test.size(); i++) {
if (QStringList_No_OK.contains(Test_Item.at(Conf_Test.at(i).toInt()))) {
//
} else {
QStringList_OK += (Test_Item.at(Conf_Test.at(i).toInt())+" ");
}
}
/* int id = sql.selectMax("TestDa");
query.prepare(QString(tr("insert into TestDa (id,项目,参数,结果,判定,配置)"\
"values(:id,:项目,:参数,:结果,:判定,:配置)")));
for (i = 0; i < SQL_Item.size(); i++) {
// qDebug() << "SQL_Item.at(i)" << SQL_Item.at(i);
// qDebug() << "SQL_Param.at(i)" << SQL_Param.at(i);
// qDebug() << "SQL_Result.at(i)" << SQL_Result.at(i);
// qDebug() << "SQL_Judge.at(i)" << SQL_Judge.at(i);
// qDebug() << QStringList_OK + "------" + QStringList_No_OK;
id = id + 1;
query.bindValue(tr(":id" ), id);
query.bindValue(tr(":项目"), SQL_Item.at(i));
query.bindValue(tr(":参数"), SQL_Param.at(i));
query.bindValue(tr(":结果"), SQL_Result.at(i));
query.bindValue(tr(":判定"), SQL_Judge.at(i));
if (i > 0) {
query.bindValue(tr(":配置"), tr(""));
} else {
query.bindValue(tr(":配置"), QStringList_OK + QStringList_No_OK + "------" + QStringList_No_OK);
}
query.exec();
}
sql.db.commit(); */
QStringList tmpList;
for (int i=0; i < strTest.size(); i++) {
QString tmpStr;
tmpStr.append(strTest.at(i));
tmpStr.append("@");
tmpStr.append(strParam.at(i));
tmpStr.append("@");
if (i < Result.size())
tmpStr.append(Result.at(i));
else
tmpStr.append("");
tmpStr.append("@");
if (i < Judge.size())
tmpStr.append(Judge.at(i));
else
tmpStr.append("");
tmpList.append(tmpStr);
}
QVariantMap tmpMap;
tmpMap.insert("enum", QMessageBox::Save);
tmpMap.insert("post", Get_Set.at(0)); // 工位
tmpMap.insert("pass", Get_Set.at(1)); // 总判定
tmpMap.insert("time", Get_Set.at(2)); // 时间
tmpMap.insert("date", Get_Set.at(3)); // 日期
tmpMap.insert("temp", Get_Set.at(4)); // 温度
tmpMap.insert("numb", Get_Set.at(5)); // 编码
tmpMap.insert("user", Get_Set.at(6)); // 用户
tmpMap.insert("type", Ini_ActiveFile); // 型号
tmpMap.insert("data", tmpList.join("\n"));
emit sendAppMap(tmpMap);
qDebug() << tmpMap;
tmpMap.clear();
/* for (i = 0; i < QStringList_OK.size(); i++) {
s.clear();
s = QString(tr("%1@%2@OK")).arg(QStringList_OK.at(i)).arg(SQL_Result.at(0));
WConf_WriteSql(s.toUtf8());
}
for (i = 0; i < QStringList_No_OK.size(); i++) {
s.clear();
s = QString(tr("%1@%2@NG")).arg(QStringList_No_OK.at(i)).arg(SQL_Result.at(0));
WConf_WriteSql(s.toUtf8());
}
for (i = 3; i < SQL_Item.size(); i++) {
s.clear();
s.append(sql_Test.at(i-3) + "@" + SQL_Item.at(i) + " " + SQL_Param.at(i) + \
"@" + SQL_Result.at(i) + "@" + SQL_Judge.at(i));
qDebug() << "s" << s;
WConf_WriteSql(s.toUtf8());
}
s = QString(tr("总数@%1@%2")).arg(SQL_Result.at(0)).arg(SQL_Judge.at(0));
WConf_WriteSql(s.toUtf8()); */
if ((Ini_Udp_Enable) || (NetSQL_OpenOk)) { // -
if (SQL_Item.at(1) == "ITEM-2") {
SQL_Result.replace(1, QString(SQL_Result.at(1)).replace(QRegExp("\\°C"), "C"));
if (SQL_Judge.at(1) == QString(tr("左工位"))) {
SQL_Judge.replace(1, "Left");
} else {
SQL_Judge.replace(1, "Right");
}
}
if (SQL_Item.at(2) == "ITEM-3") {
if (SQL_Result.at(2) == QString(tr("管理员"))) {
SQL_Result.replace(2, "Admin");
} else {
SQL_Result.replace(2, "Guest");
}
}
for (i = 0; i < SQL_Item.size(); i++) {
if (SQL_Item.at(i).contains(tr("电阻"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).replace\
(QRegExp(tr("\\电阻")), "DCR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).replace\
(QRegExp("\\Ω"), "ohm"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).replace\
(QRegExp("\\Ω"), ""));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\不平衡度")), "Banlance--"));
} else if (SQL_Item.at(i).contains(tr("反嵌"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\反嵌")), "MAG"));
} else if (SQL_Item.at(i) == (tr("磁旋"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\磁旋")), "DIR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\反转")), "CCWW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\不转")), "NO"));
} else if (SQL_Item.at(i).contains(tr("绝缘"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\绝缘")), "IR"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp("\\Ω"), "ohm"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp("\\Ω"), ""));
} else if (SQL_Item.at(i).contains(tr("交耐"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\交耐")), "ACHV"));
} else if (SQL_Item.at(i).contains(tr("匝间"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\匝间")), "SURGE"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\面积")), " Area"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\差积")), " Diff"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\面积")), " Area"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\差积")), " Diff"));
} else if (SQL_Item.at(i).contains(tr("电感"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\电感")), "IND"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\不平衡度")), "Banlance--"));
} else if (SQL_Item.at(i).contains(tr("电参"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\电参")), "POWER"));
} else if (SQL_Item.at(i) == (tr("转向"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\转向")), "T"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Param.replace(i, QString(SQL_Param.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\正转")), "CW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\反转")), "CCW"));
SQL_Result.replace(i, QString(SQL_Result.at(i)).\
replace(QRegExp(tr("\\不转")), "NO"));
} else if (SQL_Item.at(i).contains(tr("堵转"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\堵转")), "BLOCK"));
} else if (SQL_Item.at(i).contains(tr("低启"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\低启")), "LVS"));
} else if (SQL_Item.at(i).contains(tr("PG"))) {
SQL_Item.replace(i, QString(SQL_Item.at(i)).\
replace(QRegExp(tr("\\PG")), "PG"));
} else {
//
}
}
}
if (Ini_Udp_Enable) { // -UDP上传
QString UDP_Data;
for (i = 0; i < SQL_Item.size(); i++) {
UDP_Data += "(" + SQL_Item.at(i) + ")(" + SQL_Param.at(i) + \
")(" + SQL_Result.at(i)+")(" + SQL_Judge.at(i)+")";
} // qDebug() << "UDP_Data"<<UDP_Data;
WriteMessage((6000), (0x04), UDP_Data.toUtf8());
WriteMessage((6000), (0x15), ("free"));
} else {
//
}
if (NetSQL_OpenOk) { // -网络数据库
QSqlQuery query_net(sql_net.dbtwo);
int id = sql_net.selectMax_net(Ini_Factory);
qDebug() << "id--------------------------" << id;
query_net.prepare(QString(("insert into %1 (id,项目,参数,结果,判定)""values(?,?,?,?,?)"))\
.arg(Ini_Factory)); // ,配置,?
for (i = 0; i < SQL_Item.size(); i++) {
id = id+1;
query_net.bindValue(0, id);
query_net.bindValue(1, SQL_Item.at(i));
query_net.bindValue(2, SQL_Param.at(i));
query_net.bindValue(3, SQL_Result.at(i));
query_net.bindValue(4, SQL_Judge.at(i));
query_net.exec();
sql_net.dbtwo.commit();
}
} else {
//
}
system("sync");
qDebug() << "Finsh";
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 调试数据的保存
******************************************************************************/
void w_Conf::Slot_Save_Debug(QString Name, QString Data)
{
// 保存数据文件进行保存数据(ini)文件进行
QString currentDateTime = QDateTime::currentDateTime().\
toString("yyyy-MM-dd-hh-mm-ss"); // -设置显示格式
QString qname;
QSettings set_Test_File(Test_Debug_path, QSettings::IniFormat);
set_Test_File.setIniCodec("GB2312");
QDir *temp = new QDir;
bool exist = temp->exists(Test_Debug_path);
if (exist) {
qname = QString("%1/%2").arg(currentDateTime).arg(Name);
set_Test_File.setValue(qname, Data);
} else {
system("mkdir /mnt/nandflash/AIP/debug/");
system("touch /mnt/nandflash/AIP/debug/debug.ini");
system("chmod +x /mnt/nandflash/AIP/debug/debug.ini");
qname = QString("%1/%2").arg(currentDateTime).arg(Name);
set_Test_File.setValue(qname, Data);
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: 电阻板测试电阻信息,用于快速设置和测试补偿
******************************************************************************/
QStringList w_Conf::Board_DLR_TestData(can_frame canframe)
{
QStringList Back_QStringList; Back_QStringList.clear();
if ((canframe.data[2] == 1) || (canframe.data[2] == 2)) {
// -档位(1,2)-"mΩ"
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])* \
(qPow(10, -(6-canframe.data[2])))*1000)); //
Back_QStringList.append("mΩ");
} else if ((canframe.data[2] == 3) || (canframe.data[2] == 4) || (canframe.data[2] == 5)) {
// -档位(3,4,5)-"Ω"
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, -(6-canframe.data[2]))))); //
Back_QStringList.append("Ω");
} else if ((canframe.data[2] == 6) || (canframe.data[2] == 7) || (canframe.data[2] == 8)) {
// -档位(6,7,8)-"KΩ" 其中(7,8)暂时未用到
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, (canframe.data[2]-6)))/1000)); //
Back_QStringList.append("KΩ");
}
Back_QStringList.append(QString::number(canframe.data[1]));
if (canframe.data[2] < 6) {
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, -(6-canframe.data[2])))));
} else {
Back_QStringList.append(QString::number((canframe.data[3]*256+canframe.data[4])*\
(qPow(10, (canframe.data[2]-6)))));
}
Back_QStringList.append(QString::number(canframe.data[2]));
return Back_QStringList;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: can信息传递到配置页面
******************************************************************************/
void w_Conf::SlOT_can_to_conf(can_frame frame, QStringList Data, int flag)
{
QStringList DLR_Can_Data;
QStringList PWR_Conf_Data;
switch (flag) {
case 1:
WIMP->Pub_Conf_Get_Result(frame, 1);
if ((frame.data[6] == 0) && (!Quick_Set)) { // -采样失败, 快速设置
Pri_Conf_WMessage(tr("采集失败,电机存在击穿的状况\n建议降低电压进行采集"));
} else {
WriteMessage(6000, 0x92, QString::number(frame.data[1]*100+frame.data[3]).toUtf8());
}
break;
case 2:
//
break;
case 3:
if (!Quick_Set) {
return;
}
if (frame.data[3] != 0) { // -主参
return;
}
Result_indl.dat[0] = frame.data[4];
Result_indl.dat[1] = frame.data[5];
Result_indl.dat[2] = frame.data[6];
Result_indl.dat[3] = frame.data[7];
WINDL->Pub_Conf_Set_INDL(QString::number(Result_indl.Result), frame.data[1], 7);
break;
case 5:
/* WBLOCK->Pub_Conf_Set_BLOCK(QString::number(frame.data[3]*256 + frame.data[4]), \
frame.data[5]*256 + frame.data[6], 5); */
PWR_Conf_Data.clear();
PWR_Conf_Data.append(QString::number(frame.data[1]*256 + frame.data[2]));
PWR_Conf_Data.append(QString::number(frame.data[3]*256 + frame.data[4]));
PWR_Conf_Data.append(QString::number(frame.data[5]*256 + frame.data[6]));
if (index_c == 7) {
WPWR->Pub_Conf_Set_PWR(PWR_Conf_Data.at(0), 7);
} else if (index_c == 9) {
WBLOCK->Pub_Conf_Set_BLOCK(PWR_Conf_Data.at(0), 7, 7);
} else if (index_c == 10) {
WLVS->Pub_Conf_Set_LVS(PWR_Conf_Data.at(0), 7);
} else {
//
}
break;
case 6:
DLR_Can_Data = Board_DLR_TestData(frame);
if (Quick_Set) { // -快速设置
if (DLR_Can_Data.at(0).toDouble() < (2*qPow(10, (1+frame.data[2]%3)))) {
// -小于 20,200,2000
AutoSet[frame.data[1]] = DLR_Can_Data;
} else {
//
}
} else {
DLR_Compensate_Back(DLR_Can_Data);
}
break;
default:
//
break;
}
Data.clear();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.28
* brief: 日志数据的保存
******************************************************************************/
void w_Conf::Slot_Save_DayRecoord(QString Text = "", QString GetData = "")
{
QString currentDateTime = QDateTime::currentDateTime().toString \
("yyyy-MM-dd---hh-mm-ss"); // -设置显示格式
QSettings set_Test_File(Test_Day_Record_path, QSettings::IniFormat);
set_Test_File.setIniCodec(QTextCodec::codecForName("GB2312"));
QDir *temp = new QDir;
bool exist = temp->exists(Test_Day_Record_path);
if (exist) {
qDebug() << "Day_Record File exist";
} else {
qDebug() << "Day_Record File Not Exist";
system("mkdir /mnt/nandflash/AIP/dayrecord/");
system("touch /mnt/nandflash/AIP/dayrecord/dayrecord.ini");
system("chmod +x /mnt/nandflash/AIP/dayrecord/dayrecord.ini");
}
QString keyname;
keyname = QString("%1/%2").arg(Text).arg(currentDateTime);
set_Test_File.setValue(keyname, GetData);
QString strstr;
strstr = GetData.replace(" ", "");
// for (int i=0;i<strstr.size()/10;i++) {
// qDebug() << strstr.mid(i*10, 10);
// }
// qDebug() << strstr.size()<<strstr;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.8.16
* brief: 勾选是否进行测试
******************************************************************************/
void w_Conf::Item_Chose_Box_stateChanged(int checked)
{
qDebug() << "*********************** ui->test->currentRow()" << ui->test->currentRow();
if (Item_Chose_Box->isHidden()) {
return;
}
if (checked) {
qDebug() << "green";
ui->test->item(ui->test->currentRow(), 0)->setTextColor(QColor("green"));
} else {
qDebug() << "red";
ui->test->item(ui->test->currentRow(), 0)->setTextColor(QColor("red"));
}
}
/******************************************************************************
* version: 1.0
* author: link
* date: 2015.12.30
* brief: 电机类型切换
******************************************************************************/
int w_Conf::on_MotorType_currentIndexChanged(int index)
{
if ((model_Type.size() == 0) || (index < 0)) {
return 0;
}
int i = 0;
QString str;
ui->Label_Picture->clear();
QPixmap *pixmap;
pixmap = new QPixmap(QString("/mnt/nandflash/AIP/Model/%1.jpg").arg \
(ui->MotorType->currentText()));
ui->Label_Picture->setPixmap(*pixmap);
QSettings settings(data_path, QSettings::IniFormat);
Ini.Color = settings.value(QString("%1/Color").arg \
(ui->MotorType->currentText())).toString();
for (i = 0; i < Ini_Proj.size(); i++) { // -对端点进行锁定
switch (Ini_Proj.at(i).toInt()) {
case 1: // -电阻
Ini.DLR = settings.value(QString("%1/DLR").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 2: // -反嵌
Ini.MAG = settings.value(QString("%1/MAG").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 3: // -绝缘
//
break;
case 4: // -交耐
//
break;
case 5: // -直耐
if (WDCW != NULL) {
WDCW->Slot_DCW_Setpoint("12");
}
break;
case 6: // -匝间
Ini.IMP = settings.value(QString("%1/IMP").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 7: // -功率
//
break;
case 8: // -电感
Ini.IINDL = settings.value(QString("%1/INDL").arg \
(ui->MotorType->currentText()), "12").toString();
break;
case 9: // -堵转
//
break;
case 10: // -低启
//
break;
case 11: // -霍尔
//
break;
case 12: // -负载
//
break;
case 13: // -空载
//
break;
case 14: // -反电动势
//
break;
}
}
if (ui->MotorType->currentText() == "None") { // -(None)型号时按键全部使能
Ini.Color = "12345678"; // -设置初始值
} else {
//
}
CONF.replace(13, ui->MotorType->currentText());
qColor_BtnList.clear();
colorIdList.clear();
colorIdList_C.clear();
Singal_Conf_to_Main(QStringList(""), ui->MotorType->currentText(), 5, 5);
for (i = 0; i < 8; i++) { // -初始化下拉列表
qColor_BtnList.append(new QToolButton(this));
ui->colrLayout->addWidget(qColor_BtnList[i], i/2, i%2);
btnGroup_Color->addButton(qColor_BtnList[i], i);
qColor_BtnList[i]->setEnabled(true);
colorIdList.append(CONF[i]);
colorIdList_C.append(CONF[i]);
if (Ini.Color.indexOf(QString::number(i+1)) >= 0) {
if (colorIdList[i] == "#000000") {
str = QString("height:90px;width:95px;color: #191919;"\
"border:none;background-color:%1;color:white").arg\
(colorIdList[i]);
} else {
str = QString("height:90px;width:95px;"\
"color: #191919;border:none;background-color:%1").arg\
(colorIdList[i]);
}
} else {
qColor_BtnList[i]->setDisabled(true);
colorIdList_C.replace(i, "#191919");
str = QString("height:90px;width:95px;color: #191919;"\
"border:none;background-color:%1").arg \
(colorIdList_C[i]);
}
qColor_BtnList[i]->setStyleSheet(str);
qColor_BtnList[i]->setText(QString::number(i+1));
}
return true;
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2016.7.19
* brief: Main传递数据到配置页面
******************************************************************************/
void w_Conf::Pub_main_to_conf(QStringList list, QString str, int value, int flag)
{
int Success = 0;
int i;
switch (flag) {
case 1:
Usart_GetFcous();
break;
case 2:
Usart_Button(value);
break;
case 3:
Ini_System = list;
Conf_User = list[5].toInt();
Save_SystemConf_Data(value);
break;
case 4:
Set_Color(str);
break;
case 5: // 用于系统初始化
thread_sql = new QThread(this);
sql_Client.moveToThread(thread_sql);
connect(thread_sql, SIGNAL(started()), &sql_Client, SLOT(DeviceOpen()));
connect(thread_sql, SIGNAL(finished()), &sql_Client, SLOT(DeviceQuit()));
connect(this, SIGNAL(WConf_WriteSql(QByteArray)), &sql_Client, SLOT(Write(QByteArray)));
thread_sql->start();
Sync_Conf();
break;
case 7:
SlOT_Button_Function_Judge(Qt::Key_A);
break;
case 10:
if (value == 1) {
ui->fileEdit1->setText(str);
on_fileBtnAdd_clicked();
} else if (value == 2) {
on_fileBtnDel_clicked();
} else if (value == 3) {
emit WriteMessage(6000, 0x67, QString(currentFile.join(" ")).toUtf8());
} else if (value == 5) {
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(i, 0)->text() == str) { // 设置背景
on_fileTab_cellClicked(i, 0);
}
}
} else {
//
}
break;
case 11:
Conf_Set_User(value);
break;
case 12:
lable_Zero->hide();
break;
case 13:
if (value == 1) {
PC_CONF_Data();
} else if (value == 2) {
PC_SYS_Data();
} else if (value == 3) {
PC_Item_DCR_Data();
} else if (value == 4) {
PC_Item_IR_Data();
} else if (value == 5) {
PC_Item_ACW_Data();
} else if (value == 6) {
PC_Item_IMP_Data();
} else if (value == 7) {
PC_Item_IND_Data();
} else if (value == 11) {
PC_Item_PGHALL_Data();
} else if (value == 12) {
PC_Item_LOAD_Data();
} else if (value == 13) {
PC_Item_NOLOAD_Data();
} else if (value == 14) {
PC_Item_BEMF_Data();
} else if (value == 15) {
PC_Item_MAG_Data();
} else {
//
}
break;
case 15:
qDebug()<<"2017-12-27 Pub_main_to_conf index_c"<<index_c;
if(index_c==7) {
WPWR->Pub_Conf_Set_PWR(list.at(0),7);
}
else if(index_c==9) {
WBLOCK->Pub_Conf_Set_BLOCK(list.at(0),7,7);
}
else if(index_c==10) {
WLVS->Pub_Conf_Set_LVS(list.at(0),7);
}
else {
}
break;
case 16:
if (index_c == 7) {
if (PWR_Test_Usart) {
PWR_Test_Usart = false;
} else {
WPWR->Pub_Conf_Set_PWR(QString(""), 8);
break;
}
if (value == 2) {
Pri_Conf_WMessage("串口不在调试模式,或者串口出现问题");
} else {
Pri_Conf_WMessage("串口 Ok");
}
} else if (index_c == 9) {
WBLOCK->Pub_Conf_Set_BLOCK("", 8, 8);
} else if (index_c == 10) {
WLVS->Pub_Conf_Set_LVS("", 8);
} else {
//
}
break;
case 17:
if (Ini_Set_ImpVolt == QString(tr("noback"))) {
WIMP->Pub_Conf_Set_IMP("", 12);
}
break;
case 18:
for (i = 0; i < currentFile.size(); i++) {
if (ui->fileTab->item(i, 0)->text() == str) { // 设置背景
on_fileTab_cellClicked(i, 0);
}
}
qApp->processEvents(); // 立即显示生效
break;
case 19:
if (WMAG != NULL) {
WMAG->Pub_Conf_Set_MAG(QString::number(value), 10);
} else {
//
}
if (WIMP != NULL) {
WIMP->Pub_Conf_Set_IMP(QString::number(value), 13);
} else {
//
}
break;
case 20:
if (IRACW_Compensate == TestIW_IR) {
if (value == 0) {
return;
}
Success = WIR->IR_Compensate(str.toDouble());
if (Success == 0) {
return;
} else if (Success == 1) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else if (Success == 2) {
Pri_Conf_WMessage(tr(" 补偿错误 "));
} else {
//
}
} else if (IRACW_Compensate == TestIW_ACW) {
if (value == 0) {
return;
}
Success = WACW->ACW_Compensate(str.toDouble());
if (Success == 0) {
return;
} else if (Success == 1) {
ui->Key_E->setStyleSheet("background:#00FF00;color:rgb(0, 0, 0);");
ui->Key_E->setText(tr("已补偿"));
} else if (Success == 2) {
Pri_Conf_WMessage(tr(" 补偿错误 "));
} else {
//
}
} else {
//
}
break;
default:
break;
}
}
void w_Conf::Pub_QbyteArray_conf(QByteArray dat) {
int model_position = 0;
int i = 0;
int j = 0;
dat = dat.remove(0, 5);
QDomDocument docs;
QStringList temp;
docs.setContent(dat);
if (!(docs.elementsByTagName("DCR").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("DCR").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WDLR->DLR_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wire_comp2"))) {
RES = WDLR->Copy_DLR_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("MAG").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("MAG").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WMAG->MAG_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
OPP = WMAG->Copy_MAG_List;
SlOT_Button_Function_Judge(Qt::Key_B);
}
}
} else if (!(docs.elementsByTagName("IR").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IR").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WIR->IR_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt"))) {
INS = WIR->Copy_IR_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("ACW").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("ACW").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WACW->ACW_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt"))) {
ACV = WACW->Copy_ACW_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("IMP").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IMP").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
// qDebug() << "temp"<<temp<<"node.nodeName()"<<node.nodeName();
WIMP->IMP_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
ITT = WIMP->Copy_IMP_List;
SlOT_Button_Function_Judge(Qt::Key_B);
}
}
} else if (!(docs.elementsByTagName("IND").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("IND").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WINDL->INDL_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wire_comp2"))) {
INDL = WINDL->Copy_INDL_List;
SlOT_Button_Function_Judge(Qt::Key_B);
// SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("HALL").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("HALL").at(0).childNodes();
qDebug() << "list.size()" << list.size();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
WPG->BLDCPG_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("wave"))) {
BLDCPG = WPG->Copy_BLDCPG_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("LOAD").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("LOAD").at(0).childNodes();
qDebug() << "list.size()" << list.size();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
WLOAD->LOAD_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("vsp_volt"))) {
LOAD = WLOAD->Copy_LOAD_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("NOLOAD").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("NOLOAD").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WNoLoad->NOLOAD_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("vsp_volt"))) {
NOLOAD = WNoLoad->Copy_NOLOAD_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("BEMF").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("BEMF").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
WBEMF->BEMF_NetData(temp, node.nodeName());
if (node.nodeName() == QString(tr("volt_vcc"))) {
BEMF = WBEMF->Copy_BEMF_List;
SlOT_Button_Function_Judge(Qt::Key_B);
SlOT_Button_Conf_Judge(Qt::Key_0);
}
}
} else if (!(docs.elementsByTagName("Conf").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("Conf").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
if (node.nodeName() == QString(tr("color"))) {
for (j = 0; j < 8; j++) {
iColorBtn = i;
Set_Color(temp.at(i));
}
}
if (node.nodeName() == QString(tr("type"))) {
model_position = model_Type.indexOf(temp.at(0));
ui->MotorType->setCurrentIndex(model_position);
Save_ConfData();
}
}
} else if (!(docs.elementsByTagName("Sys").isEmpty())) {
QDomNodeList list = docs.elementsByTagName("Sys").at(0).childNodes();
for (i = 0; i < list.size(); i++) {
QDomNode node = list.item(i);
QDomElement dom = node.toElement();
temp = dom.text().split(",");
qDebug() << "Indl temp" << temp << node.nodeName();
if (node.nodeName() == QString(tr("Test_Item"))) {
QSettings set_Test_File(Test_File_path, QSettings::IniFormat);
set_Test_File.setIniCodec("UTF-8");
QString name_list;
name_list = QString("Test_File/%1").arg(Ini_ActiveFile);
set_Test_File.setValue(name_list, temp);
test_Inifile = temp;
ui->test->setRowCount(0);
ui->test->setGeometry(305, 20, 131, 39*14+(ui->test->horizontalHeader()->height()));
ui->test->setRowCount(13);
for (i =0 ; i < 13; i++) {
ui->test->setRowHeight(i, 39);
}
Init_test_TableWidget(); // -初始化测试项目
for (i = 1; i <= Count_Item; i++) { // -设置显示, 锁定端子号
btnGroup_Item->button(i)->hide();
}
btnGroup_Item->button(0)->show();
btnGroup_Item->button(20)->show();
for (i = 1; i < Ini_Proj.size(); i++) {
btnGroup_Item->button(Ini_Proj.at(i).toInt())->show();
}
SlOT_Button_Function_Judge(Qt::Key_B);
// SlOT_Button_Function_Judge(Qt::Key_A);
qApp->processEvents();
}
}
} else {
qDebug() << "Error Data";
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 网络数据库打开,数据库窗口显示
******************************************************************************/
void w_Conf::on_SQL_Task_clicked()
{
if (NetSQL_OpenOk) { // -网络数据库打开
SQL_Widget->show();
} else {
Pri_Conf_WMessage(tr("未连接网络\n下载远程数据库失败"));
}
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库窗口隐藏
******************************************************************************/
void w_Conf::SQL_Widget_autoquit()
{
SQL_Widget->hide();
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库查询任务表-生产线-
******************************************************************************/
void w_Conf::SQL_Produce_Plan_textChanged(const QString &text)
{
int i = 0;
if (SQL_Init) {
return;
}
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo);
QString net_str = QString(tr("Select 生产任务编号 from %2 Where 生产线 = '%1'").arg\
(text).arg(Ini_Task_Table));
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
}
SQL_Init = true;
SQL_Line_Text.at(0)->text().clear(); // -计划数量清空
SQL_Line_Text.at(1)->text().clear(); // -生产部门清空
SQL_Line_Text.at(2)->text().clear(); // -产品型号清空
SQL_Produce_Number->clear();
for (i = 0; i < SQL_Task.size(); i++) {
SQL_Produce_Number->addItem(QWidget::tr("%1").arg(SQL_Task.at(i)));
}
SQL_Init = false;
SQL_Produce_Number_textChanged(SQL_Produce_Number->currentText());
}
/******************************************************************************
* version: 1.0
* author: sl
* date: 2017.6.10
* brief: 数据库查询任务表-生产任务号-
******************************************************************************/
void w_Conf::SQL_Produce_Number_textChanged(const QString &text)
{
if (SQL_Init) {
return;
}
if (SQL_Produce_Plan->currentText() == "") {
return;
}
SQL_Line_Text.at(0)->text().clear(); // -计划数量清空
SQL_Line_Text.at(1)->text().clear(); // -生产部门清空
SQL_Line_Text.at(2)->text().clear(); // -产品型号清空
SQL_Task.clear();
QSqlQuery query_net(sql_net.dbtwo);
QString net_str = QString(tr("Select 计划数量, 生产部门, 产品型号 from %3 Where "\
"生产线 = '%1' and 生产任务编号 ='%2'").arg \
(SQL_Produce_Plan->currentText()).arg(text).arg(Ini_Task_Table));
query_net.exec(net_str);
while (query_net.next()) {
SQL_Task.append(query_net.value(0).toString().trimmed());
SQL_Task.append(query_net.value(1).toString().trimmed());
SQL_Task.append(query_net.value(2).toString().trimmed());
SQL_Line_Text.at(0)->setText(SQL_Task.at(0));
SQL_Line_Text.at(1)->setText(SQL_Task.at(1));
SQL_Line_Text.at(2)->setText(SQL_Task.at(2));
}
}
void w_Conf::PC_Test_Param_Data(QStringList netdata)
{
int i = 0;
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Test_Data_Param");
doc.appendChild(root);
QStringList temp;
for (i=0; i < netdata.size()/2; i++) {
temp.append(netdata.at(i));
}
QDomElement Test_1 = doc.createElement("Test_1"); // Test_1
root.appendChild(Test_1);
text = doc.createTextNode(temp.join(","));
Test_1.appendChild(text);
temp.clear();
for (i=0; i < netdata.size()/2; i++) {
temp.append(netdata.at(netdata.size()/2+i));
}
QDomElement Test_2 = doc.createElement("Test_2");
root.appendChild(Test_2);
text = doc.createTextNode(temp.join(","));
Test_2.appendChild(text);
qDebug() << "doc" << doc.toByteArray();
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
void w_Conf::PC_Item_IR_Data() {
int i = 0;
int j = 0;
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("IR");
doc.appendChild(root);
QStringList ir_param;
QStringList ir_param_common;
ir_param.clear();
ir_param_common.clear();
ir_param << tr("test") << tr("port1") << tr("port2") << tr("volt")\
<< tr("min") << tr("max") << tr("time");
ir_param_common << tr("2") << tr("PE") << tr("ALL");
ir_param_common.append(INS.at(20));
ir_param_common.append(INS.at(23));
ir_param_common.append(INS.at(22));
ir_param_common.append(INS.at(21));
int ir_position[] = {36, 30, 31, 32, \
33, 34, 35, \
};
QStringList temp;
for (j = 0; j < ir_param.size(); j++) {
temp.clear();
for (i = 0; i < 4; i++) {
temp.append(RES.at(10*i+ir_position[j]));
}
temp.append(ir_param_common.at(j));
QDomElement test = doc.createElement(ir_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_3);
}
void w_Conf::PC_Item_ACW_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("ACW");
doc.appendChild(root);
QStringList acw_param;
QStringList acw_param_common;
acw_param.clear();
acw_param_common.clear();
acw_param << tr("test") << tr("port1") << tr("port2") << tr("volt")\
<< tr("min") << tr("max") << tr("time")\
<< tr("freq") << tr("arc");
acw_param_common << tr("2") << tr("PE") << tr("ALL");
acw_param_common.append(ACV.at(20));
acw_param_common.append(ACV.at(23));
acw_param_common.append(ACV.at(24));
acw_param_common.append(ACV.at(21));
acw_param_common.append(ACV.at(1));
acw_param_common.append(ACV.at(0));
int acw_position[] = {40, 30, 31, 32, \
33, 34, 36, \
10, 35};
QStringList temp;
for (int j = 0; j < acw_param.size(); j++) {
temp.clear();
if (j == 7) {
for (int i = 0; i < 4; i++) {
temp.append(ACV.at(acw_position[j]));
}
} else {
for (int i = 0; i < 4; i++) {
temp.append(ACV.at(16*i+acw_position[j]));
}
}
temp.append(acw_param_common.at(j));
QDomElement test = doc.createElement(acw_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_4);
}
void w_Conf::PC_Item_IMP_Data() {
SlOT_Button_Conf_Judge(Qt::Key_6);
}
void w_Conf::PC_Item_IND_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("IND");
doc.appendChild(root);
QStringList ind_param;
ind_param.clear();
ind_param << tr("test") << tr("port1") << tr("port2") << tr("unit")\
<< tr("min") << tr("max") << tr("qmin") << tr("qmax")\
<< tr("std") << tr("mode") << tr("noun");
int ind_position[] = {38, 30, 31, 37, \
32, 33, 34, 35, \
36};
QStringList temp;
for (int j = 0; j < ind_param.size(); j++) {
temp.clear();
if (j == 9) {
temp.append(INDL.at(0)); // 次数
temp.append(INDL.at(2)); // 频率
temp.append(INDL.at(3)); // 频率
temp.append(INDL.at(6)); // 快测慢测
} else if (j == 10) {
temp.append(INDL.at(1)); // 不平衡度
} else {
for (int i=0; i < 8; i++) {
temp.append(INDL.at(20*i+ind_position[j]));
}
}
QDomElement test = doc.createElement(ind_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
qDebug() << "doc.toByteArray()" << doc.toByteArray();
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_8);
}
void w_Conf::PC_Item_PGHALL_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("HALL");
doc.appendChild(root);
QStringList fg_param;
fg_param.clear();
fg_param << tr("volt_low_min") << tr("volt_low_max") << tr("volt_up_min") << tr("volt_up_max")\
<< tr("freq_min") << tr("freq_max") << tr("duty_min") << tr("duty_max")\
<< tr("skewing_min") << tr("skewing_max")\
<< tr("count") << tr("vcc_volt") << tr("time");
int fg_position[] = {50, 65, 51, 66, \
52, 67, 53, 68, \
54, 69, \
1, 0, 2};
QStringList temp;
for (int j = 0; j < fg_param.size(); j++) {
temp.clear();
temp.append(BLDCPG.at(fg_position[j]));
QDomElement test = doc.createElement(fg_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(59);
}
void w_Conf::PC_Item_LOAD_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("LOAD");
doc.appendChild(root);
QStringList load_param;
load_param.clear();
load_param << tr("volt") << tr("curr_min") << tr("curr_max") << tr("pwr_min") << tr("pwr_max")\
<< tr("speed_min") << tr("speed_max") << tr("torque") << tr("vcc_volt")\
<< tr("vsp_volt") << tr("time") << tr("sequence");
int load_position[] = {0, 50, 65, 51, 66, \
52, 67, 4, 1, \
2, 3, 110};
QStringList temp;
for (int j = 0; j < load_param.size(); j++) {
temp.clear();
if (j == 11) {
for (int i = 0; i < 14; i++) {
temp.append(LOAD.at(load_position[j]+i));
}
} else {
temp.append(LOAD.at(load_position[j]));
}
QDomElement test = doc.createElement(load_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(60);
}
void w_Conf::PC_Item_NOLOAD_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("NOLOAD");
doc.appendChild(root);
QStringList noload_param;
noload_param.clear();
noload_param << tr("volt") << tr("curr_min") << tr("curr_max") << tr("pwr_min") \
<< tr("pwr_max")\
<< tr("speed_min") << tr("speed_max") << tr("vcc_volt")\
<< tr("vsp_volt") << tr("time") << tr("sequence")\
<< tr("turn");
int noload_position[] = {0, 50, 65, 51, 66, \
52, 67, 1, \
2, 3, 110, \
4};
QStringList temp;
for (int j = 0; j < noload_param.size(); j++) {
temp.clear();
if (j == 10) {
for (int i = 0; i < 10; i++) {
temp.append(NOLOAD.at(noload_position[j]+i));
}
} else {
temp.append(NOLOAD.at(noload_position[j]));
}
QDomElement test = doc.createElement(noload_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(61);
}
void w_Conf::PC_Item_BEMF_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("BEMF");
doc.appendChild(root);
QStringList bemf_param;
bemf_param.clear();
bemf_param << tr("hu_volt_min") << tr("hu_volt_max") << tr("hv_volt_min") << tr("hv_volt_max")\
<< tr("hw_volt_min") << tr("hw_volt_max") << tr("speed") << tr("turn")\
<< tr("skewing") << tr("noun");
int bemf_position[] = {50, 65, 51, 66, \
52, 67, 1, 2, \
3, 0};
QStringList temp;
for (int j = 0; j < bemf_param.size(); j++) {
temp.clear();
temp.append(BEMF.at(bemf_position[j]));
QDomElement test = doc.createElement(bemf_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(62);
}
void w_Conf::PC_Item_DCR_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("DCR");
doc.appendChild(root);
QStringList dcr_param;
dcr_param.clear();
dcr_param << tr("test") << tr("port1") << tr("port2") << tr("wire")\
<< tr("unit") << tr("min") << tr("max") << tr("std")\
<< tr("std_temp") << tr("wire_comp1") << tr("wire_comp2")\
<< tr("temp_comp") << ("noun");
int dcr_position[] = {7, 0, 1, 5, \
9, 2, 3, 4, \
0, 6, 10, \
33, 7};
QStringList temp;
for (int j = 0; j < dcr_param.size(); j++) {
temp.clear();
if ((j == 8) || (j == 11) || (j == 12)) {
temp.append(RES.at(dcr_position[j]));
} else {
for (int i=0; i < 8; i++) {
temp.append(RES.at(25+16*i+dcr_position[j]));
}
}
QDomElement test = doc.createElement(dcr_param.at(j));
root.appendChild(test);
text = doc.createTextNode(temp.join(","));
test.appendChild(text);
}
emit WriteMessage(6000, 0x60, doc.toByteArray());
SlOT_Button_Conf_Judge(Qt::Key_1);
}
void w_Conf::PC_Item_MAG_Data() {
qDebug() << "Mag Join";
SlOT_Button_Conf_Judge(Qt::Key_2);
}
void w_Conf::PC_SYS_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Sys");
doc.appendChild(root);
QStringList temp;
for (int i=0; i < test_Inifile.size(); i++) {
temp.append(test_Inifile.at(i));
}
QDomElement Test_Item = doc.createElement("Test_Item");
root.appendChild(Test_Item);
text = doc.createTextNode(temp.join(","));
Test_Item.appendChild(text);
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
void w_Conf::PC_CONF_Data() {
QDomText text;
QDomDocument doc;
QDomElement root = doc.createElement("Conf");
doc.appendChild(root);
QStringList temp;
for (int i=0; i < colorIdList_C.size(); i++) {
temp.append(colorIdList_C.at(i));
}
QDomElement color = doc.createElement("color");
root.appendChild(color);
text = doc.createTextNode(temp.join(","));
color.appendChild(text);
temp.clear();
temp.append(ui->MotorType->currentText());
QDomElement type = doc.createElement("type");
root.appendChild(type);
text = doc.createTextNode(temp.join(","));
type.appendChild(text);
emit WriteMessage(6000, 0x60, doc.toByteArray());
}
| 36.772231
| 110
| 0.486184
|
Bluce-Song
|
0c429aff8c66779da4ad1f05c1768aa976621b05
| 12,024
|
hpp
|
C++
|
include/ShaderWriter/VecTypes/Swizzle.hpp
|
jarrodmky/ShaderWriter
|
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
|
[
"MIT"
] | 148
|
2018-10-11T16:51:37.000Z
|
2022-03-26T13:55:08.000Z
|
include/ShaderWriter/VecTypes/Swizzle.hpp
|
jarrodmky/ShaderWriter
|
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
|
[
"MIT"
] | 30
|
2019-11-30T11:43:07.000Z
|
2022-01-25T21:09:47.000Z
|
include/ShaderWriter/VecTypes/Swizzle.hpp
|
jarrodmky/ShaderWriter
|
ee9ce00a003bf544f8c8f23b5c07739e21cb3754
|
[
"MIT"
] | 8
|
2020-04-17T13:18:30.000Z
|
2021-11-20T06:24:44.000Z
|
/*
See LICENSE file in root folder
*/
#ifndef ___SDW_Swizzle_H___
#define ___SDW_Swizzle_H___
#include "ShaderWriter/BaseTypes/Bool.hpp"
#define Writer_UseSwizzle 0
#if defined( RGB )
# undef RGB
#endif
namespace sdw
{
#if Writer_UseSwizzle
template< typename Input, typename Output >
struct Swizzle
: public Output
{
inline Swizzle( std::string const & p_name
, Input * input );
inline Swizzle & operator=( Swizzle const & rhs );
template< typename T > inline Swizzle & operator=( T const & rhs );
inline operator Output()const;
template< typename UInput, typename UOutput > inline Swizzle & operator+=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator-=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator*=( Swizzle< UInput, UOutput > const & rhs );
template< typename UInput, typename UOutput > inline Swizzle & operator/=( Swizzle< UInput, UOutput > const & rhs );
inline Swizzle & operator+=( float rhs );
inline Swizzle & operator-=( float rhs );
inline Swizzle & operator*=( float rhs );
inline Swizzle & operator/=( float rhs );
inline Swizzle & operator+=( int rhs );
inline Swizzle & operator-=( int rhs );
inline Swizzle & operator*=( int rhs );
inline Swizzle & operator/=( int rhs );
Input * m_input;
};
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Output > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Float > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator+( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator-( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator*( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename TInput, typename UInput, typename Output > inline Output operator/( Swizzle< TInput, Output > const & lhs, Swizzle< UInput, Int > const & rhs );
template< typename Input, typename Output > inline Output operator+( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator-( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator*( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator/( Swizzle< Input, Output > const & lhs, float rhs );
template< typename Input, typename Output > inline Output operator+( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator-( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator*( Swizzle< Input, Output > const & lhs, int rhs );
template< typename Input, typename Output > inline Output operator/( Swizzle< Input, Output > const & lhs, int rhs );
# define Writer_Swizzle( Input, Output, Name )\
Swizzle< Input, Output > Name;
# define Writer_FirstSwizzle( Input, Output, Name )\
Swizzle< Input, Output > Name = Swizzle< Input, Output >( castor::string::stringCast< char >( #Name ), this )
# define Writer_LastSwizzle( Input, Output, Name )\
Swizzle< Input, Output > Name = Swizzle< Input, Output >( castor::string::stringCast< char >( #Name ), this )
# define Swizzle_X x
# define Swizzle_Y y
# define Swizzle_Z z
# define Swizzle_W w
# define Swizzle_R r
# define Swizzle_G g
# define Swizzle_B b
# define Swizzle_A a
# define Swizzle_XY xy
# define Swizzle_XZ xz
# define Swizzle_XW xw
# define Swizzle_YX yx
# define Swizzle_YZ yz
# define Swizzle_YW yw
# define Swizzle_ZX zx
# define Swizzle_ZY zy
# define Swizzle_ZW zw
# define Swizzle_WX wx
# define Swizzle_WY wy
# define Swizzle_WZ wz
# define Swizzle_RG rg
# define Swizzle_RB rb
# define Swizzle_RA ra
# define Swizzle_GR gr
# define Swizzle_GB gb
# define Swizzle_GA ga
# define Swizzle_BR br
# define Swizzle_BG bg
# define Swizzle_BA ba
# define Swizzle_AR ar
# define Swizzle_AG ag
# define Swizzle_AB ab
# define Swizzle_XYZ xyz
# define Swizzle_XYW xyw
# define Swizzle_XZY xzy
# define Swizzle_XZW xzw
# define Swizzle_XWY xwy
# define Swizzle_XWZ xwz
# define Swizzle_YXZ yxz
# define Swizzle_YXW yxw
# define Swizzle_YZX yzx
# define Swizzle_YZW yzw
# define Swizzle_YWX ywx
# define Swizzle_YWZ ywz
# define Swizzle_ZXY zxy
# define Swizzle_ZXW zxw
# define Swizzle_ZYX zyx
# define Swizzle_ZYW zyw
# define Swizzle_ZWX zwx
# define Swizzle_ZWY zwy
# define Swizzle_WXY wxy
# define Swizzle_WXZ wxz
# define Swizzle_WYX wyx
# define Swizzle_WYZ wyz
# define Swizzle_WZX wzx
# define Swizzle_WZY wzy
# define Swizzle_RGB rgb
# define Swizzle_RGA rga
# define Swizzle_RBG rbg
# define Swizzle_RBA rba
# define Swizzle_RAG rag
# define Swizzle_RAB rab
# define Swizzle_GRB grb
# define Swizzle_GRA gra
# define Swizzle_GBR gbr
# define Swizzle_GBA gba
# define Swizzle_GAR gar
# define Swizzle_GAB gab
# define Swizzle_BRG brg
# define Swizzle_BRA bra
# define Swizzle_BGR bgr
# define Swizzle_BGA bga
# define Swizzle_BAR bar
# define Swizzle_BAG bag
# define Swizzle_ARG arg
# define Swizzle_ARB arb
# define Swizzle_AGR agr
# define Swizzle_AGB agb
# define Swizzle_ABR abr
# define Swizzle_ABG abg
# define Swizzle_XYZW xyzw
# define Swizzle_XYWW xyww
# define Swizzle_XYWZ xywz
# define Swizzle_XZYW xzyw
# define Swizzle_XZWY xzwy
# define Swizzle_XWYZ xwyz
# define Swizzle_XWZY xwzy
# define Swizzle_YXZW yxzw
# define Swizzle_YXWZ yxwz
# define Swizzle_YZXW yzxw
# define Swizzle_YZWX yzwx
# define Swizzle_YWXZ ywxz
# define Swizzle_YWZX ywzx
# define Swizzle_ZXYW zxyw
# define Swizzle_ZXWY zxwy
# define Swizzle_ZYXW zyxw
# define Swizzle_ZYWX zywx
# define Swizzle_ZWXY zwxy
# define Swizzle_ZWYX zwyx
# define Swizzle_WXYZ wxyz
# define Swizzle_WXZY wxzy
# define Swizzle_WYXZ wyxz
# define Swizzle_WYZX wyzx
# define Swizzle_WZXY wzxy
# define Swizzle_WZYX wzyx
# define Swizzle_RGBA rgba
# define Swizzle_RGAB rgab
# define Swizzle_RBGA rbga
# define Swizzle_RBAG rbag
# define Swizzle_RAGB ragb
# define Swizzle_RABG rabg
# define Swizzle_GRBA grba
# define Swizzle_GRAB grab
# define Swizzle_GBRA gbra
# define Swizzle_GBAR gbar
# define Swizzle_GARB garb
# define Swizzle_GABR gabr
# define Swizzle_BRGA brga
# define Swizzle_BRAG brag
# define Swizzle_BGRA bgra
# define Swizzle_BGAR bgar
# define Swizzle_BARG barg
# define Swizzle_BAGR bagr
# define Swizzle_ARGB argb
# define Swizzle_ARBG arbg
# define Swizzle_AGRB agrb
# define Swizzle_AGBR agbr
# define Swizzle_ABRG abrg
# define Swizzle_ABGR abgr
#else
# define Writer_Swizzle( Input, Output, Name )\
inline Output Name()const\
{\
auto & shader = findWriterMandat( *this );\
return Output{ shader\
, sdw::makeSwizzle( makeExpr( shader, this->getExpr() )\
, expr::SwizzleKind::e##Name )\
, this->isEnabled() };\
}
# define Writer_FirstSwizzle( Input, Output, Name )\
Writer_Swizzle( Input, Output, Name )
# define Writer_LastSwizzle( Input, Output, Name )\
Writer_Swizzle( Input, Output, Name )
# define Swizzle_X x()
# define Swizzle_Y y()
# define Swizzle_Z z()
# define Swizzle_W w()
# define Swizzle_R r()
# define Swizzle_G g()
# define Swizzle_B b()
# define Swizzle_A a()
# define Swizzle_XY xy()
# define Swizzle_XZ xz()
# define Swizzle_XW xw()
# define Swizzle_YX yx()
# define Swizzle_YZ yz()
# define Swizzle_YW yw()
# define Swizzle_ZX zx()
# define Swizzle_ZY zy()
# define Swizzle_ZW zw()
# define Swizzle_WX wx()
# define Swizzle_WY wy()
# define Swizzle_WZ wz()
# define Swizzle_RG rg()
# define Swizzle_RB rb()
# define Swizzle_RA ra()
# define Swizzle_GR gr()
# define Swizzle_GB gb()
# define Swizzle_GA ga()
# define Swizzle_BR br()
# define Swizzle_BG bg()
# define Swizzle_BA ba()
# define Swizzle_AR ar()
# define Swizzle_AG ag()
# define Swizzle_AB ab()
# define Swizzle_XYZ xyz()
# define Swizzle_XYW xyw()
# define Swizzle_XZY xzy()
# define Swizzle_XZW xzw()
# define Swizzle_XWY xwy()
# define Swizzle_XWZ xwz()
# define Swizzle_YXZ yxz()
# define Swizzle_YXW yxw()
# define Swizzle_YZX yzx()
# define Swizzle_YZW yzw()
# define Swizzle_YWX ywx()
# define Swizzle_YWZ ywz()
# define Swizzle_ZXY zxy()
# define Swizzle_ZXW zxw()
# define Swizzle_ZYX zyx()
# define Swizzle_ZYW zyw()
# define Swizzle_ZWX zwx()
# define Swizzle_ZWY zwy()
# define Swizzle_WXY wxy()
# define Swizzle_WXZ wxz()
# define Swizzle_WYX wyx()
# define Swizzle_WYZ wyz()
# define Swizzle_WZX wzx()
# define Swizzle_WZY wzy()
# define Swizzle_RGB rgb()
# define Swizzle_RGA rga()
# define Swizzle_RBG rbg()
# define Swizzle_RBA rba()
# define Swizzle_RAG rag()
# define Swizzle_RAB rab()
# define Swizzle_GRB grb()
# define Swizzle_GRA gra()
# define Swizzle_GBR gbr()
# define Swizzle_GBA gba()
# define Swizzle_GAR gar()
# define Swizzle_GAB gab()
# define Swizzle_BRG brg()
# define Swizzle_BRA bra()
# define Swizzle_BGR bgr()
# define Swizzle_BGA bga()
# define Swizzle_BAR bar()
# define Swizzle_BAG bag()
# define Swizzle_ARG arg()
# define Swizzle_ARB arb()
# define Swizzle_AGR agr()
# define Swizzle_AGB agb()
# define Swizzle_ABR abr()
# define Swizzle_ABG abg()
# define Swizzle_XYZW xyzw()
# define Swizzle_XYWW xyww()
# define Swizzle_XYWZ xywz()
# define Swizzle_XZYW xzyw()
# define Swizzle_XZWY xzwy()
# define Swizzle_XWYZ xwyz()
# define Swizzle_XWZY xwzy()
# define Swizzle_YXZW yxzw()
# define Swizzle_YXWZ yxwz()
# define Swizzle_YZXW yzxw()
# define Swizzle_YZWX yzwx()
# define Swizzle_YWXZ ywxz()
# define Swizzle_YWZX ywzx()
# define Swizzle_ZXYW zxyw()
# define Swizzle_ZXWY zxwy()
# define Swizzle_ZYXW zyxw()
# define Swizzle_ZYWX zywx()
# define Swizzle_ZWXY zwxy()
# define Swizzle_ZWYX zwyx()
# define Swizzle_WXYZ wxyz()
# define Swizzle_WXZY wxzy()
# define Swizzle_WYXZ wyxz()
# define Swizzle_WYZX wyzx()
# define Swizzle_WZXY wzxy()
# define Swizzle_WZYX wzyx()
# define Swizzle_RGBA rgba()
# define Swizzle_RGAB rgab()
# define Swizzle_RBGA rbga()
# define Swizzle_RBAG rbag()
# define Swizzle_RAGB ragb()
# define Swizzle_RABG rabg()
# define Swizzle_GRBA grba()
# define Swizzle_GRAB grab()
# define Swizzle_GBRA gbra()
# define Swizzle_GBAR gbar()
# define Swizzle_GARB garb()
# define Swizzle_GABR gabr()
# define Swizzle_BRGA brga()
# define Swizzle_BRAG brag()
# define Swizzle_BGRA bgra()
# define Swizzle_BGAR bgar()
# define Swizzle_BARG barg()
# define Swizzle_BAGR bagr()
# define Swizzle_ARGB argb()
# define Swizzle_ARBG arbg()
# define Swizzle_AGRB agrb()
# define Swizzle_AGBR agbr()
# define Swizzle_ABRG abrg()
# define Swizzle_ABGR abgr()
#endif
}
#include "Swizzle.inl"
#endif
| 33.586592
| 167
| 0.747006
|
jarrodmky
|
0c48d3843cc045a691df4fb5fa11b824127a990c
| 2,155
|
cpp
|
C++
|
ares/gba/system/system.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 153
|
2020-07-25T17:55:29.000Z
|
2021-10-01T23:45:01.000Z
|
ares/gba/system/system.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 245
|
2021-10-08T09:14:46.000Z
|
2022-03-31T08:53:13.000Z
|
ares/gba/system/system.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 44
|
2020-07-25T08:51:55.000Z
|
2021-09-25T16:09:01.000Z
|
#include <gba/gba.hpp>
namespace ares::GameBoyAdvance {
auto enumerate() -> vector<string> {
return {
"[Nintendo] Game Boy Advance",
"[Nintendo] Game Boy Player",
};
}
auto load(Node::System& node, string name) -> bool {
if(!enumerate().find(name)) return false;
return system.load(node, name);
}
Scheduler scheduler;
BIOS bios;
System system;
#include "bios.cpp"
#include "controls.cpp"
#include "serialization.cpp"
auto System::game() -> string {
if(cartridge.node) {
return cartridge.title();
}
return "(no cartridge connected)";
}
auto System::run() -> void {
scheduler.enter();
if(GameBoyAdvance::Model::GameBoyPlayer()) player.frame();
}
auto System::load(Node::System& root, string name) -> bool {
if(node) unload();
information = {};
if(name.find("Game Boy Advance")) {
information.name = "Game Boy Advance";
information.model = Model::GameBoyAdvance;
}
if(name.find("Game Boy Player")) {
information.name = "Game Boy Player";
information.model = Model::GameBoyPlayer;
}
node = Node::System::create(information.name);
node->setGame({&System::game, this});
node->setRun({&System::run, this});
node->setPower({&System::power, this});
node->setSave({&System::save, this});
node->setUnload({&System::unload, this});
node->setSerialize({&System::serialize, this});
node->setUnserialize({&System::unserialize, this});
root = node;
if(!node->setPak(pak = platform->pak(node))) return false;
scheduler.reset();
controls.load(node);
bios.load(node);
cpu.load(node);
ppu.load(node);
apu.load(node);
cartridgeSlot.load(node);
return true;
}
auto System::save() -> void {
if(!node) return;
cartridge.save();
}
auto System::unload() -> void {
if(!node) return;
save();
bios.unload();
cpu.unload();
ppu.unload();
apu.unload();
cartridgeSlot.unload();
pak.reset();
node.reset();
}
auto System::power(bool reset) -> void {
for(auto& setting : node->find<Node::Setting::Setting>()) setting->setLatch();
bus.power();
player.power();
cpu.power();
ppu.power();
apu.power();
cartridge.power();
scheduler.power(cpu);
}
}
| 21.336634
| 80
| 0.64826
|
CasualPokePlayer
|
0c4989d25a814a669fb015108e6a2955c27aac80
| 1,759
|
cc
|
C++
|
squid/squid3-3.3.8.spaceify/src/tests/testStore.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-01-20T15:25:34.000Z
|
2017-12-20T06:47:42.000Z
|
squid/squid3-3.3.8.spaceify/src/tests/testStore.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-05-15T09:32:55.000Z
|
2016-02-18T13:43:31.000Z
|
squid/squid3-3.3.8.spaceify/src/tests/testStore.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | null | null | null |
#define SQUID_UNIT_TEST 1
#include "squid.h"
#include "testStore.h"
#include "Store.h"
CPPUNIT_TEST_SUITE_REGISTRATION( testStore );
int
TestStore::callback()
{
return 1;
}
StoreEntry*
TestStore::get(const cache_key*)
{
return NULL;
}
void
TestStore::get(String, void (*)(StoreEntry*, void*), void*)
{}
void
TestStore::init()
{}
uint64_t
TestStore::maxSize() const
{
return 3;
}
uint64_t
TestStore::minSize() const
{
return 1;
}
uint64_t
TestStore::currentSize() const
{
return 2;
}
uint64_t
TestStore::currentCount() const
{
return 2;
}
int64_t
TestStore::maxObjectSize() const
{
return 1;
}
void
TestStore::getStats(StoreInfoStats &) const
{
}
void
TestStore::stat(StoreEntry &) const
{
const_cast<TestStore *>(this)->statsCalled = true;
}
StoreSearch *
TestStore::search(String const url, HttpRequest *)
{
return NULL;
}
void
testStore::testSetRoot()
{
StorePointer aStore(new TestStore);
Store::Root(aStore);
CPPUNIT_ASSERT(&Store::Root() == aStore.getRaw());
Store::Root(NULL);
}
void
testStore::testUnsetRoot()
{
StorePointer aStore(new TestStore);
StorePointer aStore2(new TestStore);
Store::Root(aStore);
Store::Root(aStore2);
CPPUNIT_ASSERT(&Store::Root() == aStore2.getRaw());
Store::Root(NULL);
}
void
testStore::testStats()
{
TestStorePointer aStore(new TestStore);
Store::Root(aStore.getRaw());
CPPUNIT_ASSERT(aStore->statsCalled == false);
Store::Stats(NullStoreEntry::getInstance());
CPPUNIT_ASSERT(aStore->statsCalled == true);
Store::Root(NULL);
}
void
testStore::testMaxSize()
{
StorePointer aStore(new TestStore);
Store::Root(aStore.getRaw());
CPPUNIT_ASSERT(aStore->maxSize() == 3);
Store::Root(NULL);
}
| 15.163793
| 59
| 0.682206
|
spaceify
|
0c4ba09acd9004f5019125826d45f4490b9acaba
| 4,657
|
cpp
|
C++
|
sslpod/src/v20190605/model/CreateDomainRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 43
|
2019-08-14T08:14:12.000Z
|
2022-03-30T12:35:09.000Z
|
sslpod/src/v20190605/model/CreateDomainRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 12
|
2019-07-15T10:44:59.000Z
|
2021-11-02T12:35:00.000Z
|
sslpod/src/v20190605/model/CreateDomainRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 28
|
2019-07-12T09:06:22.000Z
|
2022-03-30T08:04:18.000Z
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/sslpod/v20190605/model/CreateDomainRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Sslpod::V20190605::Model;
using namespace std;
CreateDomainRequest::CreateDomainRequest() :
m_serverTypeHasBeenSet(false),
m_domainHasBeenSet(false),
m_portHasBeenSet(false),
m_iPHasBeenSet(false),
m_noticeHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
string CreateDomainRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_serverTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServerType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_serverType, allocator);
}
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_portHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Port";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_port.c_str(), allocator).Move(), allocator);
}
if (m_iPHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IP";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_iP.c_str(), allocator).Move(), allocator);
}
if (m_noticeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Notice";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_notice, allocator);
}
if (m_tagsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Tags";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_tags.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int64_t CreateDomainRequest::GetServerType() const
{
return m_serverType;
}
void CreateDomainRequest::SetServerType(const int64_t& _serverType)
{
m_serverType = _serverType;
m_serverTypeHasBeenSet = true;
}
bool CreateDomainRequest::ServerTypeHasBeenSet() const
{
return m_serverTypeHasBeenSet;
}
string CreateDomainRequest::GetDomain() const
{
return m_domain;
}
void CreateDomainRequest::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool CreateDomainRequest::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
string CreateDomainRequest::GetPort() const
{
return m_port;
}
void CreateDomainRequest::SetPort(const string& _port)
{
m_port = _port;
m_portHasBeenSet = true;
}
bool CreateDomainRequest::PortHasBeenSet() const
{
return m_portHasBeenSet;
}
string CreateDomainRequest::GetIP() const
{
return m_iP;
}
void CreateDomainRequest::SetIP(const string& _iP)
{
m_iP = _iP;
m_iPHasBeenSet = true;
}
bool CreateDomainRequest::IPHasBeenSet() const
{
return m_iPHasBeenSet;
}
bool CreateDomainRequest::GetNotice() const
{
return m_notice;
}
void CreateDomainRequest::SetNotice(const bool& _notice)
{
m_notice = _notice;
m_noticeHasBeenSet = true;
}
bool CreateDomainRequest::NoticeHasBeenSet() const
{
return m_noticeHasBeenSet;
}
string CreateDomainRequest::GetTags() const
{
return m_tags;
}
void CreateDomainRequest::SetTags(const string& _tags)
{
m_tags = _tags;
m_tagsHasBeenSet = true;
}
bool CreateDomainRequest::TagsHasBeenSet() const
{
return m_tagsHasBeenSet;
}
| 23.882051
| 91
| 0.703028
|
suluner
|
0c4e705ba82a61bd92b2df479ae3e571b063c3ac
| 1,079
|
cpp
|
C++
|
client/Classes/Model/Effects/DefenceEffect.cpp
|
plankes-projects/BaseWar
|
693f7d02fa324b917b28be58d33bb77a18d77f26
|
[
"Apache-2.0"
] | 60
|
2015-01-03T07:31:14.000Z
|
2021-12-17T02:39:17.000Z
|
client/Classes/Model/Effects/DefenceEffect.cpp
|
plankes-projects/BaseWar
|
693f7d02fa324b917b28be58d33bb77a18d77f26
|
[
"Apache-2.0"
] | 1
|
2018-08-17T09:59:30.000Z
|
2018-08-17T09:59:30.000Z
|
client/Classes/Model/Effects/DefenceEffect.cpp
|
plankes-projects/BaseWar
|
693f7d02fa324b917b28be58d33bb77a18d77f26
|
[
"Apache-2.0"
] | 27
|
2015-01-22T06:55:10.000Z
|
2021-12-17T02:39:23.000Z
|
/*
* Attack.cpp
*
* Created on: May 18, 2013
* Author: planke
*/
#include "DefenceEffect.h"
#include "../Units/Unit.h"
DefenceEffect::~DefenceEffect() {
}
DefenceEffect::DefenceEffect(float timeInMilliseconds, float increasedHPInPercent, float increasedDefenseInPercent) :
Effect(timeInMilliseconds, NOTICK) {
_increasedHPInPercent = increasedHPInPercent;
_increasedDefenseInPercent = increasedDefenseInPercent;
_isHarmful = false;
_GUID = 4;
_isStackAble = true; //if false, only duration is updated
}
void DefenceEffect::onApply(Unit* owner) {
float grow = _increasedHPInPercent / 2;
owner->increaseSizeBy(grow > 1 ? 1 : grow);
owner->increaseHitpointsBy(_increasedHPInPercent);
owner->increaseArmourEffectBy(_increasedDefenseInPercent);
}
void DefenceEffect::perform(Unit* owner) {
//nothing to do
}
void DefenceEffect::onRemoving(Unit* owner) {
float grow = _increasedHPInPercent / 2;
owner->decreaseSizeBy(grow > 1 ? 1 : grow);
owner->decreaseHitpointsBy(_increasedHPInPercent);
owner->decreaseArmourEffectBy(_increasedDefenseInPercent);
}
| 26.317073
| 117
| 0.762743
|
plankes-projects
|
31b1283cb103db9834c630868c49bcf8acde0ec2
| 2,109
|
cc
|
C++
|
src/logtrace.cc
|
Gear2D/gear2d
|
7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63
|
[
"MIT"
] | 4
|
2015-05-15T06:30:23.000Z
|
2018-06-17T22:34:07.000Z
|
src/logtrace.cc
|
Gear2D/gear2d
|
7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63
|
[
"MIT"
] | null | null | null |
src/logtrace.cc
|
Gear2D/gear2d
|
7a9c9c479cbd8f15e5ce9050a43b041d60e8ab63
|
[
"MIT"
] | null | null | null |
#include "logtrace.h"
#ifdef ANDROID
void logtrace::initandroidlog() {
static bool initialized = false;
if (!initialized) {
std::cout.rdbuf(new androidbuf);
initialized = true;
}
}
#endif
/* logtrace static calls */
std::ostream *& logtrace::logstream() {
static std::ostream * stream = &std::cout;
return stream;
}
int & logtrace::indent() {
static int i = 0;
return i;
}
logtrace::verbosity & logtrace::globalverb() {
static logtrace::verbosity verb = logtrace::error;
return verb;
}
logtrace::verbosity & logtrace::globalverb(const verbosity & newverb) {
globalverb() = newverb;
return globalverb();
}
std::set<std::string> & logtrace::filter() {
static std::set<std::string> filters;
return filters;
}
std::set<std::string> & logtrace::ignore() {
static std::set<std::string> ignores;
return ignores;
}
void logtrace::open(const std::string & filename) {
std::ofstream * filestream = new std::ofstream(filename, std::ofstream::out | std::ofstream::trunc);
if (logstream() != &std::cout) { logstream()->flush(); delete logstream(); }
logstream() = filestream;
}
logtrace::logtrace(const std::string & module, logtrace::verbosity level) : logtrace(module, "", level) { }
logtrace::logtrace(logtrace::verbosity level) : logtrace("", "", level) { }
logtrace::logtrace(const std::string & module, const std::string & trace, logtrace::verbosity level)
: trace(trace)
, tracemodule(module)
, level(level)
, traced(false)
, done(true) {
if (!check()) return;
mark();
}
bool logtrace::check() {
if (globalverb() < level) return false; /* check if verbosity level allows */
/* check to see if there's a filter and if this is string is in there */
if (!filter().empty() && filter().find(tracemodule) == filter().end()) return false;
/* check to see if module is on the ignore list */
if (ignore().find(tracemodule) != ignore().end())
return false;
#ifdef ANDROID
initandroidlog();
#endif
return true;
}
| 26.037037
| 108
| 0.62826
|
Gear2D
|
31bc1a58d99ba272d9042fc85b1bff354fd28044
| 1,119
|
cpp
|
C++
|
EZOJ/1721.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 6
|
2019-09-30T16:11:00.000Z
|
2021-11-01T11:42:33.000Z
|
EZOJ/1721.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-11-21T08:17:42.000Z
|
2020-07-28T12:09:52.000Z
|
EZOJ/1721.cpp
|
sshockwave/Online-Judge-Solutions
|
9d0bc7fd68c3d1f661622929c1cb3752601881d3
|
[
"MIT"
] | 4
|
2017-07-26T05:54:06.000Z
|
2020-09-30T13:35:38.000Z
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
using namespace std;
inline bool is_num(char c){
return c>='0'&&c<='9';
}
inline int ni(){
int i=0;char c;
while(!is_num(c=getchar()));
while(i=i*10-'0'+c,is_num(c=getchar()));
return i;
}
const int N=10000010;
int prime[N],ptop=0,mu[N],lambda[N],_lambda[N];
bool np[N];
int main(){
memset(np,0,sizeof(np));
mu[1]=1;
lambda[1]=_lambda[0]=_lambda[1]=0;
for(int i=2;i<N;i++){
if(!np[i]){
prime[ptop++]=i;
mu[i]=-1;
lambda[i]=1;
}
for(int j=0;j<ptop&&i*prime[j]<N;j++){
np[i*prime[j]]=true;
if(i%prime[j]==0){
mu[i*prime[j]]=0;
if((i/prime[j])%prime[j]==0){
lambda[i*prime[j]]=0;
}else{
lambda[i*prime[j]]=mu[i];
}
break;
}else{
mu[i*prime[j]]=-mu[i];
lambda[i*prime[j]]=mu[i]-lambda[i];
}
}
_lambda[i]=_lambda[i-1]+lambda[i];
}
for(int tot=ni();tot--;){
int n=ni(),m=ni();
long long ans=0;
for(int l=1,r,top=min(m,n);l<=top;l=r+1){
r=min(top,min(n/(n/l),m/(m/l)));
ans+=(long long)(n/l)*(m/l)*(_lambda[r]-_lambda[l-1]);
}
printf("%lld\n",ans);
}
}
| 20.345455
| 57
| 0.549598
|
sshockwave
|
31c2c5f20495c3b6a74d21eb34910702277df60c
| 4,518
|
hpp
|
C++
|
src/centurion/math/vector3.hpp
|
twantonie/centurion
|
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
|
[
"MIT"
] | 126
|
2020-12-05T00:05:56.000Z
|
2022-03-30T15:15:03.000Z
|
src/centurion/math/vector3.hpp
|
twantonie/centurion
|
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
|
[
"MIT"
] | 46
|
2020-12-27T14:25:22.000Z
|
2022-01-26T13:58:11.000Z
|
src/centurion/math/vector3.hpp
|
twantonie/centurion
|
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
|
[
"MIT"
] | 13
|
2021-01-20T20:50:18.000Z
|
2022-03-25T06:59:03.000Z
|
#ifndef CENTURION_VECTOR3_HEADER
#define CENTURION_VECTOR3_HEADER
#include <ostream> // ostream
#include <string> // string, to_string
#include "../compiler/features.hpp"
#if CENTURION_HAS_FEATURE_FORMAT
#include <format> // format
#endif // CENTURION_HAS_FEATURE_FORMAT
namespace cen {
/// \addtogroup math
/// \{
/**
* \struct vector3
*
* \brief A simple representation of a 3-dimensional vector.
*
* \serializable
*
* \tparam T the representation type, e.g. `float` or `double`.
*
* \since 5.2.0
*/
template <typename T>
struct vector3 final
{
using value_type = T; ///< The type of the vector components.
value_type x{}; ///< The x-coordinate of the vector.
value_type y{}; ///< The y-coordinate of the vector.
value_type z{}; ///< The z-coordinate of the vector.
#if CENTURION_HAS_FEATURE_SPACESHIP
[[nodiscard]] constexpr auto operator<=>(const vector3&) const noexcept = default;
#endif // CENTURION_HAS_FEATURE_SPACESHIP
/**
* \brief Casts the vector to a vector with another representation type.
*
* \tparam U the target vector type.
*
* \return the result vector.
*
* \since 5.2.0
*/
template <typename U>
[[nodiscard]] explicit operator vector3<U>() const noexcept
{
using target_value_type = typename vector3<U>::value_type;
return vector3<U>{static_cast<target_value_type>(x),
static_cast<target_value_type>(y),
static_cast<target_value_type>(z)};
}
};
/**
* \brief Serializes a 3D-vector.
*
* \details This function expects that the archive provides an overloaded `operator()`,
* used for serializing data. This API is based on the Cereal serialization library.
*
* \tparam Archive the type of the archive.
* \tparam T the type of the vector components.
*
* \param archive the archive used to serialize the vector.
* \param vector the vector that will be serialized.
*
* \since 5.3.0
*/
template <typename Archive, typename T>
void serialize(Archive& archive, vector3<T>& vector)
{
archive(vector.x, vector.y, vector.z);
}
/// \name Vector3 comparison operators
/// \{
#if !CENTURION_HAS_FEATURE_SPACESHIP
/**
* \brief Indicates whether or not two 3D vectors are equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the vectors are equal; `false` otherwise.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator==(const vector3<T>& lhs, const vector3<T>& rhs) noexcept
-> bool
{
return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z);
}
/**
* \brief Indicates whether or not two 3D vectors aren't equal.
*
* \tparam T the representation type used by the vectors.
*
* \param lhs the left-hand side vector.
* \param rhs the right-hand side vector.
*
* \return `true` if the vectors aren't equal; `false` otherwise.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] constexpr auto operator!=(const vector3<T>& lhs, const vector3<T>& rhs) noexcept
-> bool
{
return !(lhs == rhs);
}
#endif // CENTURION_HAS_FEATURE_SPACESHIP
/// \} End of vector3 comparison operators
/// \name String conversions
/// \{
/**
* \brief Returns a string that represents a vector.
*
* \tparam T the representation type used by the vector.
*
* \param vector the vector that will be converted to a string.
*
* \return a string that represents the supplied vector.
*
* \since 5.2.0
*/
template <typename T>
[[nodiscard]] auto to_string(const vector3<T>& vector) -> std::string
{
#if CENTURION_HAS_FEATURE_FORMAT
return std::format("vector3{{x: {}, y: {}, z: {}}}", vector.x, vector.y, vector.z);
#else
return "vector3{x: " + std::to_string(vector.x) + ", y: " + std::to_string(vector.y) +
", z: " + std::to_string(vector.z) + "}";
#endif // CENTURION_HAS_FEATURE_FORMAT
}
/// \} End of string conversions
/// \name Streaming
/// \{
/**
* \brief Prints a textual representation of a vector.
*
* \tparam T the representation type used by the vector.
*
* \param stream the stream that will be used.
* \param vector the vector that will be printed.
*
* \return the used stream.
*
* \since 5.2.0
*/
template <typename T>
auto operator<<(std::ostream& stream, const vector3<T>& vector) -> std::ostream&
{
return stream << to_string(vector);
}
/// \} End of streaming
/// \} End of group math
} // namespace cen
#endif // CENTURION_VECTOR3_HEADER
| 24.160428
| 94
| 0.671536
|
twantonie
|
31c395f56ebf021b843d39a805f7d24ab94733b0
| 4,328
|
cpp
|
C++
|
src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp
|
Lywx/FalconEngine
|
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
|
[
"MIT"
] | 6
|
2017-04-17T12:34:57.000Z
|
2019-10-19T23:29:59.000Z
|
src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp
|
Lywx/FalconEngine
|
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
|
[
"MIT"
] | null | null | null |
src/FalconEngine/Graphics/Renderer/Resource/Texture.cpp
|
Lywx/FalconEngine
|
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
|
[
"MIT"
] | 2
|
2019-12-30T08:28:04.000Z
|
2020-08-05T09:58:53.000Z
|
#include <FalconEngine/Graphics/Renderer/Resource/Texture.h>
#include <FalconEngine/Core/Exception.h>
#include <FalconEngine/Graphics/Renderer/Renderer.h>
#include <FalconEngine/Content/StbLibGuardBegin.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
#include <FalconEngine/Content/StbLibGuardEnd.h>
namespace FalconEngine
{
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
// NOTE(Wuxiang): This default constructor is used in deserialization for texture
// loading.
Texture::Texture() :
mAccessMode(ResourceCreationAccessMode::None),
mAccessUsage(ResourceCreationAccessUsage::None),
mAttachment(),
mDimension(),
mFormat(TextureFormat::None),
mMipmapLevel(0),
mData(nullptr),
mDataSize(0),
mStorageMode(ResourceStorageMode::None),
mType(TextureType::None)
{
}
Texture::Texture(AssetSource assetSource,
const std::string& fileName,
const std::string& filePath,
int width,
int height,
int depth,
TextureFormat format,
TextureType type,
ResourceCreationAccessMode accessMode,
ResourceCreationAccessUsage accessUsage,
ResourceStorageMode storageMode,
int mipmapLevel) :
Asset(assetSource, AssetType::Texture, fileName, filePath),
mAccessMode(accessMode),
mAccessUsage(accessUsage),
mAttachment(),
mDimension(),
mFormat(format),
mMipmapLevel(mipmapLevel),
mStorageMode(storageMode),
mType(type)
{
// Test validity of dimension.
if (width < 1 || height < 1 || depth < 1)
{
FALCON_ENGINE_THROW_RUNTIME_EXCEPTION("Invalid texture dimension.");
}
mDimension[0] = width;
mDimension[1] = height;
mDimension[2] = depth;
// Allocate texture storage.
if (mStorageMode == ResourceStorageMode::Device)
{
mDataSize = 0;
mData = nullptr;
}
else if (mStorageMode == ResourceStorageMode::Host)
{
mDataSize = size_t(mDimension[0]) * size_t(mDimension[1])
* size_t(mDimension[2]) * TexelSize[TextureFormatIndex(mFormat)];
mData = new unsigned char[mDataSize];
}
else
{
FALCON_ENGINE_THROW_ASSERTION_EXCEPTION();
}
}
Texture::~Texture()
{
FALCON_ENGINE_RENDERER_UNBIND(this);
delete[] mData;
}
/************************************************************************/
/* Public Members */
/************************************************************************/
ResourceCreationAccessMode
Texture::GetAccessMode() const
{
return mAccessMode;
}
void
Texture::SetAccessModeInternal(ResourceCreationAccessMode accessMode)
{
mAccessMode = accessMode;
}
ResourceCreationAccessUsage
Texture::GetAccessUsage() const
{
return mAccessUsage;
}
void
Texture::SetAccessUsageInternal(ResourceCreationAccessUsage accessUsage)
{
mAccessUsage = accessUsage;
}
bool
Texture::GetAttachmentEnabled(TextureMode textureMode) const
{
return mAttachment[TextureModeIndex(textureMode)];
}
void
Texture::SetAttachmentEnabled(TextureMode textureMode)
{
mAttachment[TextureModeIndex(textureMode)] = true;
}
void
Texture::ResetAttachmentEnabled(TextureMode textureMode)
{
mAttachment.fill(false);
SetAttachmentEnabled(textureMode);
}
unsigned char *
Texture::GetData()
{
return mData;
}
const unsigned char *
Texture::GetData() const
{
return mData;
}
size_t
Texture::GetDataSize() const
{
return mDataSize;
}
std::array<int, 3>
Texture::GetDimension() const
{
return mDimension;
}
int
Texture::GetDimension(int dimensionIndex) const
{
return mDimension[dimensionIndex];
}
TextureFormat
Texture::GetFormat() const
{
return mFormat;
}
int
Texture::GetMipmapLevel() const
{
return mMipmapLevel;
}
ResourceStorageMode
Texture::GetStorageMode() const
{
return mStorageMode;
}
TextureType Texture::GetTextureType() const
{
return mType;
}
size_t
Texture::GetTexelSize() const
{
return TexelSize[TextureFormatIndex(mFormat)];
}
}
| 22.081633
| 85
| 0.628466
|
Lywx
|
31c8f60900a92de6d519e7caa3f4a3546b425799
| 1,877
|
cpp
|
C++
|
Week 8/Assignment 8_2.cpp
|
BenM-OC/CS10A
|
65823fae5c5fa45942cb942450126aca9294e22e
|
[
"MIT"
] | null | null | null |
Week 8/Assignment 8_2.cpp
|
BenM-OC/CS10A
|
65823fae5c5fa45942cb942450126aca9294e22e
|
[
"MIT"
] | null | null | null |
Week 8/Assignment 8_2.cpp
|
BenM-OC/CS10A
|
65823fae5c5fa45942cb942450126aca9294e22e
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
// The purpose of this program is to prompt the user for a number, and then provide the user with the sum of all squares between zero and the number they've entered
int main()
{
int sumOfSquares = 0;
int calcLoopCounter = 0;
int userTopNumber;
//User inputs the max number the program is allowed to square
cout << "Enter a number greater than 0 (less than 1 to quit): ";
cin >> userTopNumber;
//While the value of the max number is greater than 0 this loop is executed
while (userTopNumber > 0) {
//Calcualtion values are reset to zero so each run of the following loop is ran like the first
calcLoopCounter = 0;
sumOfSquares = 0;
//While the calcLoopCounter is less than the max number selected by the user, the program adds one to the value of the calcLoopCounter, and uses the value of the (calcLoopCounter^2) plus the existing value of the sumOfSqaures to calculate the New sumOfSquares.
while (calcLoopCounter < userTopNumber) {
calcLoopCounter++;
sumOfSquares = (calcLoopCounter * calcLoopCounter) + sumOfSquares;
}
//Program informs the user of the sum of each number from 1 to their max number sqaured
cout << "The sum of squares from 1 to " << userTopNumber << " is " << sumOfSquares << endl;
//Program re-prompts for a max number to rerun the previously executed calculations, exiting the loop and program if the value of the max number is less than one.
cout << "Enter a number greater than 0 (less than 1 to quit): ";
cin >> userTopNumber;
}
return 0;
}
/* OUTPUT
[benji@thinktop Week 8]$ ./sumOfSquares.out
Enter a number greater than 0 (less than 1 to quit): 4
The sum of squares from 1 to 4 is 30
Enter a number greater than 0 (less than 1 to quit): 1
The sum of squares from 1 to 1 is 1
Enter a number greater than 0 (less than 1 to quit): 0
[benji@thinktop Week 8]$
*/
| 37.54
| 263
| 0.732019
|
BenM-OC
|
31cb1ee9c2f7fa49713fd79cfebf07be2cbe60dc
| 12,950
|
cpp
|
C++
|
src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 120
|
2015-01-22T14:10:39.000Z
|
2021-11-25T12:57:16.000Z
|
src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 8
|
2015-02-07T19:38:19.000Z
|
2017-11-30T20:18:28.000Z
|
src/plugins/lmp/plugins/ppl/tracksselectordialog.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 33
|
2015-02-07T16:59:55.000Z
|
2021-10-12T00:36:40.000Z
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "tracksselectordialog.h"
#include <numeric>
#include <QAbstractItemModel>
#include <QApplication>
#include <QDesktopWidget>
#include <QShortcut>
#include <util/sll/prelude.h>
#include <util/sll/views.h>
#include <util/sll/util.h>
namespace LC
{
namespace LMP
{
namespace PPL
{
class TracksSelectorDialog::TracksModel : public QAbstractItemModel
{
const QStringList HeaderLabels_;
enum Header : uint8_t
{
ScrobbleSummary,
Artist,
Album,
Track,
Date
};
static constexpr uint8_t MaxPredefinedHeader = Header::Date;
const Media::IAudioScrobbler::BackdatedTracks_t Tracks_;
QVector<QVector<bool>> Scrobble_;
public:
TracksModel (const Media::IAudioScrobbler::BackdatedTracks_t&,
const QList<Media::IAudioScrobbler*>&, QObject* = nullptr);
static constexpr uint8_t ColumnSelectAll = Header::ScrobbleSummary;
QModelIndex index (int, int, const QModelIndex& = {}) const override;
QModelIndex parent (const QModelIndex&) const override;
int rowCount (const QModelIndex& = {}) const override;
int columnCount (const QModelIndex&) const override;
QVariant data (const QModelIndex&, int) const override;
QVariant headerData (int, Qt::Orientation, int) const override;
Qt::ItemFlags flags (const QModelIndex& index) const override;
bool setData (const QModelIndex& index, const QVariant& value, int role) override;
QList<TracksSelectorDialog::SelectedTrack> GetSelectedTracks () const;
void MarkAll ();
void UnmarkAll ();
void SetMarked (const QList<QModelIndex>&, bool);
void UnmarkRepeats ();
private:
template<typename Summary, typename Specific>
auto WithCheckableColumns (const QModelIndex& index, Summary&& summary, Specific&& specific) const
{
switch (index.column ())
{
case Header::Artist:
case Header::Album:
case Header::Track:
case Header::Date:
using ResultType_t = std::result_of_t<Summary (int)>;
if constexpr (std::is_same_v<ResultType_t, void>)
return;
else
return ResultType_t {};
case Header::ScrobbleSummary:
return summary (index.row ());
}
return specific (index.row (), index.column () - (MaxPredefinedHeader + 1));
}
void MarkRow (const QModelIndex&, bool);
};
TracksSelectorDialog::TracksModel::TracksModel (const Media::IAudioScrobbler::BackdatedTracks_t& tracks,
const QList<Media::IAudioScrobbler*>& scrobblers, QObject *parent)
: QAbstractItemModel { parent }
, HeaderLabels_
{
[&scrobblers]
{
const QStringList predefined
{
{},
tr ("Artist"),
tr ("Album"),
tr ("Title"),
tr ("Date")
};
const auto& scrobbleNames = Util::Map (scrobblers, &Media::IAudioScrobbler::GetServiceName);
return predefined + scrobbleNames;
} ()
}
, Tracks_ { tracks }
, Scrobble_ { tracks.size (), QVector<bool> (scrobblers.size (), true) }
{
}
QModelIndex TracksSelectorDialog::TracksModel::index (int row, int column, const QModelIndex& parent) const
{
return parent.isValid () ?
QModelIndex {} :
createIndex (row, column);
}
QModelIndex TracksSelectorDialog::TracksModel::parent (const QModelIndex&) const
{
return {};
}
int TracksSelectorDialog::TracksModel::rowCount (const QModelIndex& parent) const
{
return parent.isValid () ?
0 :
Tracks_.size () + 1;
}
int TracksSelectorDialog::TracksModel::columnCount (const QModelIndex& parent) const
{
return parent.isValid () ?
0 :
HeaderLabels_.size ();
}
namespace
{
template<typename H, typename D>
auto WithIndex (const QModelIndex& index, H&& header, D&& data)
{
if (!index.row ())
return header (index);
else
return data (index.sibling (index.row () - 1, index.column ()));
}
QVariant PartialCheck (int enabled, int total)
{
if (!enabled)
return Qt::Unchecked;
else if (enabled == total)
return Qt::Checked;
else
return Qt::PartiallyChecked;
}
}
QVariant TracksSelectorDialog::TracksModel::data (const QModelIndex& srcIdx, int role) const
{
return WithIndex (srcIdx,
[&] (const QModelIndex& index) -> QVariant
{
if (role != Qt::CheckStateRole)
return {};
return WithCheckableColumns (index,
[this] (int)
{
const auto enabled = std::accumulate (Scrobble_.begin (), Scrobble_.end (), 0,
[] (int val, const auto& subvec)
{
return std::accumulate (subvec.begin (), subvec.end (), val);
});
const auto total = Scrobble_.size () * Scrobble_ [0].size ();
return PartialCheck (enabled, total);
},
[this] (int, int column)
{
const auto enabled = std::accumulate (Scrobble_.begin (), Scrobble_.end (), 0,
[column] (int val, const auto& subvec) { return val + subvec.at (column); });
return PartialCheck (enabled, Scrobble_.size ());
});
},
[&] (const QModelIndex& index) -> QVariant
{
switch (role)
{
case Qt::DisplayRole:
{
const auto& record = Tracks_.value (index.row ());
switch (index.column ())
{
case Header::ScrobbleSummary:
return {};
case Header::Artist:
return record.first.Artist_;
case Header::Album:
return record.first.Album_;
case Header::Track:
return record.first.Title_;
case Header::Date:
return record.second.toString ();
}
return {};
}
case Qt::CheckStateRole:
{
return WithCheckableColumns (index,
[&] (int row)
{
const auto& flags = Scrobble_.value (row);
const auto enabled = std::accumulate (flags.begin (), flags.end (), 0);
return PartialCheck (enabled, flags.size ());
},
[&] (int row, int column) -> QVariant
{
return Scrobble_.value (row).value (column) ?
Qt::Checked :
Qt::Unchecked;
});
}
default:
return {};
}
});
}
QVariant TracksSelectorDialog::TracksModel::headerData (int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return {};
switch (orientation)
{
case Qt::Horizontal:
return HeaderLabels_.value (section);
case Qt::Vertical:
return section ?
QString::number (section) :
tr ("All");
default:
return {};
}
}
Qt::ItemFlags TracksSelectorDialog::TracksModel::flags (const QModelIndex& index) const
{
switch (index.column ())
{
case Header::Artist:
case Header::Album:
case Header::Track:
case Header::Date:
return QAbstractItemModel::flags (index);
default:
return Qt::ItemIsSelectable |
Qt::ItemIsEnabled |
Qt::ItemIsUserCheckable;
}
}
bool TracksSelectorDialog::TracksModel::setData (const QModelIndex& srcIdx, const QVariant& value, int role)
{
if (role != Qt::CheckStateRole)
return false;
MarkRow (srcIdx, value.toInt () == Qt::Checked);
return true;
}
QList<TracksSelectorDialog::SelectedTrack> TracksSelectorDialog::TracksModel::GetSelectedTracks () const
{
QList<TracksSelectorDialog::SelectedTrack> result;
for (const auto& pair : Util::Views::Zip<std::pair> (Tracks_, Scrobble_))
if (std::any_of (pair.second.begin (), pair.second.end (), Util::Id))
result.push_back ({ pair.first, pair.second });
return result;
}
void TracksSelectorDialog::TracksModel::MarkAll ()
{
for (int i = 0; i < rowCount (); ++i)
MarkRow (index (i, Header::ScrobbleSummary), true);
}
void TracksSelectorDialog::TracksModel::UnmarkAll ()
{
for (int i = 0; i < rowCount (); ++i)
MarkRow (index (i, Header::ScrobbleSummary), false);
}
void TracksSelectorDialog::TracksModel::SetMarked (const QList<QModelIndex>& indices, bool shouldScrobble)
{
for (const auto& idx : indices)
MarkRow (idx, shouldScrobble);
}
void TracksSelectorDialog::TracksModel::UnmarkRepeats ()
{
const auto asTuple = [] (const auto& pair)
{
const auto& media = pair.first;
return std::tie (media.Artist_, media.Album_, media.Title_);
};
for (auto pos = Tracks_.begin (); pos != Tracks_.end (); )
{
pos = std::adjacent_find (pos, Tracks_.end (), Util::EqualityBy (asTuple));
if (pos == Tracks_.end ())
break;
const auto& referenceInfo = asTuple (*pos);
while (++pos != Tracks_.end () && asTuple (*pos) == referenceInfo)
MarkRow (index (std::distance (Tracks_.begin (), pos) + 1, Header::ScrobbleSummary), false);
}
}
void TracksSelectorDialog::TracksModel::MarkRow (const QModelIndex& srcIdx, bool shouldScrobble)
{
WithIndex (srcIdx,
[&] (const QModelIndex& index)
{
WithCheckableColumns (index,
[&] (int)
{
for (auto& subvec : Scrobble_)
std::fill (subvec.begin (), subvec.end (), shouldScrobble);
},
[&] (int, int column)
{
for (auto& subvec : Scrobble_)
subvec [column] = shouldScrobble;
});
const auto lastRow = rowCount (index.parent ()) - 1;
const auto lastColumn = columnCount (index.parent ()) - 1;
emit dataChanged (createIndex (0, 0), createIndex (lastRow, lastColumn));
},
[&] (const QModelIndex& index)
{
auto& scrobbles = Scrobble_ [index.row ()];
WithCheckableColumns (index,
[&] (int) { std::fill (scrobbles.begin (), scrobbles.end (), shouldScrobble); },
[&] (int, int column) { scrobbles [column] = shouldScrobble; });
const auto lastColumn = columnCount (index.parent ()) - 1;
emit dataChanged (createIndex (0, 0), createIndex (0, lastColumn));
emit dataChanged (index.sibling (index.row (), 0), index.sibling (index.row (), lastColumn));
});
}
TracksSelectorDialog::TracksSelectorDialog (const Media::IAudioScrobbler::BackdatedTracks_t& tracks,
const QList<Media::IAudioScrobbler*>& scrobblers,
QWidget *parent)
: QDialog { parent }
, Model_ { new TracksModel { tracks, scrobblers, this } }
{
Ui_.setupUi (this);
Ui_.Tracks_->setModel (Model_);
FixSize ();
auto withSelected = [this] (bool shouldScrobble)
{
return [this, shouldScrobble]
{
auto indices = Ui_.Tracks_->selectionModel ()->selectedIndexes ();
if (indices.isEmpty ())
return;
const auto notCheckable = [] (const auto& idx) { return !(idx.flags () & Qt::ItemIsUserCheckable); };
if (notCheckable (indices.value (0)))
{
const auto column = indices.value (0).column ();
if (std::all_of (indices.begin (), indices.end (),
[&column] (const auto& idx) { return idx.column () == column; }))
for (auto& idx : indices)
idx = idx.sibling (idx.row (), TracksModel::ColumnSelectAll);
}
indices.erase (std::remove_if (indices.begin (), indices.end (), notCheckable), indices.end ());
Model_->SetMarked (indices, shouldScrobble);
};
};
connect (new QShortcut { QString { "Alt+S" }, this },
&QShortcut::activated,
Ui_.MarkSelected_,
&QPushButton::click);
connect (new QShortcut { QString { "Alt+U" }, this },
&QShortcut::activated,
Ui_.UnmarkSelected_,
&QPushButton::click);
connect (Ui_.MarkAll_,
&QPushButton::clicked,
[this] { Model_->MarkAll (); });
connect (Ui_.UnmarkAll_,
&QPushButton::clicked,
[this] { Model_->UnmarkAll (); });
connect (Ui_.UnmarkRepeats_,
&QPushButton::clicked,
[this] { Model_->UnmarkRepeats (); });
connect (Ui_.MarkSelected_,
&QPushButton::clicked,
withSelected (true));
connect (Ui_.UnmarkSelected_,
&QPushButton::clicked,
withSelected (false));
}
void TracksSelectorDialog::FixSize ()
{
Ui_.Tracks_->resizeColumnsToContents ();
const auto showGuard = Util::MakeScopeGuard ([this] { show (); });
const auto Margin = 50;
int totalWidth = Margin + Ui_.Tracks_->verticalHeader ()->width ();
const auto header = Ui_.Tracks_->horizontalHeader ();
for (int j = 0; j < Model_->columnCount ({}); ++j)
totalWidth += std::max (header->sectionSize (j),
Ui_.Tracks_->sizeHintForIndex (Model_->index (0, j, {})).width ());
totalWidth += Ui_.ButtonsLayout_->sizeHint ().width ();
if (totalWidth < size ().width ())
return;
const auto desktop = qApp->desktop ();
const auto& availableGeometry = desktop->availableGeometry (this);
if (totalWidth > availableGeometry.width ())
return;
setGeometry (QStyle::alignedRect (Qt::LeftToRight,
Qt::AlignCenter,
{ totalWidth, height () },
availableGeometry));
}
QList<TracksSelectorDialog::SelectedTrack> TracksSelectorDialog::GetSelectedTracks () const
{
return Model_->GetSelectedTracks ();
}
}
}
}
| 28.152174
| 114
| 0.643012
|
Maledictus
|
31d2b445465a692fd314c9af51918c773d81c991
| 559
|
cpp
|
C++
|
purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp
|
freeeyes/PSS
|
cb6dac549f2fa36c9838b5cb183ba010d56978e3
|
[
"Apache-2.0"
] | 213
|
2015-01-08T05:58:52.000Z
|
2022-03-22T01:23:37.000Z
|
purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp
|
volute24/PSS
|
cb6dac549f2fa36c9838b5cb183ba010d56978e3
|
[
"Apache-2.0"
] | 33
|
2015-09-11T02:52:03.000Z
|
2021-04-12T01:23:48.000Z
|
purenessscopeserver/FrameCore/CppUnit/Unit_BaseConnectClient.cpp
|
volute24/PSS
|
cb6dac549f2fa36c9838b5cb183ba010d56978e3
|
[
"Apache-2.0"
] | 126
|
2015-01-08T06:21:05.000Z
|
2021-11-19T08:19:12.000Z
|
#include "Unit_BaseConnectClient.h"
#ifdef _CPPUNIT_TEST
void CUnit_BaseConnectClient::setUp(void)
{
m_u2CommandID = 0x1003;
}
void CUnit_BaseConnectClient::tearDown(void)
{
m_u2CommandID = 0;
}
void CUnit_BaseConnectClient::Test_Common_Send_ConnectError(void)
{
ACE_INET_Addr objAddrServer;
CPostServerData objPostServerData;
ACE_Message_Block* pMb = App_MessageBlockManager::instance()->Create(10);
Common_Send_ConnectError(pMb, objAddrServer, dynamic_cast<IClientMessage*>(&objPostServerData));
m_nTestCount++;
}
#endif
| 19.964286
| 100
| 0.774597
|
freeeyes
|
31d7740a1cc8ecda041ab5376d9f5d20eebe6147
| 799
|
cpp
|
C++
|
lib/mutexp.cpp
|
williamledda/CPPosix
|
235e990731c7cade43a1105dce6705329c56adbe
|
[
"MIT"
] | null | null | null |
lib/mutexp.cpp
|
williamledda/CPPosix
|
235e990731c7cade43a1105dce6705329c56adbe
|
[
"MIT"
] | null | null | null |
lib/mutexp.cpp
|
williamledda/CPPosix
|
235e990731c7cade43a1105dce6705329c56adbe
|
[
"MIT"
] | null | null | null |
/*
* mutexp.cpp
*
* Created on: 11 gen 2018
* Author: william
*/
#include "mutexp.h"
#include <iostream>
namespace cpposix {
MutexP::MutexP() {
/*Both returns always zero. No error check is needed*/
pthread_mutexattr_init(&this->mtx_attr);
pthread_mutex_init(&this->mtx, &this->mtx_attr);
}
MutexP::~MutexP() {
if(pthread_mutex_destroy(&this->mtx) != 0) {
std::cerr << "Error destroying mutex" << std::endl;
}
if(pthread_mutexattr_destroy(&this->mtx_attr) != 0) {
std::cerr << "Error destroying mutex attribute" << std::endl;
}
}
int MutexP::lock(void) {
return pthread_mutex_lock(&this->mtx);
}
int MutexP::unlock(void) {
return pthread_mutex_unlock(&this->mtx);
}
int MutexP::tryLock(void) {
return pthread_mutex_trylock(&this->mtx);
}
} /* namespace cpposix */
| 18.581395
| 63
| 0.674593
|
williamledda
|
31dbc824948a7a31ecce7e3b96ba48db77e33a51
| 880
|
cpp
|
C++
|
source/toy/gadget/HexCharToInt.cpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 4
|
2017-07-06T22:18:41.000Z
|
2021-05-24T21:28:37.000Z
|
source/toy/gadget/HexCharToInt.cpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | null | null | null |
source/toy/gadget/HexCharToInt.cpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 1
|
2020-08-02T13:00:38.000Z
|
2020-08-02T13:00:38.000Z
|
#include "toy/gadget/HexCharToInt.hpp"
#if TOY_OPTION_RELEASE
#include "toy/Oops.hpp"
#else
#include "toy/Exception.hpp"
#endif
namespace toy{
namespace gadget{
int HexCharToInt(const char code)
{
if ( code<'0' )
{
#if TOY_OPTION_RELEASE
toy::Oops(TOY_MARK);
return 0;
#else
throw toy::Exception(TOY_MARK);
#endif
}
else if ( code>'9' )
{
switch ( code )
{
case 'a': return 10;
case 'A': return 10;
case 'b': return 11;
case 'B': return 11;
case 'c': return 12;
case 'C': return 12;
case 'd': return 13;
case 'D': return 13;
case 'e': return 14;
case 'E': return 14;
case 'f': return 15;
case 'F': return 15;
default:
#if TOY_OPTION_RELEASE
{
toy::Oops(TOY_MARK);
return 0;
}
#else
throw toy::Exception(TOY_MARK);
#endif
}
}
else
{
return code-'0';
}
return 0;
}
}}
| 14.915254
| 38
| 0.589773
|
ToyAuthor
|
31dbffd6b5779c68ec93537e13f905efda9a14ec
| 1,757
|
cpp
|
C++
|
src/cppLinqUnitTest/emptyTest.cpp
|
paolosev/cpplinq
|
9d631e852ebb8f3a0f134524fb82abccd799a361
|
[
"Apache-2.0"
] | null | null | null |
src/cppLinqUnitTest/emptyTest.cpp
|
paolosev/cpplinq
|
9d631e852ebb8f3a0f134524fb82abccd799a361
|
[
"Apache-2.0"
] | null | null | null |
src/cppLinqUnitTest/emptyTest.cpp
|
paolosev/cpplinq
|
9d631e852ebb8f3a0f134524fb82abccd799a361
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2012 Paolo Severini
//
// 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 "stdafx.h"
#include "CppUnitTest.h"
#include "testUtils.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest
{
TEST_CLASS(EmptyTest)
{
public:
static void test()
{
fprintf(stdout, "empty\n");
EmptyTest t;
t.Empty_EmptyContainsNoElements();
t.Empty_EmptyIsASingletonPerElementType();
}
TEST_METHOD(Empty_EmptyContainsNoElements)
{
auto empty = IEnumerable<int>::Empty()->GetEnumerator();
Assert::IsFalse(empty->MoveNext());
}
TEST_METHOD(Empty_EmptyIsASingletonPerElementType)
{
Assert::IsTrue(IEnumerable<int>::Empty().get() == IEnumerable<int>::Empty().get());
Assert::IsTrue(IEnumerable<long>::Empty().get() == IEnumerable<long>::Empty().get());
Assert::IsTrue(IEnumerable<std::string>::Empty().get() == IEnumerable<std::string>::Empty().get());
Assert::IsFalse((void*)IEnumerable<long>::Empty().get() == (void*)IEnumerable<int>::Empty().get());
}
};
}
| 33.788462
| 112
| 0.627775
|
paolosev
|
31dd567dedb65314795c4b49818e6c1d792f0827
| 18,443
|
cpp
|
C++
|
library/src/Json.cpp
|
StratifyLabs/JsonAPI
|
82283d2571452d75468d508db19c328f052ecac7
|
[
"MIT"
] | null | null | null |
library/src/Json.cpp
|
StratifyLabs/JsonAPI
|
82283d2571452d75468d508db19c328f052ecac7
|
[
"MIT"
] | null | null | null |
library/src/Json.cpp
|
StratifyLabs/JsonAPI
|
82283d2571452d75468d508db19c328f052ecac7
|
[
"MIT"
] | null | null | null |
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md
#include <type_traits>
#if USE_PRINTER
#include "sys/Printer.hpp"
#endif
//#include "sys/Sys.hpp"
#include <printer/Printer.hpp>
#include <var/StackString.hpp>
#include <var/StringView.hpp>
#include <var/Tokenizer.hpp>
#include "json/Json.hpp"
printer::Printer &
printer::operator<<(Printer &printer, const json::JsonValue &a) {
return print_value(printer, a, "");
}
printer::Printer &
printer::operator<<(Printer &printer, const json::JsonError &a) {
printer.key("text", a.text());
printer.key("line", var::NumberString(a.line()).string_view());
printer.key("column", var::NumberString(a.column()).string_view());
printer.key("position", var::NumberString(a.position()).string_view());
printer.key("source", a.source());
return printer;
}
printer::Printer &printer::print_value(
Printer &printer,
const json::JsonValue &a,
var::StringView key) {
if (a.is_object()) {
json::JsonValue::KeyList key_list = a.to_object().get_key_list();
if (!key.is_empty()) {
printer.print_open_object(printer.verbose_level(), key);
}
for (const auto &subkey : key_list) {
const json::JsonValue &entry = a.to_object().at(subkey);
print_value(printer, entry, subkey);
}
if (!key.is_empty()) {
printer.print_close_object();
}
} else if (a.is_array()) {
if (!key.is_empty()) {
printer.print_open_array(printer.verbose_level(), key);
}
for (u32 i = 0; i < a.to_array().count(); i++) {
const json::JsonValue &entry = a.to_array().at(i);
print_value(printer, entry, var::NumberString().format("[%04d]", i));
}
if (!key.is_empty()) {
printer.print_close_array();
}
} else if (a.is_integer()) {
printer.key(key, var::NumberString(a.to_integer()).string_view());
} else if (a.is_real()) {
printer.key(key, var::NumberString(a.to_real()).string_view());
} else {
printer.key(key, var::StringView(a.to_cstring()));
}
return printer;
}
using namespace var;
using namespace json;
JsonApi JsonValue::m_api;
JsonValue::JsonValue() {
if (api().is_valid() == false) {
exit_fatal("json api missing");
}
m_value = nullptr; // create() method from children are not available in the
// constructor
}
int JsonValue::translate_json_error(int json_result) {
switch (json_result) {
case json_error_unknown:
return -1;
case json_error_out_of_memory:
return -1;
case json_error_stack_overflow:
return -1;
case json_error_cannot_open_file:
return -1;
case json_error_invalid_argument:
return -1;
case json_error_invalid_utf8:
return -1;
case json_error_premature_end_of_input:
return -1;
case json_error_end_of_input_expected:
return -1;
case json_error_invalid_syntax:
return -1;
case json_error_invalid_format:
return -1;
case json_error_wrong_type:
return -1;
case json_error_null_character:
return -1;
case json_error_null_value:
return -1;
case json_error_null_byte_in_key:
return -1;
case json_error_duplicate_key:
return -1;
case json_error_numeric_overflow:
return -1;
case json_error_item_not_found:
return -1;
case json_error_index_out_of_range:
return -1;
}
return 0;
}
JsonValue::JsonValue(json_t *value) {
if (api().is_valid() == false) {
exit_fatal("json api missing");
}
add_reference(value);
}
JsonValue::JsonValue(const JsonValue &value) {
if (api().is_valid() == false) {
exit_fatal("json api missing");
}
add_reference(value.m_value);
}
JsonValue &JsonValue::operator=(const JsonValue &value) {
if (this != &value) {
api()->decref(m_value);
add_reference(value.m_value);
}
return *this;
}
void JsonValue::add_reference(json_t *value) {
m_value = value;
api()->incref(value);
}
JsonValue::JsonValue(JsonValue &&a) {
std::swap(m_value, a.m_value);
}
JsonValue &JsonValue::operator=(JsonValue &&a) {
std::swap(m_value, a.m_value);
return *this;
}
JsonValue::~JsonValue() {
// only decref if object was created (not just a reference)
if (m_value) {
api()->decref(m_value);
m_value = nullptr;
}
}
JsonValue JsonValue::lookup(const var::StringView key_path) const {
API_ASSERT(key_path.at(0) == '/');
const auto element_list = key_path.split("/");
JsonValue parent = *this;
for (size_t i = 1; i < element_list.count(); i++) {
const auto element = element_list.at(i);
// first element is empty
JsonValue child
= parent.is_object()
? parent.to_object().at(element)
: (
parent.is_array() ? parent.to_array().at(element.to_integer())
: parent);
parent = child;
}
return parent;
}
const JsonObject &JsonValue::to_object() const {
return static_cast<const JsonObject &>(*this);
}
JsonValue JsonObjectIterator::operator*() const noexcept {
return JsonValue(m_json_value)
.to_object()
.at(api()->object_iter_key(m_json_iter));
}
JsonObject &JsonValue::to_object() { return static_cast<JsonObject &>(*this); }
const JsonArray &JsonValue::to_array() const {
return static_cast<const JsonArray &>(*this);
}
JsonArray &JsonValue::to_array() { return static_cast<JsonArray &>(*this); }
int JsonValue::create_if_not_valid() {
API_RETURN_VALUE_IF_ERROR(-1);
if (is_valid()) {
return 0;
}
m_value = create();
if (m_value == nullptr) {
API_SYSTEM_CALL("", -1);
return -1;
}
return 0;
}
JsonValue &JsonValue::assign(const var::StringView value) {
API_RETURN_VALUE_IF_ERROR(*this);
if (is_string()) {
API_SYSTEM_CALL(
"",
api()->string_setn(m_value, value.data(), value.length()));
} else if (is_real()) {
API_SYSTEM_CALL(
"",
api()->real_set(m_value, var::NumberString(value).to_float()));
} else if (is_integer()) {
API_SYSTEM_CALL(
"",
api()->integer_set(m_value, var::NumberString(value).to_integer()));
} else if (is_true() || is_false()) {
if (var::StringView(value) == "true") {
*this = JsonTrue();
} else {
*this = JsonFalse();
}
}
return *this;
}
JsonValue &JsonValue::copy(const JsonValue &value, IsDeepCopy is_deep) {
api()->decref(m_value);
if (is_deep == IsDeepCopy::yes) {
m_value = api()->deep_copy(value.m_value);
} else {
m_value = api()->copy(value.m_value);
}
return *this;
}
const char *JsonValue::to_cstring() const {
const char *result;
if (is_string()) {
result = api()->string_value(m_value);
} else if (is_true()) {
result = "true";
} else if (is_false()) {
result = "false";
} else if (is_null()) {
result = "null";
} else if (is_object()) {
result = "{object}";
} else if (is_array()) {
result = "[array]";
} else {
result = "";
}
return result;
}
var::String JsonValue::to_string() const {
var::String result;
if (is_string()) {
result = api()->string_value(m_value);
} else if (is_real()) {
result.format("%f", api()->real_value(m_value));
} else if (is_integer()) {
result.format("%ld", api()->integer_value(m_value));
} else if (is_true()) {
result = "true";
} else if (is_false()) {
result = "false";
} else if (is_null()) {
result = "null";
} else if (is_object()) {
result = "{object}";
} else if (is_array()) {
result = "[array]";
} else {
result = "";
}
return result;
}
float JsonValue::to_real() const {
if (is_string()) {
return to_string_view().to_float();
} else if (is_integer()) {
return to_integer() * 1.0f;
} else if (is_real()) {
return api()->real_value(m_value);
} else if (is_true()) {
return 1.0f;
}
return 0.0f;
}
int JsonValue::to_integer() const {
if (is_string()) {
return to_string_view().to_integer();
} else if (is_real()) {
return to_real();
} else if (is_integer()) {
return api()->integer_value(m_value);
}
if (is_true()) {
return 1;
}
if (is_false()) {
return 0;
}
if (is_null()) {
return 0;
}
return 0;
}
bool JsonValue::to_bool() const {
if (is_true()) {
return true;
}
if (is_false()) {
return false;
}
if (is_string()) {
if (to_cstring() == var::StringView("true")) {
return true;
}
return false;
}
if (is_integer()) {
return to_integer() != 0;
}
if (is_real()) {
return to_real() != 0.0f;
}
if (is_object()) {
return true;
}
if (is_array()) {
return true;
}
return false;
}
JsonObject::JsonObject() { m_value = JsonObject::create(); }
JsonObject::JsonObject(const JsonObject &value) {
add_reference(value.m_value);
}
JsonObject &JsonObject::operator=(const JsonObject &value) {
api()->decref(m_value);
add_reference(value.m_value);
return *this;
}
json_t *JsonObject::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
json_t *result = API_SYSTEM_CALL_NULL("", api()->create_object());
return result;
}
json_t *JsonArray::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_array());
}
json_t *JsonReal::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_real(0.0f));
}
json_t *JsonInteger::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_integer(0));
}
json_t *JsonTrue::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_true());
}
json_t *JsonFalse::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_false());
}
json_t *JsonString::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_string(""));
}
json_t *JsonNull::create() {
API_RETURN_VALUE_IF_ERROR(nullptr);
return API_SYSTEM_CALL_NULL("", api()->create_null());
}
JsonObject &JsonObject::insert_bool(const var::StringView key, bool value) {
if (value) {
return insert(Key(key).cstring, JsonTrue());
}
return insert(Key(key).cstring, JsonFalse());
}
JsonObject &
JsonObject::insert(const var::StringView key, const JsonValue &value) {
if (create_if_not_valid() < 0) {
return *this;
}
API_SYSTEM_CALL(
"",
api()->object_set(m_value, Key(key).cstring, value.m_value));
return *this;
}
JsonObject &JsonObject::update(const JsonValue &value, UpdateFlags o_flags) {
API_RETURN_VALUE_IF_ERROR(*this);
if (o_flags & UpdateFlags::existing) {
API_SYSTEM_CALL("", api()->object_update_existing(m_value, value.m_value));
return *this;
}
if (o_flags & UpdateFlags::missing) {
API_SYSTEM_CALL("", api()->object_update_missing(m_value, value.m_value));
return *this;
}
API_SYSTEM_CALL("", api()->object_update(m_value, value.m_value));
return *this;
}
JsonObject &JsonObject::remove(const var::StringView key) {
API_RETURN_VALUE_IF_ERROR(*this);
API_SYSTEM_CALL("", api()->object_del(m_value, Key(key).cstring));
return *this;
}
u32 JsonObject::count() const { return api()->object_size(m_value); }
JsonObject &JsonObject::clear() {
API_RETURN_VALUE_IF_ERROR(*this);
API_SYSTEM_CALL("", api()->object_clear(m_value));
return *this;
}
JsonObject::KeyList JsonObject::get_key_list() const {
const char *key;
u32 count = 0;
for (key = api()->object_iter_key(api()->object_iter(m_value)); key;
key = api()->object_iter_key(
api()->object_iter_next(m_value, api()->object_key_to_iter(key)))) {
count++;
}
KeyList result = KeyList().reserve(count);
for (key = api()->object_iter_key(api()->object_iter(m_value)); key;
key = api()->object_iter_key(
api()->object_iter_next(m_value, api()->object_key_to_iter(key)))) {
result.push_back(key);
}
return result;
}
JsonValue JsonObject::at(const var::StringView key) const {
return JsonValue(api()->object_get(m_value, Key(key).cstring));
}
JsonValue JsonObject::at(size_t offset) const {
size_t count = 0;
for (const auto &child : *this) {
if (count == offset) {
return child;
}
count++;
}
return JsonValue();
}
JsonValue
JsonValue::find(const var::StringView path, const char *delimiter) const {
const auto list = path.split(delimiter);
JsonValue current = *this;
auto get_offset_from_string = [](var::StringView item) {
return item.pop_back().pop_back().to_unsigned_long();
};
for (const auto item : list) {
if (item.is_empty()) {
API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "empty item provided", EINVAL);
return JsonValue();
}
if (current.is_object()) {
auto next = current.to_object().at(item);
if (next.is_valid()) {
current = next;
continue;
}
if (item.at(0) == '{') {
const auto object_offset = get_offset_from_string(item);
size_t count = 0;
bool is_found = false;
for (const auto &value : current.to_object()) {
if (count == object_offset) {
current = value;
is_found = true;
break;
}
count++;
}
if (!is_found) {
API_RETURN_VALUE_ASSIGN_ERROR(
JsonValue(),
"didn't find {} offset",
EINVAL);
}
} else {
current = current.to_object().at(item);
}
} else if (current.is_array()) {
if (item.at(0) == '[') {
if (current.is_array() == false) {
API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "not an array", EINVAL);
}
const auto array_offset = get_offset_from_string(item);
;
if (current.to_array().count() <= array_offset) {
API_RETURN_VALUE_ASSIGN_ERROR(
JsonValue(),
"[] is beyond array",
EINVAL);
}
current = current.to_array().at(array_offset);
} else {
API_RETURN_VALUE_ASSIGN_ERROR(
JsonValue(),
"array not specified []",
EINVAL);
return JsonValue();
}
}
if (current.is_valid() == false) {
API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "invalid path", EINVAL);
return JsonValue();
}
}
return current;
}
JsonArray::JsonArray() { m_value = JsonArray::create(); }
JsonArray::JsonArray(const JsonArray &value) { add_reference(value.m_value); }
JsonArray &JsonArray::operator=(const JsonArray &value) {
api()->decref(m_value);
add_reference(value.m_value);
return *this;
}
u32 JsonArray::count() const { return api()->array_size(m_value); }
JsonValue JsonArray::at(size_t position) const {
return JsonValue(api()->array_get(m_value, position));
}
JsonArray::JsonArray(const var::StringList &list) {
m_value = JsonArray::create();
for (const auto &entry : list) {
append(JsonString(entry.cstring()));
}
}
JsonArray::JsonArray(const var::StringViewList &list) {
m_value = JsonArray::create();
for (const auto &entry : list) {
append(JsonString(entry));
}
}
JsonArray::JsonArray(const var::Vector<float> &list) {
m_value = JsonArray::create();
for (const auto &entry : list) {
append(JsonReal(entry));
}
}
JsonArray::JsonArray(const var::Vector<u32> &list) {
m_value = JsonArray::create();
for (const auto &entry : list) {
append(JsonInteger(entry));
}
}
JsonArray::JsonArray(const var::Vector<s32> &list) {
m_value = JsonArray::create();
for (const auto &entry : list) {
append(JsonInteger(entry));
}
}
JsonArray &JsonArray::append(const JsonValue &value) {
if (create_if_not_valid() < 0) {
return *this;
}
API_SYSTEM_CALL("", api()->array_append(m_value, value.m_value));
return *this;
}
JsonArray &JsonArray::append(const JsonArray &array) {
if (create_if_not_valid() < 0) {
return *this;
}
API_SYSTEM_CALL("", api()->array_extend(m_value, array.m_value));
return *this;
}
JsonArray &JsonArray::insert(size_t position, const JsonValue &value) {
if (create_if_not_valid() < 0) {
return *this;
}
API_SYSTEM_CALL("", api()->array_insert(m_value, position, value.m_value));
return *this;
}
JsonArray &JsonArray::remove(size_t position) {
API_RETURN_VALUE_IF_ERROR(*this);
API_SYSTEM_CALL("", api()->array_remove(m_value, position));
return *this;
}
JsonArray &JsonArray::clear() {
API_RETURN_VALUE_IF_ERROR(*this);
API_SYSTEM_CALL("", api()->array_clear(m_value));
return *this;
}
var::StringViewList JsonArray::string_view_list() const {
var::StringViewList result;
result.reserve(count());
for (u32 i = 0; i < count(); i++) {
result.push_back(var::StringView(at(i).to_cstring()));
}
return result;
}
var::Vector<s32> JsonArray::integer_list() const {
var::Vector<s32> result;
result.reserve(count());
for (u32 i = 0; i < count(); i++) {
result.push_back(at(i).to_integer());
}
return result;
}
var::Vector<float> JsonArray::float_list() const {
var::Vector<float> result;
result.reserve(count());
for (u32 i = 0; i < count(); i++) {
result.push_back(at(i).to_real());
}
return result;
}
var::Vector<bool> JsonArray::bool_list() const {
var::Vector<bool> result;
result.reserve(count());
for (u32 i = 0; i < count(); i++) {
result.push_back(at(i).to_bool());
}
return result;
}
JsonString::JsonString() { m_value = JsonString::create(); }
JsonString::JsonString(const char *str) {
API_RETURN_IF_ERROR();
m_value = API_SYSTEM_CALL_NULL("", api()->create_string(str));
}
JsonString::JsonString(const var::StringView str) {
API_RETURN_IF_ERROR();
m_value
= API_SYSTEM_CALL_NULL("", api()->create_stringn(str.data(), str.length()));
}
JsonString::JsonString(const var::String &str) {
API_RETURN_IF_ERROR();
m_value = API_SYSTEM_CALL_NULL(
"",
api()->create_stringn(str.cstring(), str.length()));
}
const char *JsonString::cstring() const { return api()->string_value(m_value); }
JsonReal::JsonReal() { m_value = JsonReal::create(); }
JsonReal::JsonReal(float value) {
API_RETURN_IF_ERROR();
m_value = API_SYSTEM_CALL_NULL("", api()->create_real(value));
}
JsonInteger::JsonInteger() { m_value = JsonInteger::create(); }
JsonInteger::JsonInteger(int value) {
API_RETURN_IF_ERROR();
m_value = API_SYSTEM_CALL_NULL("", api()->create_integer(value));
}
JsonNull::JsonNull() { m_value = JsonNull::create(); }
JsonTrue::JsonTrue() { m_value = JsonTrue::create(); }
JsonFalse::JsonFalse() { m_value = JsonFalse::create(); }
| 24.922973
| 80
| 0.643659
|
StratifyLabs
|
31e293a3b1575e0b4889caef9ddfba87b7e9e515
| 2,349
|
cpp
|
C++
|
board/fpga/net_reliable/tx_arbiter/tb.cpp
|
WukLab/Clio
|
7908c3a022fd356cd54616630fcddf59f7f3fd95
|
[
"MIT"
] | 46
|
2021-12-02T04:45:23.000Z
|
2022-03-21T08:19:07.000Z
|
board/fpga/net_reliable/tx_arbiter/tb.cpp
|
WukLab/Clio
|
7908c3a022fd356cd54616630fcddf59f7f3fd95
|
[
"MIT"
] | null | null | null |
board/fpga/net_reliable/tx_arbiter/tb.cpp
|
WukLab/Clio
|
7908c3a022fd356cd54616630fcddf59f7f3fd95
|
[
"MIT"
] | 2
|
2022-03-17T04:00:53.000Z
|
2022-03-20T14:06:25.000Z
|
/*
* Copyright (c) 2020,Wuklab, UCSD.
*/
#include "arbiter_64.hpp"
#include <uapi/gbn.h>
#define MAX_CYCLE 50
struct net_axis_64 build_gbn_header(ap_uint<8> type, ap_uint<SEQ_WIDTH> seqnum,
ap_uint<1> last)
{
struct net_axis_64 pkt;
pkt.data(7, 0) = type;
pkt.data(8 + SEQ_WIDTH - 1, 8) = seqnum;
pkt.data(63, 8 + SEQ_WIDTH) = 0;
pkt.keep = 0xff;
pkt.last = last;
pkt.user = 0;
return pkt;
}
int main() {
stream<struct udp_info> rsp_header, rt_header, tx_header, out_header;
stream<struct net_axis_64> rsp_payload, rt_payload, tx_payload,
out_payload;
struct udp_info test_header;
struct net_axis_64 test_payload;
test_header.src_ip = 0xc0a80181; // 192.168.1.129
test_header.dest_ip = 0xc0a80180; // 192.168.1.128
test_header.src_port = 1234;
test_header.dest_port = 2345;
rsp_header.write(test_header);
test_payload = build_gbn_header(GBN_PKT_ACK, 1, 1);
rsp_payload.write(test_payload);
test_payload.keep = 0xff;
test_payload.user = 0;
rt_header.write(test_header);
for (int j = 0; j < 10; j++) {
test_payload.data = 0x0f0f0f0f0f0f0f0f;
test_payload.last = 0;
rt_payload.write(test_payload);
}
test_payload.data = 0x0f0f0f0f0f0f0f0f;
test_payload.last = 1;
rt_payload.write(test_payload);
tx_header.write(test_header);
for (int j = 0; j < 10; j++) {
test_payload.data = 0x0101010101010101;
test_payload.last = 0;
tx_payload.write(test_payload);
}
test_payload.data = 0x0101010101010101;
test_payload.last = 1;
tx_payload.write(test_payload);
for (int cycle = 0; cycle < MAX_CYCLE; cycle++) {
arbiter_64(&rsp_header, &rsp_payload, &tx_header, &tx_payload,
&rt_header, &rt_payload, &out_header, &out_payload);
struct udp_info recv_hd;
struct net_axis_64 recv_data;
if (out_header.read_nb(recv_hd)) {
dph("[cycle %2d] send data to net %x:%d -> %x:%d\n",
cycle, recv_hd.src_ip.to_uint(),
recv_hd.src_port.to_uint(),
recv_hd.dest_ip.to_uint(),
recv_hd.dest_port.to_uint());
}
if (out_payload.read_nb(recv_data)) {
dph("[cycle %2d] send data to net %llx, ", cycle,
recv_data.data.to_uint64());
ap_uint<8> type = recv_data.data(7, 0);
ap_uint<SEQ_WIDTH> seqnum =
recv_data.data(8 + SEQ_WIDTH - 1, 8);
dph("if gbn header [type %d, seq %lld]\n",
type.to_ushort(), seqnum.to_uint64());
}
}
}
| 27
| 79
| 0.689229
|
WukLab
|
31e36365fa9475874f775caf70baa488eacc3cc0
| 588
|
hpp
|
C++
|
include/MCL/Screenshot.hpp
|
mattoverby/mclapp
|
e17cdf5ce1fb22f3061d46c26978ea9c60371841
|
[
"MIT"
] | null | null | null |
include/MCL/Screenshot.hpp
|
mattoverby/mclapp
|
e17cdf5ce1fb22f3061d46c26978ea9c60371841
|
[
"MIT"
] | null | null | null |
include/MCL/Screenshot.hpp
|
mattoverby/mclapp
|
e17cdf5ce1fb22f3061d46c26978ea9c60371841
|
[
"MIT"
] | null | null | null |
// Copyright Matt Overby 2021.
// Distributed under the MIT License.
#ifndef MCL_SCREENSHOT_HPP
#define MCL_SCREENSHOT_HPP 1
#include <igl/opengl/glfw/Viewer.h>
namespace mcl
{
class Screenshot
{
public:
int frame_counter;
bool render_background;
bool rendered_init;
Screenshot() :
frame_counter(0),
render_background(0),
rendered_init(0)
{}
// If filename is empty, it's auto computed from the frame_counter.
// Otherwise, the frame_counter is NOT incremented.
void save_frame(igl::opengl::glfw::Viewer &viewer, std::string fn="");
};
} // end namespace mcl
#endif
| 18.375
| 71
| 0.738095
|
mattoverby
|
31e4de8ace3e37b2951c4690b3af0bb105b0c50a
| 966
|
cpp
|
C++
|
src/Root.cpp
|
syoch/wiiu-libgu
|
6744c46c9522c1a6def23aa613e8b759c50064c4
|
[
"MIT"
] | 1
|
2021-02-26T15:49:54.000Z
|
2021-02-26T15:49:54.000Z
|
src/Root.cpp
|
syoch/wiiu-libgui
|
6744c46c9522c1a6def23aa613e8b759c50064c4
|
[
"MIT"
] | null | null | null |
src/Root.cpp
|
syoch/wiiu-libgui
|
6744c46c9522c1a6def23aa613e8b759c50064c4
|
[
"MIT"
] | null | null | null |
#include <Root.hpp>
#include <DrawWrapper.hpp>
#include <mc/internal/std/string.hpp>
void GUI::Root::draw_line(DrawPoint start, DrawPoint end)
{
GUI::draw_line(start, end);
}
void GUI::Root::draw_rect(DrawPoint start, DrawPoint end)
{
GUI::draw_rect(start, end);
}
void GUI::Root::draw_rect(DrawPoint A, DrawPoint B, DrawPoint C, DrawPoint D)
{
GUI::draw_rect(A, B, C, D);
}
void GUI::Root::draw_triangle(DrawPoint A, DrawPoint B, DrawPoint C)
{
GUI::draw_triangle(A, B, C);
}
void GUI::Root::draw_text(int row, int column, mstd::wstring text, Color color)
{
GUI::draw_text(row, column, text, color);
}
void GUI::Root::draw_textShadow(int row, int column, mstd::wstring text, Color color)
{
GUI::draw_textShadow(row, column, text, color);
}
void GUI::Root::draw_translate(float x, float y)
{
GUI::_draw_translate(x, y);
}
void GUI::Root::_draw()
{
ContainerBase::_draw();
}
GUI::Root::Root()
: GUI::ContainerBase(0, 0, 0, 0)
{
}
| 23.560976
| 85
| 0.682195
|
syoch
|
31e4fc1d129b7959afb1ac46924c6898167485fb
| 1,970
|
hpp
|
C++
|
cpp/timeSerie/sources/sparseTimeSerie.hpp
|
jxtopher/quick-codes
|
577711394f3f338c061f1e53df875d958c645071
|
[
"Apache-2.0"
] | null | null | null |
cpp/timeSerie/sources/sparseTimeSerie.hpp
|
jxtopher/quick-codes
|
577711394f3f338c061f1e53df875d958c645071
|
[
"Apache-2.0"
] | null | null | null |
cpp/timeSerie/sources/sparseTimeSerie.hpp
|
jxtopher/quick-codes
|
577711394f3f338c061f1e53df875d958c645071
|
[
"Apache-2.0"
] | null | null | null |
///
/// @file sparseTimeSerie.hpp
/// @author Jxtopher
/// @brief
/// @version 0.1
/// @date 2019-11-09
///
/// @copyright Copyright (c) 2019
///
///
#include <iostream>
#include <map>
#include "timeSerie.hpp"
template <typename TYPE_VALUES>
class SparseTimeSerie : public TimeSerie {
public:
SparseTimeSerie(unsigned int size, TYPE_VALUES defaultValue) : _size(size) {
_values[0] = defaultValue;
}
TYPE_VALUES operator()(const unsigned int t) const {
if (_size < t) {
std::cout<<"_size < t"<<std::endl;
exit(0);
}
if (_values.find(t) != _values.end()) { // Key found
return _values.at(t);
} else { // Key not found
unsigned int index = 0;
if (_values.size() == 1) return _values.at(0);
for (typename std::map<unsigned int, TYPE_VALUES>::const_iterator it=_values.begin(); it!=_values.end(); ++it)
if (t < it->first) return _values.at((--it)->first);
return (--_values.end())->second;
}
}
void operator()(const unsigned int t, const TYPE_VALUES value) {
if (_values.find(t) == _values.end()) { // Key found
TYPE_VALUES tmp = this->operator()(t);
_values[t] = value;
if (_values.find(t+1) == _values.end())// Key not found
_values[t+1] = tmp;
} else// Key not found
_values[t] = value;
}
unsigned int size() const {
return _size;
}
friend std::ostream& operator<<(std::ostream& os, const SparseTimeSerie<TYPE_VALUES>& sparseTimeSerie) {
for (typename std::map<unsigned int, TYPE_VALUES>::const_iterator it = sparseTimeSerie._values.begin(); it != sparseTimeSerie._values.end(); ++it)
os << it->first << " => " << it->second << '\n';
return os;
}
private:
std::map<unsigned int, TYPE_VALUES> _values;
unsigned int _size;
};
| 28.142857
| 155
| 0.560406
|
jxtopher
|
31e54d8e5561952e08a33f4e57e87e915b0154dd
| 540
|
hpp
|
C++
|
flare/include/flare/exceptions/missing_file_exception.hpp
|
taehyub/flare_cpp
|
7731bc0bcf2ce721f103586a48f74aa5c12504e8
|
[
"MIT"
] | 14
|
2019-04-29T15:17:24.000Z
|
2020-12-30T12:51:05.000Z
|
flare/include/flare/exceptions/missing_file_exception.hpp
|
taehyub/flare_cpp
|
7731bc0bcf2ce721f103586a48f74aa5c12504e8
|
[
"MIT"
] | null | null | null |
flare/include/flare/exceptions/missing_file_exception.hpp
|
taehyub/flare_cpp
|
7731bc0bcf2ce721f103586a48f74aa5c12504e8
|
[
"MIT"
] | 6
|
2019-04-29T15:17:25.000Z
|
2021-11-16T03:20:59.000Z
|
#ifndef _FLARE_MISSINGFILEEXCEPTION_HPP_
#define _FLARE_MISSINGFILEEXCEPTION_HPP_
#include <exception>
#include <string>
namespace flare
{
class MissingFileException : public std::exception
{
std::string m_Message;
std::string m_Filename;
public:
MissingFileException(const std::string& msg, const std::string& filename) : m_Message(msg), m_Filename(filename)
{
}
const std::string& message() const
{
return m_Message;
}
const std::string& filename() const
{
return m_Filename;
}
};
}
#endif
| 18
| 115
| 0.709259
|
taehyub
|
31e5ee3abf51f0f9a819a5a9406f79dee4d4a305
| 728
|
cpp
|
C++
|
src/test/test_sensors.cpp
|
sj0897/my-ARIAC-competition-2021
|
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/test_sensors.cpp
|
sj0897/my-ARIAC-competition-2021
|
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
|
[
"BSD-3-Clause"
] | null | null | null |
src/test/test_sensors.cpp
|
sj0897/my-ARIAC-competition-2021
|
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
|
[
"BSD-3-Clause"
] | null | null | null |
#include<memory>
#include <ros/ros.h>
#include "sensors.h"
int main(int argc, char **argv){
ros::init(argc, argv, "test_sensors");
ros::NodeHandle nh;
auto logical_camera_bins0 = std::make_unique<LogicalCamera>(&nh, "logical_camera_bins0");
auto logical_camera_station2 = std::make_unique<LogicalCamera>(&nh, "logical_camera_station2");
auto depth_camera_bins1 = std::make_unique<DepthCamera>(&nh, "depth_camera_bins1");
auto proximity_sensor_0 = std::make_unique<ProximitySensor>(&nh, "proximity_sensor_0");
auto laser_profiler_0 = std::make_unique<LaserProfiler>(&nh, "laser_profiler_0");
auto breakbeam_0 = std::make_unique<BreakBeam>(&nh, "breakbeam_0");
ros::spin();
return 0;
}
| 30.333333
| 99
| 0.722527
|
sj0897
|
31eaed72f7e10018a0e4cfabc9f0d5ebed075fa8
| 81
|
cxx
|
C++
|
test/itkEmptyTest.cxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | 4
|
2016-01-09T19:02:28.000Z
|
2017-07-31T19:41:32.000Z
|
test/itkEmptyTest.cxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | null | null | null |
test/itkEmptyTest.cxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | 2
|
2016-08-06T00:58:26.000Z
|
2019-02-18T01:03:13.000Z
|
#include <cstdlib>
int itkEmptyTest( int , char ** )
{
return EXIT_SUCCESS;
}
| 11.571429
| 33
| 0.666667
|
bloyl
|
31ef33265c56b7126138f4d0838d0ebae8ea6d53
| 6,025
|
cpp
|
C++
|
ui/renderer/yas_ui_renderer_dependency.cpp
|
objective-audio/ui
|
cabf854b290c8df8c7e2f22f0f026b32c4173208
|
[
"MIT"
] | 2
|
2017-06-07T18:30:29.000Z
|
2019-04-29T07:18:53.000Z
|
ui/renderer/yas_ui_renderer_dependency.cpp
|
objective-audio/ui
|
cabf854b290c8df8c7e2f22f0f026b32c4173208
|
[
"MIT"
] | null | null | null |
ui/renderer/yas_ui_renderer_dependency.cpp
|
objective-audio/ui
|
cabf854b290c8df8c7e2f22f0f026b32c4173208
|
[
"MIT"
] | null | null | null |
//
// yas_ui_renderer_dependency.cpp
//
#include "yas_ui_renderer_dependency.h"
#include <cpp_utils/yas_fast_each.h>
#include <cpp_utils/yas_stl_utils.h>
using namespace yas;
using namespace yas::ui;
bool tree_updates::is_any_updated() const {
return this->node_updates.flags.any() || this->mesh_updates.flags.any() || this->vertex_data_updates.flags.any() ||
this->index_data_updates.flags.any() || this->render_target_updates.flags.any() ||
this->effect_updates.flags.any();
}
bool tree_updates::is_collider_updated() const {
static node_updates_t const _node_collider_updates = {
ui::node_update_reason::enabled, ui::node_update_reason::children, ui::node_update_reason::collider};
return this->node_updates.and_test(_node_collider_updates);
}
bool tree_updates::is_render_target_updated() const {
return this->render_target_updates.flags.any() || this->effect_updates.flags.any();
}
batch_building_type tree_updates::batch_building_type() const {
static node_updates_t const _node_rebuild_updates = {ui::node_update_reason::mesh, ui::node_update_reason::enabled,
ui::node_update_reason::children,
ui::node_update_reason::batch};
static mesh_updates_t const _mesh_rebuild_updates = {
ui::mesh_update_reason::texture, ui::mesh_update_reason::vertex_data, ui::mesh_update_reason::index_data};
static mesh_data_updates_t const _vertex_data_rebuild_updates = {ui::mesh_data_update_reason::data_count};
if (this->node_updates.and_test(_node_rebuild_updates) || this->mesh_updates.and_test(_mesh_rebuild_updates) ||
this->vertex_data_updates.and_test(_vertex_data_rebuild_updates) ||
this->index_data_updates.and_test(_vertex_data_rebuild_updates)) {
return ui::batch_building_type::rebuild;
}
if (this->node_updates.flags.any() || this->mesh_updates.flags.any() || this->vertex_data_updates.flags.any() ||
this->index_data_updates.flags.any()) {
return ui::batch_building_type::overwrite;
}
return ui::batch_building_type::none;
}
std::string yas::to_string(ui::node_update_reason const &reason) {
switch (reason) {
case ui::node_update_reason::geometry:
return "geometry";
case ui::node_update_reason::mesh:
return "mesh";
case ui::node_update_reason::collider:
return "collider";
case ui::node_update_reason::enabled:
return "enabled";
case ui::node_update_reason::batch:
return "batch";
case ui::node_update_reason::render_target:
return "render_target";
case ui::node_update_reason::children:
return "children";
case ui::node_update_reason::count:
return "count";
}
}
std::string yas::to_string(ui::batch_building_type const &type) {
switch (type) {
case ui::batch_building_type::rebuild:
return "rebuild";
case ui::batch_building_type::overwrite:
return "overwrite";
case ui::batch_building_type::none:
return "none";
}
}
std::string yas::to_string(ui::mesh_data_update_reason const &reason) {
switch (reason) {
case ui::mesh_data_update_reason::data_content:
return "data_content";
case ui::mesh_data_update_reason::data_count:
return "data_count";
case ui::mesh_data_update_reason::render_buffer:
return "render_buffer";
case ui::mesh_data_update_reason::count:
return "count";
}
}
std::string yas::to_string(ui::mesh_update_reason const &reason) {
switch (reason) {
case ui::mesh_update_reason::vertex_data:
return "vertex_data";
case ui::mesh_update_reason::index_data:
return "index_data";
case ui::mesh_update_reason::texture:
return "texture";
case ui::mesh_update_reason::primitive_type:
return "primitive_type";
case ui::mesh_update_reason::color:
return "color";
case ui::mesh_update_reason::use_mesh_color:
return "use_mesh_color";
case ui::mesh_update_reason::matrix:
return "matrix";
case ui::mesh_update_reason::count:
return "count";
}
}
std::ostream &operator<<(std::ostream &os, yas::ui::node_update_reason const &reason) {
os << to_string(reason);
return os;
}
std::ostream &operator<<(std::ostream &os, yas::ui::batch_building_type const &type) {
os << to_string(type);
return os;
}
std::ostream &operator<<(std::ostream &os, yas::ui::mesh_data_update_reason const &reason) {
os << to_string(reason);
return os;
}
std::ostream &operator<<(std::ostream &os, yas::ui::mesh_update_reason const &reason) {
os << to_string(reason);
return os;
}
std::ostream &operator<<(std::ostream &os, yas::ui::effect_update_reason const &value) {
os << to_string(value);
return os;
}
std::ostream &operator<<(std::ostream &os, yas::ui::effect_updates_t const &value) {
os << to_string(value);
return os;
}
#pragma mark -
std::string yas::to_string(ui::effect_update_reason const &reason) {
switch (reason) {
case ui::effect_update_reason::textures:
return "textures";
case ui::effect_update_reason::handler:
return "handler";
case ui::effect_update_reason::count:
return "count";
}
}
std::string yas::to_string(ui::effect_updates_t const &updates) {
std::vector<std::string> flag_texts;
auto each = make_fast_each(static_cast<std::size_t>(ui::effect_update_reason::count));
while (yas_each_next(each)) {
auto const value = static_cast<ui::effect_update_reason>(yas_each_index(each));
if (updates.test(value)) {
flag_texts.emplace_back(to_string(value));
}
}
return joined(flag_texts, "|");
}
| 35.02907
| 119
| 0.657095
|
objective-audio
|
31f25ebc84f723d81883b742fb6a4ae198d3e15e
| 849
|
cpp
|
C++
|
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
|
harshanu11/Love-Babbar-450-In-CSharp
|
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
|
[
"MIT"
] | null | null | null |
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
|
harshanu11/Love-Babbar-450-In-CSharp
|
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
|
[
"MIT"
] | null | null | null |
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
|
harshanu11/Love-Babbar-450-In-CSharp
|
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
|
[
"MIT"
] | null | null | null |
///*
// link: https://practice.geeksforgeeks.org/problems/parenthesis-checker2744/1
//
// ref: 3_string/16_balanced_paranthesis.cpp
//*/
//
//
//// ----------------------------------------------------------------------------------------------------------------------- //
//bool ispar(string x)
//{
// stack<char> s;
// for (char c : x) {
// if (c == '[' | c == '{' | c == '(') {
// s.push(c);
// }
// else {
// if (s.size() == 0) {
// return false;
// }
// else if (c == ']' && s.top() == '[') s.pop();
// else if (c == '}' && s.top() == '{') s.pop();
// else if (c == ')' && s.top() == '(') s.pop();
// else {
// return false;
// }
// }
// }
// return (s.size()) ? false : true;
//}
| 29.275862
| 127
| 0.294464
|
harshanu11
|
31fa920c4e936e21b2a65498e4fe02eaebabea0b
| 180
|
hpp
|
C++
|
Contract/EOS/payout/backup/dawn/config.hpp
|
flyq/dapp-rosetta
|
0b66f1798c68cd23211105cca363ae1e8eca6876
|
[
"MIT"
] | 21
|
2019-01-24T12:43:33.000Z
|
2021-12-20T02:03:22.000Z
|
Contract/EOS/payout/backup/dawn/config.hpp
|
flyq/dapp-rosetta
|
0b66f1798c68cd23211105cca363ae1e8eca6876
|
[
"MIT"
] | 1
|
2021-12-19T18:15:15.000Z
|
2022-02-09T04:50:32.000Z
|
Contract/EOS/payout/backup/dawn/config.hpp
|
flyq/dapp-rosetta
|
0b66f1798c68cd23211105cca363ae1e8eca6876
|
[
"MIT"
] | 13
|
2019-02-14T01:56:26.000Z
|
2020-09-25T02:52:18.000Z
|
#pragma once
#define EOS_SYMBOL S(4, EOS)
#define CTN_SYMBOL S(4, CTN)
#define TOKEN_SYMBOL CTN_SYMBOL
#define TOKEN_CONTRACT N(dacincubator)
const uint128_t MAGNITUDE = 1ll<<32;
| 25.714286
| 38
| 0.783333
|
flyq
|
31fc2b6f8b6de5b495c159665d76f617211ff59f
| 525
|
cpp
|
C++
|
src/main/cpp/commands/IntakePneumaticCommand.cpp
|
GHawk1124/apex-rapid-react-2022
|
c5b0c6be47e577dbda91046cd0e6713a82100dc6
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/cpp/commands/IntakePneumaticCommand.cpp
|
GHawk1124/apex-rapid-react-2022
|
c5b0c6be47e577dbda91046cd0e6713a82100dc6
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/cpp/commands/IntakePneumaticCommand.cpp
|
GHawk1124/apex-rapid-react-2022
|
c5b0c6be47e577dbda91046cd0e6713a82100dc6
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "commands/IntakePneumaticCommand.h"
IntakePneumaticCommand::IntakePneumaticCommand(IntakeSubsystem* subsystem)
: m_subsystem{subsystem} {
AddRequirements({subsystem});
}
void IntakePneumaticCommand::Execute() {
m_subsystem->toggleSolenoid();
}
bool IntakePneumaticCommand::IsFinished() {
return true;
}
| 27.631579
| 74
| 0.773333
|
GHawk1124
|
ee02766ed6384328bfdae557ed0707e100be17e3
| 1,677
|
cpp
|
C++
|
src/api/systeminfo.cpp
|
CommitteeOfZero/noidget
|
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
|
[
"MIT"
] | null | null | null |
src/api/systeminfo.cpp
|
CommitteeOfZero/noidget
|
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
|
[
"MIT"
] | null | null | null |
src/api/systeminfo.cpp
|
CommitteeOfZero/noidget
|
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
|
[
"MIT"
] | null | null | null |
#include "systeminfo.h"
#include "apihost.h"
#include <api/exception.h>
#include <QScriptValue>
#include <QScriptValueList>
#include <QProcessEnvironment>
namespace api {
SystemInfo::SystemInfo(ApiHost* parent) : QObject(parent) {}
SystemInfo::~SystemInfo() {}
void SystemInfo::setupScriptObject(QScriptValue& o) {
ApiHost::registerEnum<util::SystemInfo::OsFamily>(o);
}
/*^jsdoc
* Platform the program is currently running on.
* @method platform
* @memberof ng.systemInfo
* @static
* @returns {ng.systemInfo.OsFamily}
^jsdoc*/
util::SystemInfo::OsFamily SystemInfo::platform() const {
return util::SystemInfo::platform();
}
/*^jsdoc
* Is the installer a Windows build running under Wine?
* @method isWine
* @memberof ng.systemInfo
* @static
* @returns {boolean}
^jsdoc*/
bool SystemInfo::isWine() const { return util::SystemInfo::isWine(); }
/*^jsdoc
* Is a process with the given name running (besides the installer application itself)?
*
* `processName` is **case sensitive**.
*
* @method isProcessRunning
* @memberof ng.systemInfo
* @static
* @param {string} processName
* @returns {boolean}
^jsdoc*/
bool SystemInfo::isProcessRunning(const QString& processName) const {
return util::SystemInfo::isProcessRunning(processName);
}
/*^jsdoc
* Get an environment variable
*
* Note we also have such functionality in {@link ng.fs.Fs#expandedPath}
*
* @method getEnv
* @memberof ng.systemInfo
* @static
* @param {string} name
* @returns {string} Value (empty if not set)
^jsdoc*/
QString SystemInfo::getEnv(const QString& name) const {
return QProcessEnvironment::systemEnvironment().value(name);
}
} // namespace api
| 24.661765
| 87
| 0.717352
|
CommitteeOfZero
|
ee07604693912d01e39210b9cd403747b98e8ec8
| 546
|
cpp
|
C++
|
problems/cf_1453_b.cpp
|
datasakura/informatika
|
71272271931b610f89eaf85ab89c199758d4a032
|
[
"MIT"
] | null | null | null |
problems/cf_1453_b.cpp
|
datasakura/informatika
|
71272271931b610f89eaf85ab89c199758d4a032
|
[
"MIT"
] | null | null | null |
problems/cf_1453_b.cpp
|
datasakura/informatika
|
71272271931b610f89eaf85ab89c199758d4a032
|
[
"MIT"
] | 1
|
2020-10-01T06:23:52.000Z
|
2020-10-01T06:23:52.000Z
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
vector<int> a(n);
for (int& i : a)
cin >> i;
long long ans0 = 0;
for (int i = 1; i < n; i++)
ans0 += abs(a[i] - a[i - 1]);
long long ans = ans0 - max(abs(a[1] - a[0]), abs(a[n - 1] - a[n - 2]));
for (int i = 2; i < n; i++) {
ans = min(ans, ans0
- abs(a[i - 0] - a[i - 1])
- abs(a[i - 1] - a[i - 2])
+ abs(a[i - 0] - a[i - 2]));
}
cout << ans << endl;
}
return 0;
}
| 18.827586
| 73
| 0.454212
|
datasakura
|
ee0c62cf6e3dc93ec85c02d35a6db9ea93175f5f
| 370
|
cpp
|
C++
|
codes/HDU/hdu4969.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/HDU/hdu4969.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/HDU/hdu4969.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int main () {
int cas;
double v1, v2, r, d;
scanf("%d", &cas);
while (cas--) {
scanf("%lf%lf%lf%lf", &v1, &v2, &r, &d);
double t = r / v1 * asin(v1 / v2);
double l = t * v2;
printf("%s\n", l > d ? "Why give up treatment" : "Wake up to code");
}
return 0;
}
| 17.619048
| 70
| 0.562162
|
JeraKrs
|
ee153f9c0c41b83f72f69abc8d043bd57c568509
| 6,206
|
hpp
|
C++
|
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
|
lkersting/SCR-2123
|
06ae3d92998664a520dc6a271809a5aeffe18f72
|
[
"BSD-3-Clause"
] | null | null | null |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_SimulationPhotonProperties.hpp
//! \author Alex Robinson, Luke Kersting
//! \brief Simulation photon properties class decl.
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP
#define MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP
// FRENSIE Includes
#include "MonteCarlo_ParticleModeType.hpp"
#include "MonteCarlo_IncoherentModelType.hpp"
namespace MonteCarlo{
/*! The simulation properties class
* \todo Modify XML parser to handle all options in this class. Use this class
* in all parts of code that require runtime configuration.
*/
class SimulationPhotonProperties
{
public:
//! Set the minimum photon energy (MeV)
static void setMinPhotonEnergy( const double energy );
//! Return the minimum photon energy (MeV)
static double getMinPhotonEnergy();
//! Return the absolute minimum photon energy (MeV)
static double getAbsoluteMinPhotonEnergy();
//! Set the maximum photon energy (MeV)
static void setMaxPhotonEnergy( const double energy );
//! Return the maximum photon energy (MeV)
static double getMaxPhotonEnergy();
//! Return the absolute maximum photon energy (MeV)
static double getAbsoluteMaxPhotonEnergy();
//! Set the Kahn sampling cutoff energy (MeV)
static void setKahnSamplingCutoffEnergy( const double energy );
//! Return the Kahn sampling cutoff energy (MeV)
static double getKahnSamplingCutoffEnergy();
//! Return the absolute min Kahn sampling cutoff energy (MeV)
static double getAbsoluteMinKahnSamplingCutoffEnergy();
//! Set the number of photon hash grid bins
static void setNumberOfPhotonHashGridBins( const unsigned bins );
//! Get the number of photon hash grid bins
static unsigned getNumberOfPhotonHashGridBins();
//! Set the incoherent model type
static void setIncoherentModelType( const IncoherentModelType model );
//! Return the incohernt model
static IncoherentModelType getIncoherentModelType();
//! Set atomic relaxation mode to off (on by default)
static void setAtomicRelaxationModeOff();
//! Return if atomic relaxation mode is on
static bool isAtomicRelaxationModeOn();
//! Set detailed pair production mode to on (off by default)
static void setDetailedPairProductionModeOn();
//! Return if detailed pair production mode is on
static bool isDetailedPairProductionModeOn();
//! Set photonuclear interaction mode to on (off by default)
static void setPhotonuclearInteractionModeOn();
//! Return if photonuclear interaction mode is on
static bool isPhotonuclearInteractionModeOn();
private:
// The absolute minimum photon energy (MeV)
static const double absolute_min_photon_energy;
// The minimum photon energy (MeV)
static double min_photon_energy;
// The maximum photon energy (MeV)
static double max_photon_energy;
// The absolute maximum photon energy
static const double absolute_max_photon_energy;
// The Kahn sampling cutoff energy (MeV)
static double kahn_sampling_cutoff_energy;
// The absolute min Kahn sampling cutoff energy (MeV)
static const double absolute_min_kahn_sampling_cutoff_energy;
// The number of photon hash grid bins
static unsigned num_photon_hash_grid_bins;
// The incoherent model
static IncoherentModelType incoherent_model_type;
// The atomic relaxation mode (true = on - default, false = off)
static bool atomic_relaxation_mode_on;
// The detailed pair production mode (true = on, false = off - default)
static bool detailed_pair_production_mode_on;
// The photonuclear interaction mode (true = on, false = off - default)
static bool photonuclear_interaction_mode_on;
};
// Return the minimum photon energy (MeV)
inline double SimulationPhotonProperties::getMinPhotonEnergy()
{
return SimulationPhotonProperties::min_photon_energy;
}
// Return the absolute minimum photon energy (MeV)
inline double SimulationPhotonProperties::getAbsoluteMinPhotonEnergy()
{
return SimulationPhotonProperties::absolute_min_photon_energy;
}
// Return the maximum photon energy (MeV) - cannot be set at runtime
inline double SimulationPhotonProperties::getMaxPhotonEnergy()
{
return SimulationPhotonProperties::max_photon_energy;
}
// Return the absolute maximum photon energy (MeV)
inline double SimulationPhotonProperties::getAbsoluteMaxPhotonEnergy()
{
return SimulationPhotonProperties::absolute_max_photon_energy;
}
// Return the Kahn sampling cutoff energy (MeV)
inline double SimulationPhotonProperties::getKahnSamplingCutoffEnergy()
{
return SimulationPhotonProperties::kahn_sampling_cutoff_energy;
}
// Return the absolute min Kahn sampling cutoff energy (MeV)
inline double SimulationPhotonProperties::getAbsoluteMinKahnSamplingCutoffEnergy()
{
return SimulationPhotonProperties::absolute_min_kahn_sampling_cutoff_energy;
}
// Get the number of photon hash grid bins
inline unsigned SimulationPhotonProperties::getNumberOfPhotonHashGridBins()
{
return SimulationPhotonProperties::num_photon_hash_grid_bins;
}
// Return the incohernt model
inline IncoherentModelType SimulationPhotonProperties::getIncoherentModelType()
{
return SimulationPhotonProperties::incoherent_model_type;
}
// Return if atomic relaxation mode is on
inline bool SimulationPhotonProperties::isAtomicRelaxationModeOn()
{
return SimulationPhotonProperties::atomic_relaxation_mode_on;
}
// Return if detailed pair production mode is on
inline bool SimulationPhotonProperties::isDetailedPairProductionModeOn()
{
return SimulationPhotonProperties::detailed_pair_production_mode_on;
}
// Return if photonuclear interaction mode is on
inline bool SimulationPhotonProperties::isPhotonuclearInteractionModeOn()
{
return SimulationPhotonProperties::photonuclear_interaction_mode_on;
}
} // end MonteCarlo namespace
#endif // end MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_SimulationPhotonProperties.cpp
//---------------------------------------------------------------------------//
| 32.15544
| 82
| 0.753626
|
lkersting
|
ee16e13195ca2c8b41142afcf549e62fc88c8c89
| 1,184
|
cpp
|
C++
|
mr/iza810/raspi_utility/src/pigpiod.cpp
|
Kitasola/robocon_2019b
|
43acfa88fb49ddeb7ec9e15976854936a71e92b6
|
[
"MIT"
] | 5
|
2020-01-24T08:05:01.000Z
|
2020-08-03T04:51:52.000Z
|
mr/iza810/raspi_utility/src/pigpiod.cpp
|
Kitasola/robocon_2019b
|
43acfa88fb49ddeb7ec9e15976854936a71e92b6
|
[
"MIT"
] | null | null | null |
mr/iza810/raspi_utility/src/pigpiod.cpp
|
Kitasola/robocon_2019b
|
43acfa88fb49ddeb7ec9e15976854936a71e92b6
|
[
"MIT"
] | 1
|
2020-07-15T05:43:48.000Z
|
2020-07-15T05:43:48.000Z
|
#include "../include/pigpiod.hpp"
#include <pigpiod_if2.h>
using namespace arrc_raspi;
Pigpiod::Pigpiod() {
gpio_handle_ = pigpio_start(const_cast<char *>(PIGPIOD_HOST),
const_cast<char *>(PIGPIOD_PORT));
}
void Pigpiod::write(int pin, int level) {
gpio_write(gpio_handle_, pin, level);
}
int Pigpiod::read(int pin) { return gpio_read(gpio_handle_, pin); }
void Pigpiod::set(int pin, int mode, int init) {
if (mode == IN) {
set_mode(gpio_handle_, pin, PI_INPUT);
if (init == PULL_UP) {
set_pull_up_down(gpio_handle_, pin, PI_PUD_UP);
} else if (init == PULL_DOWN) {
set_pull_up_down(gpio_handle_, pin, PI_PUD_DOWN);
} else if (init == PULL_OFF) {
set_pull_up_down(gpio_handle_, pin, PI_PUD_OFF);
}
} else if (mode == OUT) {
set_mode(gpio_handle_, pin, PI_OUTPUT);
gpio_write(gpio_handle_, pin, init);
}
}
int Pigpiod::checkHandle() { return gpio_handle_; }
bool Pigpiod::checkInit() {
if (gpio_handle_ < 0) {
return false;
} else {
return true;
}
}
void Pigpiod::delay(double micro_sec) { time_sleep(micro_sec / 1000000); }
Pigpiod::~Pigpiod() { pigpio_stop(gpio_handle_); }
| 25.73913
| 74
| 0.658784
|
Kitasola
|
ee1994105c0e9e1d3518b9991e8e425f342516be
| 1,313
|
cpp
|
C++
|
designpattern/AbstractFactory.cpp
|
armsword/CppSkills
|
162a83f78d3d2c8607559e03d683c90d3198cab1
|
[
"MIT"
] | 1
|
2015-04-29T14:32:38.000Z
|
2015-04-29T14:32:38.000Z
|
designpattern/AbstractFactory.cpp
|
armsword/CppSkills
|
162a83f78d3d2c8607559e03d683c90d3198cab1
|
[
"MIT"
] | null | null | null |
designpattern/AbstractFactory.cpp
|
armsword/CppSkills
|
162a83f78d3d2c8607559e03d683c90d3198cab1
|
[
"MIT"
] | null | null | null |
/* 工厂方法模式也有缺点,每增加一种产品,就需要增加一个对象的工厂。如果这家公司发展迅速,推出了很多新的处理器核,那么就要新开设相应的新工厂。在C++实现中,就是要定义一个个的工厂类。显然,相比简单工厂模式,工厂方法模式需要更多的类定义。
*/
/*
既然有了简单工厂模式和工厂方法模式,为什么还要有抽象工厂模式呢?它到底有什么作用呢?还是举例子,这家公司的技术不断进步,不仅可以生产单核处理器,也能生产多喝处理器。现在简单工厂模式和工厂方法模式都鞭长莫及。抽象工厂模式登场了。它的定义为提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
*/
// 单核
class SingleCore
{
public:
virtual void Show() = 0;
};
class SingleCoreA : public SingleCore
{
public:
void Show() {cout << "Single Core A"<<endl;}
};
class SingleCoreB : public SingleCore
{
public:
void Show() {cout << "Single Core B"<<endl;}
};
// 多核
class MultiCore
{
public:
virtual void Show() = 0;
};
class MultiCoreA : public MultiCore
{
public:
void Show() {cout<<"Multi Core A"<<endl;}
};
class MultiCoreB : public MultiCore
{
public:
void Show() {cout<<"Multi Core B"<<endl;}
};
// 工厂
class CoreFactory
{
public:
virtual SingleCore* CreateSingleCore() = 0;
virtual MultiCore* CreateMultiCore() = 0;
};
// 工厂A,专门用来生产A型号的处理器
class FactoryA : public CoreFactory
{
public:
SingleCore* CreateSingleCore() {return new SingleCoreA();}
MultiCore* CreateMultiCore() {return new MultiCoreA();}
};
// 工厂B,专门用来生产B型号的处理器
class FactoryB : public CoreFactory
{
public:
SingleCore* CreateSingleCore() {return new SingleCoreB();}
MultiCore* CreateMultiCore() {return new MultiCoreB();}
};
| 19.308824
| 156
| 0.722011
|
armsword
|
ee1b41e2b6c7a61390118b514e29f7220f8dade9
| 4,301
|
hpp
|
C++
|
src/vlGraphics/DistanceLODEvaluator.hpp
|
pasenau/VisualizationLibrary
|
2fcf1808475aebd4862f40377754be62a7f77a52
|
[
"BSD-2-Clause"
] | 1
|
2017-06-29T18:25:11.000Z
|
2017-06-29T18:25:11.000Z
|
src/vlGraphics/DistanceLODEvaluator.hpp
|
pasenau/VisualizationLibrary
|
2fcf1808475aebd4862f40377754be62a7f77a52
|
[
"BSD-2-Clause"
] | null | null | null |
src/vlGraphics/DistanceLODEvaluator.hpp
|
pasenau/VisualizationLibrary
|
2fcf1808475aebd4862f40377754be62a7f77a52
|
[
"BSD-2-Clause"
] | 1
|
2021-01-01T10:43:33.000Z
|
2021-01-01T10:43:33.000Z
|
/**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef DistanceLODEvaluator_INCLUDE_ONCE
#define DistanceLODEvaluator_INCLUDE_ONCE
#include <vlGraphics/Actor.hpp>
namespace vl
{
//-----------------------------------------------------------------------------
// DistanceLODEvaluator
//-----------------------------------------------------------------------------
/**
* A LODEvaluator that computes the appropriate LOD based on the distance of an
* Actor from the Camera.
*
* \sa
* - LODEvaluator
* - PixelLODEvaluator
*/
class DistanceLODEvaluator: public LODEvaluator
{
VL_INSTRUMENT_CLASS(vl::DistanceLODEvaluator, LODEvaluator)
public:
DistanceLODEvaluator()
{
VL_DEBUG_SET_OBJECT_NAME()
}
virtual int evaluate(Actor* actor, Camera* camera)
{
if (mDistanceRangeSet.empty())
return 0;
vec3 center = actor->transform() ? actor->transform()->worldMatrix() * actor->lod(0)->boundingBox().center() : actor->lod(0)->boundingBox().center();
double dist = (camera->modelingMatrix().getT() - center).length();
// we assume the distances are sorted in increasing order
int i=0;
for(; i<(int)mDistanceRangeSet.size(); ++i)
{
if (dist<mDistanceRangeSet[i])
return i;
}
return i; // == mDistanceRangeSet.size()
}
const std::vector<double>& distanceRangeSet() const { return mDistanceRangeSet; }
std::vector<double>& distanceRangeSet() { return mDistanceRangeSet; }
protected:
std::vector<double> mDistanceRangeSet;
};
}
#endif
| 48.875
| 156
| 0.468961
|
pasenau
|
ee2c4a08c044cded2c9bd8d6a0a2fadb397e35ba
| 9,547
|
cpp
|
C++
|
src/frontends/lean/operator_info.cpp
|
codyroux/lean0.1
|
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
|
[
"Apache-2.0"
] | 1
|
2019-06-08T15:02:03.000Z
|
2019-06-08T15:02:03.000Z
|
src/frontends/lean/operator_info.cpp
|
codyroux/lean0.1
|
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
|
[
"Apache-2.0"
] | null | null | null |
src/frontends/lean/operator_info.cpp
|
codyroux/lean0.1
|
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "util/rc.h"
#include "library/io_state_stream.h"
#include "frontends/lean/operator_info.h"
#include "frontends/lean/frontend.h"
namespace lean {
/** \brief Actual implementation of operator_info */
struct operator_info::imp {
void dealloc() { delete this; }
MK_LEAN_RC();
fixity m_fixity;
unsigned m_precedence;
list<name> m_op_parts; // operator parts, > 1 only if the operator is mixfix.
list<expr> m_exprs; // possible interpretations for the operator.
imp(name const & op, fixity f, unsigned p):
m_rc(1), m_fixity(f), m_precedence(p), m_op_parts(cons(op, list<name>())) {}
imp(unsigned num_parts, name const * parts, fixity f, unsigned p):
m_rc(1), m_fixity(f), m_precedence(p), m_op_parts(to_list<name const *>(parts, parts + num_parts)) {
lean_assert(num_parts > 0);
}
imp(imp const & s):
m_rc(1), m_fixity(s.m_fixity), m_precedence(s.m_precedence), m_op_parts(s.m_op_parts), m_exprs(s.m_exprs) {
}
bool is_eq(imp const & other) const {
return
m_fixity == other.m_fixity &&
m_precedence == other.m_precedence &&
m_op_parts == other.m_op_parts;
}
};
operator_info::operator_info(imp * p):m_ptr(p) {}
operator_info::operator_info(operator_info const & info):m_ptr(info.m_ptr) { if (m_ptr) m_ptr->inc_ref(); }
operator_info::operator_info(operator_info && info):m_ptr(info.m_ptr) { info.m_ptr = nullptr; }
operator_info::~operator_info() { if (m_ptr) m_ptr->dec_ref(); }
operator_info & operator_info::operator=(operator_info const & s) { LEAN_COPY_REF(s); }
operator_info & operator_info::operator=(operator_info && s) { LEAN_MOVE_REF(s); }
void operator_info::add_expr(expr const & d) { lean_assert(m_ptr); m_ptr->m_exprs = cons(d, m_ptr->m_exprs); }
bool operator_info::is_overloaded() const { return m_ptr && !is_nil(m_ptr->m_exprs) && !is_nil(cdr(m_ptr->m_exprs)); }
list<expr> const & operator_info::get_denotations() const { lean_assert(m_ptr); return m_ptr->m_exprs; }
fixity operator_info::get_fixity() const { lean_assert(m_ptr); return m_ptr->m_fixity; }
unsigned operator_info::get_precedence() const { lean_assert(m_ptr); return m_ptr->m_precedence; }
name const & operator_info::get_op_name() const { lean_assert(m_ptr); return car(m_ptr->m_op_parts); }
list<name> const & operator_info::get_op_name_parts() const { lean_assert(m_ptr); return m_ptr->m_op_parts; }
bool operator_info::is_safe_ascii() const {
auto l = get_op_name_parts();
return std::all_of(l.begin(), l.end(), [](name const & p) { return p.is_safe_ascii(); });
}
operator_info operator_info::copy() const { return operator_info(new imp(*m_ptr)); }
bool operator==(operator_info const & op1, operator_info const & op2) {
if ((op1.m_ptr == nullptr) != (op2.m_ptr == nullptr))
return false;
if (op1.m_ptr)
return op1.m_ptr->is_eq(*(op2.m_ptr));
else
return true;
}
operator_info infix(name const & op, unsigned precedence) {
return operator_info(new operator_info::imp(op, fixity::Infix, precedence));
}
operator_info infixr(name const & op, unsigned precedence) {
return operator_info(new operator_info::imp(op, fixity::Infixr, precedence));
}
operator_info infixl(name const & op, unsigned precedence) {
return operator_info(new operator_info::imp(op, fixity::Infixl, precedence));
}
operator_info prefix(name const & op, unsigned precedence) {
return operator_info(new operator_info::imp(op, fixity::Prefix, precedence));
}
operator_info postfix(name const & op, unsigned precedence) {
return operator_info(new operator_info::imp(op, fixity::Postfix, precedence));
}
operator_info mixfixl(unsigned num_parts, name const * parts, unsigned precedence) {
lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixl, precedence));
}
operator_info mixfixr(unsigned num_parts, name const * parts, unsigned precedence) {
lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixr, precedence));
}
operator_info mixfixc(unsigned num_parts, name const * parts, unsigned precedence) {
lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixc, precedence));
}
operator_info mixfixo(unsigned num_parts, name const * parts, unsigned precedence) {
lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixo, precedence));
}
char const * to_string(fixity f) {
switch (f) {
case fixity::Infix: return "infix";
case fixity::Infixl: return "infixl";
case fixity::Infixr: return "infixr";
case fixity::Prefix: return "prefix";
case fixity::Postfix: return "postfix";
case fixity::Mixfixl: return "mixfixl";
case fixity::Mixfixr: return "mixfixr";
case fixity::Mixfixc: return "mixfixc";
case fixity::Mixfixo: return "mixfixo";
}
lean_unreachable(); // LCOV_EXCL_LINE
}
format pp(operator_info const & o) {
format r;
switch (o.get_fixity()) {
case fixity::Infix:
case fixity::Infixl:
case fixity::Infixr:
r = highlight_command(format(to_string(o.get_fixity())));
if (o.get_precedence() > 1)
r += format{space(), format(o.get_precedence())};
r += format{space(), format(o.get_op_name())};
return r;
case fixity::Prefix:
case fixity::Postfix:
case fixity::Mixfixl:
case fixity::Mixfixr:
case fixity::Mixfixc:
case fixity::Mixfixo:
r = highlight_command(format("notation"));
if (o.get_precedence() > 1)
r += format{space(), format(o.get_precedence())};
switch (o.get_fixity()) {
case fixity::Prefix:
r += format{space(), format(o.get_op_name()), space(), format("_")};
return r;
case fixity::Postfix:
r += format{space(), format("_"), space(), format(o.get_op_name())};
return r;
case fixity::Mixfixl:
for (auto p : o.get_op_name_parts())
r += format{space(), format(p), space(), format("_")};
return r;
case fixity::Mixfixr:
for (auto p : o.get_op_name_parts())
r += format{space(), format("_"), space(), format(p)};
return r;
case fixity::Mixfixc: {
auto parts = o.get_op_name_parts();
r += format{space(), format(head(parts))};
for (auto p : tail(parts))
r += format{space(), format("_"), space(), format(p)};
return r;
}
case fixity::Mixfixo:
for (auto p : o.get_op_name_parts())
r += format{space(), format("_"), space(), format(p)};
r += format{space(), format("_")};
return r;
default: lean_unreachable(); // LCOV_EXCL_LINE
}
}
lean_unreachable(); // LCOV_EXCL_LINE
}
char const * notation_declaration::keyword() const {
return to_string(m_op.get_fixity());
}
void notation_declaration::write(serializer & s) const {
auto parts = m_op.get_op_name_parts();
s << "Notation" << length(parts);
for (auto n : parts)
s << n;
s << static_cast<char>(m_op.get_fixity()) << m_op.get_precedence() << m_expr;
}
static void read_notation(environment const & env, io_state const & ios, deserializer & d) {
buffer<name> parts;
unsigned num = d.read_unsigned();
for (unsigned i = 0; i < num; i++)
parts.push_back(read_name(d));
fixity fx = static_cast<fixity>(d.read_char());
unsigned p = d.read_unsigned();
expr e = read_expr(d);
switch (fx) {
case fixity::Infix: lean_assert(parts.size() == 1); add_infix(env, ios, parts[0], p, e); return;
case fixity::Infixl: lean_assert(parts.size() == 1); add_infixl(env, ios, parts[0], p, e); return;
case fixity::Infixr: lean_assert(parts.size() == 1); add_infixr(env, ios, parts[0], p, e); return;
case fixity::Prefix: lean_assert(parts.size() == 1); add_prefix(env, ios, parts[0], p, e); return;
case fixity::Postfix: lean_assert(parts.size() == 1); add_postfix(env, ios, parts[0], p, e); return;
case fixity::Mixfixl: add_mixfixl(env, ios, parts.size(), parts.data(), p, e); return;
case fixity::Mixfixr: add_mixfixr(env, ios, parts.size(), parts.data(), p, e); return;
case fixity::Mixfixc: add_mixfixc(env, ios, parts.size(), parts.data(), p, e); return;
case fixity::Mixfixo: add_mixfixo(env, ios, parts.size(), parts.data(), p, e); return;
}
}
static object_cell::register_deserializer_fn notation_ds("Notation", read_notation);
std::ostream & operator<<(std::ostream & out, operator_info const & o) {
out << pp(o);
return out;
}
io_state_stream const & operator<<(io_state_stream const & out, operator_info const & o) {
out.get_stream() << mk_pair(pp(o), out.get_options());
return out;
}
char const * alias_declaration::keyword() const { return "alias"; }
void alias_declaration::write(serializer & s) const { s << "alias" << m_name << m_expr; }
static void read_alias(environment const & env, io_state const &, deserializer & d) {
name n = read_name(d);
expr e = read_expr(d);
add_alias(env, n, e);
}
static object_cell::register_deserializer_fn add_alias_ds("alias", read_alias);
}
| 41.150862
| 124
| 0.658531
|
codyroux
|
0c524a156ce45e1050bf490928af9185b4a1197a
| 1,096
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_FeedingTrough_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass FeedingTrough.FeedingTrough_C
// 0x000C (0x0EC0 - 0x0EB4)
class AFeedingTrough_C : public AFeedingTroughBaseBP_C
{
public:
unsigned char UnknownData00[0x4]; // 0x0EB4(0x0004) MISSED OFFSET
class UPrimalInventoryBP_FeedingTrough_C* PrimalInventoryBP_FeedingTrough_C1; // 0x0EB8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass FeedingTrough.FeedingTrough_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_FeedingTrough(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 26.095238
| 179
| 0.603102
|
2bite
|
0c5579e83da9607ae2c95691f28f89ca1f057427
| 5,490
|
cpp
|
C++
|
src/qt/qtbase/examples/qpa/windows/window.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T15:47:35.000Z
|
2020-04-30T15:47:35.000Z
|
src/qt/qtbase/examples/qpa/windows/window.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/examples/qpa/windows/window.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "window.h"
#include <private/qguiapplication_p.h>
#include <QBackingStore>
#include <QPainter>
static int colorIndexId = 0;
QColor colorTable[] =
{
QColor("#f09f8f"),
QColor("#a2bff2"),
QColor("#c0ef8f")
};
Window::Window(QScreen *screen)
: QWindow(screen)
, m_backgroundColorIndex(colorIndexId++)
{
initialize();
}
Window::Window(QWindow *parent)
: QWindow(parent)
, m_backgroundColorIndex(colorIndexId++)
{
initialize();
}
void Window::initialize()
{
if (parent())
setGeometry(QRect(160, 120, 320, 240));
else {
setFlags(flags() | Qt::WindowTitleHint | Qt::WindowSystemMenuHint
| Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
const QSize baseSize = QSize(640, 480);
setGeometry(QRect(geometry().topLeft(), baseSize));
setSizeIncrement(QSize(10, 10));
setBaseSize(baseSize);
setMinimumSize(QSize(240, 160));
setMaximumSize(QSize(800, 600));
}
create();
m_backingStore = new QBackingStore(this);
m_image = QImage(geometry().size(), QImage::Format_RGB32);
m_image.fill(colorTable[m_backgroundColorIndex % (sizeof(colorTable) / sizeof(colorTable[0]))].rgba());
m_lastPos = QPoint(-1, -1);
m_renderTimer = 0;
}
void Window::mousePressEvent(QMouseEvent *event)
{
m_lastPos = event->pos();
}
void Window::mouseMoveEvent(QMouseEvent *event)
{
if (m_lastPos != QPoint(-1, -1)) {
QPainter p(&m_image);
p.setRenderHint(QPainter::Antialiasing);
p.drawLine(m_lastPos, event->pos());
m_lastPos = event->pos();
scheduleRender();
}
}
void Window::mouseReleaseEvent(QMouseEvent *event)
{
if (m_lastPos != QPoint(-1, -1)) {
QPainter p(&m_image);
p.setRenderHint(QPainter::Antialiasing);
p.drawLine(m_lastPos, event->pos());
m_lastPos = QPoint(-1, -1);
scheduleRender();
}
}
void Window::exposeEvent(QExposeEvent *)
{
scheduleRender();
}
void Window::resizeEvent(QResizeEvent *)
{
QImage old = m_image;
int width = qMax(geometry().width(), old.width());
int height = qMax(geometry().height(), old.height());
if (width > old.width() || height > old.height()) {
m_image = QImage(width, height, QImage::Format_RGB32);
m_image.fill(colorTable[(m_backgroundColorIndex) % (sizeof(colorTable) / sizeof(colorTable[0]))].rgba());
QPainter p(&m_image);
p.drawImage(0, 0, old);
}
scheduleRender();
}
void Window::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Backspace:
m_text.chop(1);
break;
case Qt::Key_Enter:
case Qt::Key_Return:
m_text.append('\n');
break;
default:
m_text.append(event->text());
break;
}
scheduleRender();
}
void Window::scheduleRender()
{
if (!m_renderTimer)
m_renderTimer = startTimer(1);
}
void Window::timerEvent(QTimerEvent *)
{
if (isExposed())
render();
killTimer(m_renderTimer);
m_renderTimer = 0;
}
void Window::render()
{
QRect rect(QPoint(), geometry().size());
m_backingStore->resize(rect.size());
m_backingStore->beginPaint(rect);
QPaintDevice *device = m_backingStore->paintDevice();
QPainter p(device);
p.drawImage(0, 0, m_image);
QFont font;
font.setPixelSize(32);
p.setFont(font);
p.drawText(rect, 0, m_text);
m_backingStore->endPaint();
m_backingStore->flush(rect);
}
| 27.178218
| 113
| 0.645902
|
power-electro
|
0c5657582846cb797ddcaa56ac88e7b01bed3456
| 5,256
|
cpp
|
C++
|
src/propagation.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
src/propagation.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
src/propagation.cpp
|
cgilmour/dd-opentracing-cpp
|
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
|
[
"Apache-2.0"
] | null | null | null |
#include "propagation.h"
#include <algorithm>
namespace ot = opentracing;
namespace datadog {
namespace opentracing {
namespace {
// Header names for trace data.
const std::string trace_id_header = "x-datadog-trace-id";
const std::string parent_id_header = "x-datadog-parent-id";
// Header name prefix for OpenTracing baggage. Should be "ot-baggage-" to support OpenTracing
// interop.
const ot::string_view baggage_prefix = "ot-baggage-";
// Does what it says on the tin. Just looks at each char, so don't try and use this on
// unicode strings, only used for comparing HTTP header names.
// Rolled my own because I don't want to import all of libboost for a couple of functions!
bool equals_ignore_case(const std::string &a, const std::string &b) {
return std::equal(a.begin(), a.end(), b.begin(), b.end(),
[](char a, char b) { return tolower(a) == tolower(b); });
}
// Checks to see if the given string has the given prefix.
bool has_prefix(const std::string &str, const std::string &prefix) {
if (str.size() < prefix.size()) {
return false;
}
auto result = std::mismatch(prefix.begin(), prefix.end(), str.begin());
return result.first == prefix.end();
}
} // namespace
SpanContext::SpanContext(uint64_t id, uint64_t trace_id,
std::unordered_map<std::string, std::string> &&baggage)
: id_(id), trace_id_(trace_id), baggage_(std::move(baggage)) {}
SpanContext::SpanContext(SpanContext &&other)
: id_(other.id_), trace_id_(other.trace_id_), baggage_(std::move(other.baggage_)) {}
SpanContext &SpanContext::operator=(SpanContext &&other) {
std::lock_guard<std::mutex> lock{mutex_};
id_ = other.id_;
trace_id_ = other.trace_id_;
baggage_ = std::move(other.baggage_);
return *this;
}
void SpanContext::ForeachBaggageItem(
std::function<bool(const std::string &, const std::string &)> f) const {
for (const auto &baggage_item : baggage_) {
if (!f(baggage_item.first, baggage_item.second)) {
return;
}
}
}
uint64_t SpanContext::id() const {
// Not locked, since id_ never modified.
return id_;
}
uint64_t SpanContext::trace_id() const {
// Not locked, since trace_id_ never modified.
return trace_id_;
}
void SpanContext::setBaggageItem(ot::string_view key, ot::string_view value) noexcept try {
std::lock_guard<std::mutex> lock{mutex_};
baggage_.emplace(key, value);
} catch (const std::bad_alloc &) {
}
std::string SpanContext::baggageItem(ot::string_view key) const {
std::lock_guard<std::mutex> lock{mutex_};
auto lookup = baggage_.find(key);
if (lookup != baggage_.end()) {
return lookup->second;
}
return {};
}
SpanContext SpanContext::withId(uint64_t id) const {
std::lock_guard<std::mutex> lock{mutex_};
auto baggage = baggage_; // (Shallow) copy baggage.
return std::move(SpanContext{id, trace_id_, std::move(baggage)});
}
ot::expected<void> SpanContext::serialize(const ot::TextMapWriter &writer) const {
std::lock_guard<std::mutex> lock{mutex_};
auto result = writer.Set(trace_id_header, std::to_string(trace_id_));
if (!result) {
return result;
}
// Yes, "id" does go to "parent id" since this is the point where subsequent Spans getting this
// context become children.
result = writer.Set(parent_id_header, std::to_string(id_));
if (!result) {
return result;
}
for (auto baggage_item : baggage_) {
std::string key = std::string(baggage_prefix) + baggage_item.first;
result = writer.Set(key, baggage_item.second);
if (!result) {
return result;
}
}
return result;
}
ot::expected<std::unique_ptr<ot::SpanContext>> SpanContext::deserialize(
const ot::TextMapReader &reader) try {
uint64_t trace_id, parent_id;
bool trace_id_set = false;
bool parent_id_set = false;
std::unordered_map<std::string, std::string> baggage;
auto result =
reader.ForeachKey([&](ot::string_view key, ot::string_view value) -> ot::expected<void> {
try {
if (equals_ignore_case(key, trace_id_header)) {
trace_id = std::stoull(value);
trace_id_set = true;
} else if (equals_ignore_case(key, parent_id_header)) {
parent_id = std::stoull(value);
parent_id_set = true;
} else if (has_prefix(key, baggage_prefix)) {
baggage.emplace(std::string{std::begin(key) + baggage_prefix.size(), std::end(key)},
value);
}
} catch (const std::invalid_argument &ia) {
return ot::make_unexpected(ot::span_context_corrupted_error);
} catch (const std::out_of_range &oor) {
return ot::make_unexpected(ot::span_context_corrupted_error);
}
return {};
});
if (!result) { // "if unexpected", hence "{}" from above is fine.
return ot::make_unexpected(result.error());
}
if (!trace_id_set || !parent_id_set) {
return ot::make_unexpected(ot::span_context_corrupted_error);
}
return std::move(
std::unique_ptr<ot::SpanContext>{new SpanContext{parent_id, trace_id, std::move(baggage)}});
} catch (const std::bad_alloc &) {
return ot::make_unexpected(std::make_error_code(std::errc::not_enough_memory));
}
} // namespace opentracing
} // namespace datadog
| 33.692308
| 98
| 0.671994
|
cgilmour
|
0c5b8a12c288cd2d0fd22368b928cebf0c476b3a
| 4,213
|
cpp
|
C++
|
owGameWMO/WMO_PortalsController.cpp
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | null | null | null |
owGameWMO/WMO_PortalsController.cpp
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | null | null | null |
owGameWMO/WMO_PortalsController.cpp
|
adan830/OpenWow
|
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
|
[
"Apache-2.0"
] | 1
|
2020-05-11T13:32:49.000Z
|
2020-05-11T13:32:49.000Z
|
#include "stdafx.h"
// Include
#include "WMO.h"
#include "WMO_Base_Instance.h"
// General
#include "WMO_PortalsController.h"
// Additional
#include "WMO_Group_Instance.h"
CWMO_PortalsController::CWMO_PortalsController(const WMO* _parentWMO) :
m_ParentWMO(_parentWMO)
{
for (auto& it : m_ParentWMO->m_PortalReferences)
{
CWMO_Part_Portal* portal = m_ParentWMO->m_Portals[it.portalIndex];
WMO_Group* group = m_ParentWMO->m_Groups[it.groupIndex];
if (it.groupIndex == group->m_GroupIndex)
{
group->m_Portals.push_back(portal);
}
else
{
fail1();
}
portal->setGroup(it.groupIndex, it.side);
}
}
void CWMO_PortalsController::GetPolyFrustum(const vec3* poly, uint32 num_verts, Frustum* _frustum, vec3 eye, bool _isPositive)
{
assert1(_frustum != nullptr);
Plane _portalPlanes[15];
assert1(num_verts < 15);
for (uint32 i = 0; i < num_verts; i++)
{
vec3 v1 = poly[i];
vec3 v2 = poly[(i + 1) % num_verts];
if (_isPositive)
{
_portalPlanes[i] = Plane(eye, v1, v2);
}
else
{
_portalPlanes[i] = Plane(eye, v2, v1);
}
}
_frustum->buildCustomFrustrum(_portalPlanes, num_verts);
}
void CWMO_PortalsController::Update(CWMO_Base_Instance* _localContr, cvec3 _InvWorldCamera)
{
// Reset all flags
for (auto& group : _localContr->getGroupInstances())
{
group->m_PortalsVis = false;
group->m_Calculated = false;
for (auto& doodad : group->getDoodadsInstances())
{
if (doodad)
{
doodad->setPortalVisibility(false);
}
}
}
bool insideIndoor = false;
if (m_ParentWMO->getBounds().isPointInside(_InvWorldCamera))
{
for (auto& group : _localContr->getGroupInstances())
{
if (!(group->getBounds().isPointInside(_Render->getCamera()->Position)))
{
continue;
}
if (!group->getObject()->m_Header.flags.HAS_COLLISION)
{
continue;
}
if (group->getObject()->m_Header.flags.IS_OUTDOOR)
{
continue;
}
bool recurResult = Recur(_localContr, group.operator->(), _InvWorldCamera, _Render->getCamera()->getFrustum(), true);
if (!recurResult)
{
continue;
}
if (group->getObject()->m_Header.flags.IS_INDOOR)
{
insideIndoor = true;
}
}
}
//assert1(insideOneAtLeast || !(m_ParentWMO->m_OutdoorGroups.empty()));
// If we outside WMO, then get outdorr group
//if (!insideIndoor)
{
for (auto& ogr : _localContr->getGroupOutdoorInstances())
{
Recur(_localContr, ogr.operator->(), _InvWorldCamera, _Render->getCamera()->getFrustum(), true);
}
}
}
bool CWMO_PortalsController::Recur(CWMO_Base_Instance* _localContr, CWMO_Group_Instance* _group, cvec3 _InvWorldCamera, const Frustum& _frustum, bool _isFirstIteration)
{
if (_group == nullptr || _group->m_Calculated)
{
return false;
}
if (_Render->getCamera()->getFrustum().cullBox(_group->getBounds()))
{
return false;
}
// Set visible for current
_group->m_PortalsVis = true;
_group->m_Calculated = true;
for (auto& doodad : _group->getDoodadsInstances())
{
if (doodad && (_isFirstIteration || !_frustum.cullBox(doodad->getBounds())))
{
doodad->setPortalVisibility(true);
}
}
for (auto& p : _group->getObject()->m_Portals)
{
// If we don't see portal // TODO: Don't use it on first step
if (_Render->getCamera()->getFrustum().cullPoly(_localContr->getVerts() + p->getStartVertex(), p->getCount()))
{
continue;
}
// And we don't see portal from other portal
if (!p->IsVisible(_localContr, _frustum.getPlanes(), _frustum.getPlanesCnt()))
{
continue;
}
bool isPositive = p->IsPositive(_InvWorldCamera);
// Build camera-to-poratl frustum
Frustum portalFrustum;
GetPolyFrustum
(
_localContr->getVerts() + p->getStartVertex(),
p->getCount(),
&portalFrustum,
_Render->getCamera()->Position,
isPositive
);
// Find attached to portal group
CWMO_Group_Instance* groupInstance = nullptr;
int32 groupIndex = isPositive ? p->getGrInner() : p->getGrOuter();
if (groupIndex >= 0 && groupIndex < _localContr->getGroupInstances().size())
{
groupInstance = _localContr->getGroupInstances()[groupIndex].operator->();
}
Recur
(
_localContr,
groupInstance,
_InvWorldCamera,
portalFrustum,
false
);
}
return true;
}
| 22.173684
| 168
| 0.682886
|
adan830
|
0c5f006f2cf1a2fcfc16d43162a30ba4c5900f13
| 694
|
cpp
|
C++
|
PATA1050.cpp
|
Geeks-Z/PAT-Advanced-Level-Practice
|
6b25d07ae602310215e46c951638b93080b382bf
|
[
"MIT"
] | null | null | null |
PATA1050.cpp
|
Geeks-Z/PAT-Advanced-Level-Practice
|
6b25d07ae602310215e46c951638b93080b382bf
|
[
"MIT"
] | null | null | null |
PATA1050.cpp
|
Geeks-Z/PAT-Advanced-Level-Practice
|
6b25d07ae602310215e46c951638b93080b382bf
|
[
"MIT"
] | null | null | null |
/*
* @Descripttion: https://blog.csdn.net/DayDream_x/article/details/104362662/
* @version: 1.0
* @Author: Geeks_Z
* @Date: 2021-05-31 17:07:22
* @LastEditors: Geeks_Z
* @LastEditTime: 2021-05-31 17:07:44
*/
//⽤cha[256]数组变量标记str1出现过的字符为true,str2出现过的字符为false,
//输出str1的时候根据cha[str1[i]]是否为true,如果是true就输出
#include <iostream>
#include <string>
using namespace std;
bool cha[256];
int main()
{
string s1, s2;
getline(cin, s1);
getline(cin, s2);
for (int i = 0; i < s1.size(); i++)
{
cha[s1[i]] = true;
}
for (int i = 0; i < s2.size(); i++)
{
cha[s2[i]] = false;
}
for (int i = 0; i < s1.size(); i++)
{
if (cha[s1[i]])
cout << s1[i];
}
return 0;
}
| 19.828571
| 77
| 0.592219
|
Geeks-Z
|
0c63454c8fd021902141ae6784d729ff5dd384cc
| 2,123
|
hh
|
C++
|
include/NeuTrackingAction.hh
|
kwierman/Argon40Conversion
|
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
|
[
"MIT"
] | null | null | null |
include/NeuTrackingAction.hh
|
kwierman/Argon40Conversion
|
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
|
[
"MIT"
] | null | null | null |
include/NeuTrackingAction.hh
|
kwierman/Argon40Conversion
|
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
|
[
"MIT"
] | null | null | null |
#ifndef NeuTrackingAction_hh_
#define NeuTrackingAction_hh_
#include "NeuRootOutput.hh"
#include "G4UserTrackingAction.hh"
#include "globals.hh"
namespace NeuFlux
{
/*!
\class NeuTrackingAction
\ingroup NeuFlux
\brief Header file for defining the actions to take at the beginning and end of a track.
The only capability programmed in at the moment is set parentPDG. This helps to identify
a track with it's parent track to find where products come from. This modifies the event
so that the top track is always pointed at the correct track.
\note Position calculation is still rough, given that paths may curve
\author Kevin Wierman
\version 1.0
\date Oct 1, 2013
\contact kwierman@email.unc.edu
*/
class NeuTrackingAction : public G4UserTrackingAction , public NeuOutputtingComponent
{
public:
NeuTrackingAction();
~NeuTrackingAction();
void PreUserTrackingAction(const G4Track*);
void PostUserTrackingAction(const G4Track*);
void OnNewFileCreate();
void UpdateBranches(const G4Track* theTrack);
private:
Double_t fTrackID ;
Double_t fParentID ;
Double_t fPreX ;
Double_t fPreY ;
Double_t fPreZ ;
Double_t fPreLT ;
Double_t fPreGT ;
Double_t fPrePT ;
Double_t fPostX ;
Double_t fPostY ;
Double_t fPostZ ;
Double_t fPostLT ;
Double_t fPostGT ;
Double_t fPostPT ;
Double_t fPDGMass ;
Double_t fPDGWidth ;
Double_t fPDGCharge ;
Double_t fPDGSpin ;
Double_t fPDGiSpin ;
Double_t fPDGiParity ;
Double_t fPDGiConjugation;
Double_t fPDGIsospin ;
Double_t fPDGIsospin3 ;
Double_t fPDGiIsospin ;
Double_t fPDGiIsospin3 ;
Double_t fPDGiGParity ;
Double_t fPDGMagneticMoment ;
Double_t fLeptonNumber;
Double_t fBaryonNumber ;
Int_t fPDGEncoding ;
Double_t fAtomicNumber;
Double_t fAtomicMass ;
Double_t fVolume;
Double_t fNextVolume;
};
}
#endif
| 23.32967
| 92
| 0.661799
|
kwierman
|
0c635191d64cfa0639fea9185cb642a34789d1f3
| 808
|
cpp
|
C++
|
Zerojudge/d618.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
Zerojudge/d618.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
Zerojudge/d618.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string s;
int t,state;
cin>>t;
for(int i=1;i<=t;++i)
{
cin>>s;
state=s[0]-'0';
for(int j=1;j<s.size();++j)
{
if(state==2)
{
if(s[j]-'0'!=1)continue;
else state=1;
}
else if(state==3||state==4)
{
if(state==3&&s[j]-'0'==4)state=4;
else if(state==4&&s[j]-'0'==3)state=3;
else if(s[j]-'0'==1)state=1;
}
else if(state==1||state==5||state==6||state==7)
{
state=(s[j]-'0');
}
}
cout<<state<<endl;
}
return 0;
}
| 22.444444
| 60
| 0.355198
|
w181496
|
0c66869100aab4eff2cd244d1ee5a5da6802ed71
| 8,892
|
hpp
|
C++
|
relacy/stdlib/pthread.hpp
|
pereckerdal/relacy
|
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
|
[
"BSD-3-Clause"
] | 1
|
2020-05-30T13:06:12.000Z
|
2020-05-30T13:06:12.000Z
|
relacy/stdlib/pthread.hpp
|
pereckerdal/relacy
|
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
|
[
"BSD-3-Clause"
] | null | null | null |
relacy/stdlib/pthread.hpp
|
pereckerdal/relacy
|
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
|
[
"BSD-3-Clause"
] | null | null | null |
/* Relacy Race Detector
* Copyright (c) 2008-2013, Dmitry S. Vyukov
* All rights reserved.
* This software is provided AS-IS with no warranty, either express or implied.
* This software is distributed under a license and may not be copied,
* modified or distributed except as expressly authorized under the
* terms of the license contained in the file LICENSE in this distribution.
*/
#pragma once
#include "mutex.hpp"
#include "condition_variable.hpp"
#include "semaphore.hpp"
namespace rl
{
enum RL_POSIX_ERROR_CODE
{
RL_SUCCESS,
RL_EINVAL,
RL_ETIMEDOUT,
RL_EBUSY,
RL_EINTR,
RL_EAGAIN,
RL_EWOULDBLOCK,
};
void rl_sched_yield(debug_info_param info);
typedef win_waitable_object* rl_pthread_t;
typedef void* rl_pthread_attr_t;
int rl_pthread_create(rl_pthread_t* th, rl_pthread_attr_t* attr, void* (*func) (void*), void* arg, debug_info_param info);
rl_pthread_t rl_pthread_self(debug_info_param info);
int rl_pthread_join(rl_pthread_t th, void** res, debug_info_param info);
struct sem_tag_pthread;
typedef semaphore<sem_tag_pthread> rl_sem_t;
int rl_sem_init(rl_sem_t* sema, int /*pshared*/, unsigned int initial_count, debug_info_param info);
int rl_sem_destroy(rl_sem_t* sema, debug_info_param info);
int rl_sem_wait(rl_sem_t* sema, debug_info_param info);
int rl_sem_trywait(rl_sem_t* sema, debug_info_param info);
int rl_sem_post(rl_sem_t* sema, debug_info_param info);
int rl_sem_getvalue(rl_sem_t* sema, int* value, debug_info_param info);
struct mutex_tag_pthread_mtx;
typedef generic_mutex<mutex_tag_pthread_mtx> rl_pthread_mutex_t;
struct rl_pthread_mutexattr_t
{
bool is_recursive_;
};
enum RL_PTHREAD_MUTEX_TYPE
{
RL_PTHREAD_MUTEX_NORMAL,
RL_PTHREAD_MUTEX_ERRORCHECK,
RL_PTHREAD_MUTEX_RECURSIVE,
RL_PTHREAD_MUTEX_DEFAULT,
};
int rl_pthread_mutexattr_init(rl_pthread_mutexattr_t* attr, debug_info_param info);
int rl_pthread_mutexattr_destroy(rl_pthread_mutexattr_t* attr, debug_info_param info);
int rl_pthread_mutexattr_settype(rl_pthread_mutexattr_t* attr, int type, debug_info_param info);
int rl_pthread_mutex_init(rl_pthread_mutex_t* m, rl_pthread_mutexattr_t const* attr, debug_info_param info);
int rl_pthread_mutex_destroy(rl_pthread_mutex_t* m, debug_info_param info);
int rl_pthread_mutex_lock(rl_pthread_mutex_t* m, debug_info_param info);
int rl_pthread_mutex_timedlock(rl_pthread_mutex_t* m, const void* abs_timeout, debug_info_param info);
int rl_pthread_mutex_try_lock(rl_pthread_mutex_t* m, debug_info_param info);
int rl_pthread_mutex_unlock(rl_pthread_mutex_t* m, debug_info_param info);
struct mutex_tag_pthread_rwlock;
typedef generic_mutex<mutex_tag_pthread_rwlock> rl_pthread_rwlock_t;
int rl_pthread_rwlock_init(rl_pthread_rwlock_t* lock, void const* /*attr*/, debug_info_param info);
int rl_pthread_rwlock_destroy(rl_pthread_rwlock_t* lock, debug_info_param info);
int rl_pthread_rwlock_rdlock(rl_pthread_rwlock_t* lock, debug_info_param info);
int rl_pthread_rwlock_tryrdlock(rl_pthread_rwlock_t* lock, debug_info_param info);
int rl_pthread_rwlock_wrlock(rl_pthread_rwlock_t* lock, debug_info_param info);
int rl_pthread_rwlock_trywrlock(rl_pthread_rwlock_t* lock, debug_info_param info);
int rl_pthread_rwlock_unlock(rl_pthread_rwlock_t* lock, debug_info_param info);
struct condvar_tag_pthread;
typedef condvar<condvar_tag_pthread> rl_pthread_cond_t;
typedef int rl_pthread_condattr_t;
int rl_pthread_cond_init(rl_pthread_cond_t* cv, rl_pthread_condattr_t* /*condattr*/, debug_info_param info);
int rl_pthread_cond_destroy(rl_pthread_cond_t* cv, debug_info_param info);
int rl_pthread_cond_broadcast(rl_pthread_cond_t* cv, debug_info_param info);
int rl_pthread_cond_signal(rl_pthread_cond_t* cv, debug_info_param info);
int rl_pthread_cond_timedwait(rl_pthread_cond_t* cv, rl_pthread_mutex_t* m, void const* /*timespec*/, debug_info_param info);
int rl_pthread_cond_wait(rl_pthread_cond_t* cv, rl_pthread_mutex_t* m, debug_info_param info);
enum RL_FUTEX_OP
{
RL_FUTEX_WAIT,
RL_FUTEX_WAKE,
};
int rl_int_futex_impl(context& c,
atomic<int>* uaddr,
int op,
int val,
struct timespec const* timeout,
atomic<int>* uaddr2,
int val3,
debug_info_param info);
struct futex_event
{
void* addr_;
int op_;
int val_;
bool timeout_;
int res_;
void output(std::ostream& s) const;
};
int rl_futex(atomic<int>* uaddr,
int op,
int val,
struct timespec const* timeout,
atomic<int>* uaddr2,
int val3,
debug_info_param info);
}
#ifdef EINVAL
# undef EINVAL
#endif
#define EINVAL rl::RL_EINVAL
#ifdef ETIMEDOUT
# undef ETIMEDOUT
#endif
#define ETIMEDOUT rl::RL_ETIMEDOUT
#ifdef EBUSY
# undef EBUSY
#endif
#define EBUSY rl::RL_EBUSY
#ifdef EINTR
# undef EINTR
#endif
#define EINTR rl::RL_EINTR
#ifdef EAGAIN
# undef EAGAIN
#endif
#define EAGAIN rl::RL_EAGAIN
#ifdef EWOULDBLOCK
# undef EWOULDBLOCK
#endif
#define EWOULDBLOCK rl::RL_EWOULDBLOCK
#define sched_yield() \
rl::rl_sched_yield($)
#define pthread_yield() \
rl::rl_sched_yield($)
#define pthread_t rl::rl_pthread_t
#define pthread_attr_t rl::rl_pthread_attr_t
#define pthread_create(th, attr, func, arg) \
rl::rl_pthread_create(th, attr, func, arg, $)
#define pthread_self() \
rl::rl_pthread_self($)
#define pthread_join(th, res) \
rl::rl_pthread_join(th, res, $)
#define sem_t rl::rl_sem_t
#define sem_init(sema, pshared, initial_count)\
rl::rl_sem_init(sema, pshared, initial_count, $)
#define sem_destroy(sema)\
rl::rl_sem_destroy(sema, $)
#define sem_wait(sema)\
rl::rl_sem_wait(sema, $)
#define sem_trywait(sema)\
rl::rl_sem_trywait(sema, $)
#define sem_post(sema)\
rl::rl_sem_post(sema, $)
#define sem_getvalue(sema, pvalue)\
rl::rl_sem_getvalue(sema, pvalue, $)
#define pthread_mutex_t rl::rl_pthread_mutex_t
#define pthread_mutexattr_t rl::rl_pthread_mutexattr_t
#ifdef PTHREAD_MUTEX_NORMAL
# undef PTHREAD_MUTEX_NORMAL
# undef PTHREAD_MUTEX_ERRORCHECK
# undef PTHREAD_MUTEX_RECURSIVE
# undef PTHREAD_MUTEX_DEFAULT
#endif
#define PTHREAD_MUTEX_NORMAL rl::RL_PTHREAD_MUTEX_NORMAL
#define PTHREAD_MUTEX_ERRORCHECK rl::RL_PTHREAD_MUTEX_ERRORCHECK
#define PTHREAD_MUTEX_RECURSIVE rl::RL_PTHREAD_MUTEX_RECURSIVE
#define PTHREAD_MUTEX_DEFAULT rl::RL_PTHREAD_MUTEX_DEFAULT
#define pthread_mutexattr_init(attr) \
rl::rl_pthread_mutexattr_init(attr, $)
#define pthread_mutexattr_destroy(attr) \
rl::rl_pthread_mutexattr_destroy(attr, $)
#define pthread_mutexattr_settype(attr, type) \
rl::rl_pthread_mutexattr_settype(attr, type, $)
#define pthread_mutex_init(m, attr) \
rl::rl_pthread_mutex_init(m, attr, $)
#define pthread_mutex_destroy(m) \
rl::rl_pthread_mutex_destroy(m, $)
#define pthread_mutex_lock(m) \
rl::rl_pthread_mutex_lock(m, $)
#define pthread_mutex_timedlock(m, abs_timeout) \
rl::rl_pthread_mutex_timedlock(m, abs_timeout, $)
#define pthread_mutex_try_lock(m) \
rl::rl_pthread_mutex_try_lock(m, $)
#define pthread_mutex_unlock(m) \
rl::rl_pthread_mutex_unlock(m, $)
#define pthread_rwlock_t rl::rl_pthread_rwlock_t
#define pthread_rwlock_init(lock, attr) \
rl::rl_pthread_rwlock_init(lock, attr, $)
#define pthread_rwlock_destroy(lock) \
rl::rl_pthread_rwlock_destroy(lock, $)
#define pthread_rwlock_rdlock(lock) \
rl::rl_pthread_rwlock_rdlock(lock, $)
#define pthread_rwlock_tryrdlock(lock) \
rl::rl_pthread_rwlock_tryrdlock(lock, $)
#define pthread_rwlock_wrlock(lock) \
rl::rl_pthread_rwlock_wrlock(lock, $)
#define pthread_rwlock_trywrlock(lock) \
rl::rl_pthread_rwlock_trywrlock(lock, $)
#define pthread_rwlock_unlock(lock) \
rl::rl_pthread_rwlock_unlock(lock, $)
#define pthread_cond_t rl::rl_pthread_cond_t
#define pthread_condattr_t rl::rl_pthread_condattr_t
#define pthread_cond_init(cv, condattr) \
rl::rl_pthread_cond_init(cv, condattr, $)
#define pthread_cond_destroy(cv) \
rl::rl_pthread_cond_destroy(cv, $)
#define pthread_cond_broadcast(cv) \
rl::rl_pthread_cond_broadcast(cv, $)
#define pthread_cond_signal(cv) \
rl::rl_pthread_cond_signal(cv, $)
#define pthread_cond_timedwait(cv, m, timespec) \
rl::rl_pthread_cond_timedwait(cv, m, timespec, $)
#define pthread_cond_wait(cv, m) \
rl::rl_pthread_cond_wait(cv, m, $)
#ifdef FUTEX_WAKE
# undef FUTEX_WAKE
#endif
#define FUTEX_WAKE rl::RL_FUTEX_WAKE
#ifdef FUTEX_WAIT
# undef FUTEX_WAIT
#endif
#define FUTEX_WAIT rl::RL_FUTEX_WAIT
#define futex(uaddr, op, val, timeout, uaddr2, val3) \
rl::rl_futex(uaddr, op, val, timeout, uaddr2, val3, $)
| 24.977528
| 125
| 0.752024
|
pereckerdal
|
0c6ba9bf5a78c36b40a2bc1c771ea0c842ae02f8
| 4,192
|
cpp
|
C++
|
sakura_core/util/format.cpp
|
zlatantan/sakura
|
a722f9c86f2860606b3f9e7dc79bb169294cfaea
|
[
"Zlib"
] | 1
|
2019-03-15T16:55:33.000Z
|
2019-03-15T16:55:33.000Z
|
sakura_core/util/format.cpp
|
zlatantan/sakura
|
a722f9c86f2860606b3f9e7dc79bb169294cfaea
|
[
"Zlib"
] | null | null | null |
sakura_core/util/format.cpp
|
zlatantan/sakura
|
a722f9c86f2860606b3f9e7dc79bb169294cfaea
|
[
"Zlib"
] | null | null | null |
/*! @file */
/*
Copyright (C) 2007, kobake
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "StdAfx.h"
#include "format.h"
/*! 日時をフォーマット
@param[out] 書式変換後の文字列
@param[in] バッファサイズ
@param[in] format 書式
@param[in] systime 書式化したい日時
@return bool true
@note %Y %y %m %d %H %M %S の変換に対応
@author aroka
@date 2005.11.21 新規
@todo 出力バッファのサイズチェックを行う
*/
bool GetDateTimeFormat( TCHAR* szResult, int size, const TCHAR* format, const SYSTEMTIME& systime )
{
TCHAR szTime[10];
const TCHAR *p = format;
TCHAR *q = szResult;
int len;
while( *p ){
if( *p == _T('%') ){
++p;
switch(*p){
case _T('Y'):
len = wsprintf(szTime,_T("%d"),systime.wYear);
_tcscpy( q, szTime );
break;
case _T('y'):
len = wsprintf(szTime,_T("%02d"),(systime.wYear%100));
_tcscpy( q, szTime );
break;
case _T('m'):
len = wsprintf(szTime,_T("%02d"),systime.wMonth);
_tcscpy( q, szTime );
break;
case _T('d'):
len = wsprintf(szTime,_T("%02d"),systime.wDay);
_tcscpy( q, szTime );
break;
case _T('H'):
len = wsprintf(szTime,_T("%02d"),systime.wHour);
_tcscpy( q, szTime );
break;
case _T('M'):
len = wsprintf(szTime,_T("%02d"),systime.wMinute);
_tcscpy( q, szTime );
break;
case _T('S'):
len = wsprintf(szTime,_T("%02d"),systime.wSecond);
_tcscpy( q, szTime );
break;
// A Z
case _T('%'):
default:
*q = *p;
len = 1;
break;
}
q+=len;//q += strlen(szTime);
++p;
}
else{
*q = *p;
q++;
p++;
}
}
*q = *p;
return true;
}
/*! バージョン番号の解析
@param[in] バージョン番号文字列
@return UINT32 8bit(符号1bit+数値7bit)ずつメジャー、マイナー、ビルド、リビジョンを格納
@author syat
@date 2011.03.18 新規
@note 参考 PHP version_compare http://php.s3.to/man/function.version-compare.html
*/
UINT32 ParseVersion( const TCHAR* sVer )
{
int nVer;
int nShift = 0; //特別な文字列による下駄
int nDigit = 0; //連続する数字の数
UINT32 ret = 0;
const TCHAR *p = sVer;
int i;
for( i=0; *p && i<4; i++){
//特別な文字列の処理
if( *p == _T('a') ){
if( _tcsncmp( _T("alpha"), p, 5 ) == 0 )p += 5;
else p++;
nShift = -0x60;
}
else if( *p == _T('b') ){
if( _tcsncmp( _T("beta"), p, 4 ) == 0 )p += 4;
else p++;
nShift = -0x40;
}
else if( *p == _T('r') || *p == _T('R') ){
if( _tcsnicmp( _T("rc"), p, 2 ) == 0 )p += 2;
else p++;
nShift = -0x20;
}
else if( *p == _T('p') ){
if( _tcsncmp( _T("pl"), p, 2 ) == 0 )p += 2;
else p++;
nShift = 0x20;
}
else if( !_istdigit(*p) ){
nShift = -0x80;
}
else{
nShift = 0;
}
while( *p && !_istdigit(*p) ){ p++; }
//数値の抽出
for( nVer = 0, nDigit = 0; _istdigit(*p); p++ ){
if( ++nDigit > 2 )break; //数字は2桁までで止める
nVer = nVer * 10 + *p - _T('0');
}
//区切り文字の処理
while( *p && _tcschr( _T(".-_+"), *p ) ){ p++; }
DEBUG_TRACE(_T(" VersionPart%d: ver=%d,shift=%d\n"), i, nVer, nShift);
ret |= ( (nShift + nVer + 128) << (24-8*i) );
}
for( ; i<4; i++ ){ //残りの部分はsigned 0 (=0x80)を埋める
ret |= ( 128 << (24-8*i) );
}
#ifdef _UNICODE
DEBUG_TRACE(_T("ParseVersion %ls -> %08x\n"), sVer, ret);
#endif
return ret;
}
/*! バージョン番号の比較
@param[in] バージョンA
@param[in] バージョンB
@return int 0: バージョンは等しい、1以上: Aが新しい、-1以下: Bが新しい
@author syat
@date 2011.03.18 新規
*/
int CompareVersion( const TCHAR* verA, const TCHAR* verB )
{
UINT32 nVerA = ParseVersion(verA);
UINT32 nVerB = ParseVersion(verB);
return nVerA - nVerB;
}
| 22.297872
| 99
| 0.595181
|
zlatantan
|
0c6ceb1940734cd71aefbb108f367a8cafd1abb3
| 3,423
|
cpp
|
C++
|
src/lib/init.cpp
|
lucteo/concore
|
ffbc3b8cead7498ddad601dcf357fa72529f81ad
|
[
"MIT"
] | 52
|
2020-05-23T21:34:33.000Z
|
2022-02-23T03:06:50.000Z
|
src/lib/init.cpp
|
lucteo/concore
|
ffbc3b8cead7498ddad601dcf357fa72529f81ad
|
[
"MIT"
] | null | null | null |
src/lib/init.cpp
|
lucteo/concore
|
ffbc3b8cead7498ddad601dcf357fa72529f81ad
|
[
"MIT"
] | 2
|
2021-05-06T18:41:25.000Z
|
2021-07-24T03:50:42.000Z
|
#include "concore/init.hpp"
#include "concore/low_level/spin_mutex.hpp"
#include "concore/detail/platform.hpp"
#include "concore/detail/likely.hpp"
#include "concore/detail/library_data.hpp"
#include "concore/detail/exec_context.hpp"
#include <mutex>
#define __IMPL__CONCORE_USE_CXX_ABI CONCORE_CPP_COMPILER(gcc) || CONCORE_CPP_COMPILER(clang)
namespace concore {
namespace detail {
#if __IMPL__CONCORE_USE_CXX_ABI
#if CONCORE_CPU_ARCH(arm)
using cxa_guard_type = uint32_t;
#else
using cxa_guard_type = uint64_t;
#endif
static cxa_guard_type g_initialized_guard{0};
static exec_context* g_exec_context{nullptr};
// Take the advantage of ABI compatibility
extern "C" int __cxa_guard_acquire(cxa_guard_type*);
extern "C" void __cxa_guard_release(cxa_guard_type*);
extern "C" void __cxa_guard_abort(cxa_guard_type*);
#else
static std::atomic<exec_context*> g_exec_context{nullptr};
#endif
//! Copy of the init_data used to create the global exec_context
init_data g_init_data_used;
//! The per-thread execution context; can be null if the thread doesn't belong to any execution
//! context.
thread_local exec_context* g_tlsCtx{nullptr};
//! Called to shutdown the library
void do_shutdown() {
if (!is_initialized())
return;
#if __IMPL__CONCORE_USE_CXX_ABI
delete detail::g_exec_context;
detail::g_exec_context = nullptr;
g_initialized_guard = 0;
#else
delete detail::g_exec_context.load();
detail::g_exec_context.store(nullptr, std::memory_order_release);
#endif
}
//! Actually initialized the library; this is guarded by get_exec_context()
void do_init(const init_data* config) {
static init_data default_config;
if (!config)
config = &default_config;
auto global_ctx = new exec_context(*config);
g_init_data_used = *config;
#if __IMPL__CONCORE_USE_CXX_ABI
detail::g_exec_context = global_ctx;
#else
detail::g_exec_context.store(global_ctx, std::memory_order_release);
#endif
atexit(&do_shutdown);
}
exec_context& get_exec_context(const init_data* config) {
// If we have an execution context in the current thread, return it
if (g_tlsCtx)
return *g_tlsCtx;
#if __IMPL__CONCORE_USE_CXX_ABI
CONCORE_IF_UNLIKELY(__cxa_guard_acquire(&g_initialized_guard)) {
try {
do_init(config);
} catch (...) {
__cxa_guard_abort(&g_initialized_guard);
throw;
}
__cxa_guard_release(&g_initialized_guard);
}
return *g_exec_context;
#else
auto p = detail::g_exec_context.load(std::memory_order_acquire);
CONCORE_IF_UNLIKELY(!p) {
static spin_mutex init_bottleneck;
try {
init_bottleneck.lock();
do_init(config);
init_bottleneck.unlock();
p = g_exec_context.load(std::memory_order_acquire);
} catch (...) {
init_bottleneck.unlock();
throw;
}
}
return *p;
#endif
}
void set_context_in_current_thread(exec_context* ctx) { g_tlsCtx = ctx; }
init_data get_current_init_data() { return g_init_data_used; }
} // namespace detail
inline namespace v1 {
void init(const init_data& config) {
if (is_initialized())
throw already_initialized();
detail::get_exec_context(&config);
}
bool is_initialized() { return detail::g_exec_context != nullptr; }
void shutdown() { detail::do_shutdown(); }
} // namespace v1
} // namespace concore
| 26.952756
| 95
| 0.715746
|
lucteo
|
0c6eb2e404923c73a81c117c51c8c746243191d2
| 491
|
cpp
|
C++
|
chapter-12/12.17.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
chapter-12/12.17.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
chapter-12/12.17.cpp
|
zero4drift/Cpp-Primer-5th-Exercises
|
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
|
[
"MIT"
] | null | null | null |
// int ix = 1024, *pi = &ix. *pi2 = new int(2048);
// typedef unique_ptr<int> IntP;
// a: IntP p0(ix); illegal, unique_ptr must be binded to a ptr which is the return value of operator 'new'.
// b: IntP p1(pi); illegal, same reason as a.
// c: IntP p2(pi2); legal, but pi2 may become a dangling pointer.
// d: IntP p3(&ix); illegal, same reason as a.
// e: IntP p4(new int(2048)); legal;
// f: IntP p5(p2.get()); illegal, p2 has not yet release its pointer, poniter is still 'owned' by p2.
| 49.1
| 107
| 0.659878
|
zero4drift
|
0c7118e140840ec289a924ba09e009b60764842f
| 1,146
|
cpp
|
C++
|
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
|
Tomura/TacticalVRCorePlugin
|
8c8ade8a33b68751cd73a51ddfdd098823197503
|
[
"MIT"
] | 8
|
2021-12-20T01:04:23.000Z
|
2022-03-28T02:55:34.000Z
|
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
|
Tomura/TacticalVRCorePlugin
|
8c8ade8a33b68751cd73a51ddfdd098823197503
|
[
"MIT"
] | null | null | null |
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
|
Tomura/TacticalVRCorePlugin
|
8c8ade8a33b68751cd73a51ddfdd098823197503
|
[
"MIT"
] | null | null | null |
// This file is covered by the LICENSE file in the root of this plugin.
#include "Weapon/Component/TVRAttachPoint_Muzzle.h"
#include "Weapon/Attachments/WPNA_Muzzle.h"
UTVRAttachPoint_Muzzle::UTVRAttachPoint_Muzzle(const FObjectInitializer& OI) : Super(OI)
{
CurrentAttachmentClass = nullptr;
}
bool UTVRAttachPoint_Muzzle::SetCurrentAttachmentClass(TSubclassOf<ATVRWeaponAttachment> NewClass)
{
if(NewClass == nullptr)
{
CurrentAttachmentClass = nullptr;
OnConstruction();
return true;
}
if(NewClass->IsChildOf(AWPNA_Muzzle::StaticClass()))
{
const TSubclassOf<AWPNA_Muzzle> TestClass = *NewClass;
if(AllowedMuzzles.Find(TestClass) != INDEX_NONE)
{
CurrentAttachmentClass = TestClass;
OnConstruction();
return true;
}
}
return false;
}
TSubclassOf<ATVRWeaponAttachment> UTVRAttachPoint_Muzzle::GetCurrentAttachmentClass_Internal() const
{
return CurrentAttachmentClass;
}
void UTVRAttachPoint_Muzzle::GetAllowedAttachments(
TArray<TSubclassOf<ATVRWeaponAttachment>>& OutAllowedAttachments) const
{
for(TSubclassOf<AWPNA_Muzzle> TestClass : AllowedMuzzles)
{
OutAllowedAttachments.Add(TestClass);
}
}
| 24.913043
| 100
| 0.787958
|
Tomura
|
0c7e449d9a76d4de261d1021b25def40d323d6fd
| 843
|
cpp
|
C++
|
PAT1040.cpp
|
Geeks-Z/PAT
|
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
|
[
"MIT"
] | null | null | null |
PAT1040.cpp
|
Geeks-Z/PAT
|
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
|
[
"MIT"
] | null | null | null |
PAT1040.cpp
|
Geeks-Z/PAT
|
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
|
[
"MIT"
] | null | null | null |
/*
* @Descripttion: 有几个PAT
* @version: 1.0
* @Author: Geeks_Z
* @Date: 2021-04-30 14:40:53
* @LastEditors: Geeks_Z
* @LastEditTime: 2021-05-08 11:30:38
*/
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
const int mod = 1000000007;
const int maxn = 100010;
int main()
{
// freopen("input.txt", "r", stdin);
string str;
cin >> str;
int pNum[maxn] = {0}, res = 0;
if (str[0] == 'P')
{
pNum[0] = 1;
}
for (int i = 1; i < str.length(); i++)
{
if (str[i] == 'P')
{
pNum[i] = pNum[i - 1] + 1;
}
else
{
pNum[i] = pNum[i - 1];
}
}
int tNum = 0;
for (int i = str.length() - 1; i >= 0; i--)
{
if (str[i] == 'T')
{
tNum++;
}
if (str[i] == 'A')
{
res = (res + pNum[i] * tNum) % mod;
}
}
cout << res;
return 0;
}
| 16.529412
| 45
| 0.476868
|
Geeks-Z
|
0c7f99cf703b44ea3817338b95a06c3aee761336
| 6,285
|
cpp
|
C++
|
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
|
qinwang13/CIAO
|
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
|
[
"DOC"
] | 10
|
2016-07-20T00:55:50.000Z
|
2020-10-04T19:07:10.000Z
|
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
|
qinwang13/CIAO
|
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
|
[
"DOC"
] | 13
|
2016-09-27T14:08:27.000Z
|
2020-11-11T10:45:56.000Z
|
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
|
qinwang13/CIAO
|
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
|
[
"DOC"
] | 12
|
2016-04-20T09:57:02.000Z
|
2021-12-24T17:23:45.000Z
|
// -*- C++ -*-
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.dre.vanderbilt.edu/~schmidt/TAO.html
**/
#include "CoherentWrite_Test_Sender_exec.h"
#include "tao/ORB_Core.h"
#include "ace/Reactor.h"
namespace CIAO_CoherentWrite_Test_Sender_Impl
{
/**
* WriteHandler
*/
WriteHandler::WriteHandler (Sender_exec_i &callback)
: callback_ (callback)
{
}
int
WriteHandler::handle_exception (ACE_HANDLE)
{
this->callback_.start ();
return 0;
}
/**
* Facet Executor Implementation Class: restart_writer_exec_i
*/
restart_writer_exec_i::restart_writer_exec_i (
::CoherentWrite_Test::CCM_Sender_Context_ptr ctx,
Sender_exec_i &callback)
: ciao_context_ (
::CoherentWrite_Test::CCM_Sender_Context::_duplicate (ctx))
, callback_ (callback)
{
}
restart_writer_exec_i::~restart_writer_exec_i (void)
{
}
// Operations from ::CoherentWriteRestarter
void
restart_writer_exec_i::restart_write (void)
{
this->callback_.restart ();
}
/**
* Component Executor Implementation Class: Sender_exec_i
*/
Sender_exec_i::Sender_exec_i (void)
: iterations_ (0)
, run_ (1)
, total_iter (0)
, wh_ (0)
{
ACE_NEW_THROW_EX (this->wh_,
WriteHandler (*this),
::CORBA::INTERNAL ());
}
Sender_exec_i::~Sender_exec_i (void)
{
delete this->wh_;
}
// Supported operations and attributes.
ACE_Reactor*
Sender_exec_i::reactor (void)
{
ACE_Reactor* reactor = 0;
::CORBA::Object_var ccm_object =
this->ciao_context_->get_CCM_object();
if (! ::CORBA::is_nil (ccm_object.in ()))
{
::CORBA::ORB_var orb = ccm_object->_get_orb ();
if (! ::CORBA::is_nil (orb.in ()))
{
reactor = orb->orb_core ()->reactor ();
}
}
if (reactor == 0)
{
throw ::CORBA::INTERNAL ();
}
return reactor;
}
void
Sender_exec_i::restart (void)
{
++this->run_;
delete this->wh_;
ACE_NEW_THROW_EX (this->wh_,
WriteHandler (*this),
::CORBA::INTERNAL ());
this->reactor ()->notify (this->wh_);
}
void
Sender_exec_i::start (void)
{
::CoherentWriteTestConnector::Writer_var writer =
this->ciao_context_->get_connection_info_write_data ();
CoherentWriteStarter_var starter =
this->ciao_context_->get_connection_start_reader ();
if (::CORBA::is_nil (starter.in ()) ||
::CORBA::is_nil (writer.in ()))
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Unable to start the reader\n")));
return;
}
writer->is_coherent_write (true);
starter->set_reader_properties (this->iterations_);
ACE_DEBUG ((LM_DEBUG, "Start run <%d> with <%u> iterations\n",
this->run_,
this->iterations ()));
CoherentWriteTestSeq write_many_seq (this->iterations_);
write_many_seq.length (this->iterations_);
for (int i = 1; i < this->iterations_ + 1; ++i)
{
CoherentWriteTest new_key;
new_key.symbol = CORBA::string_dup("KEY_1");
new_key.iteration = ++total_iter;
write_many_seq[i-1] = new_key;
}
writer->write_many (write_many_seq);
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Written <%u> keys uptil now\n"),
total_iter));
ACE_OS::sleep (2);
starter->start_read (this->run_);
}
// Component attributes and port operations.
::CCM_CoherentWriteRestarter_ptr
Sender_exec_i::get_restart_writer (void)
{
if ( ::CORBA::is_nil (this->ciao_restart_writer_.in ()))
{
restart_writer_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
restart_writer_exec_i (
this->ciao_context_.in (),
*this),
::CCM_CoherentWriteRestarter::_nil ());
this->ciao_restart_writer_ = tmp;
}
return
::CCM_CoherentWriteRestarter::_duplicate (
this->ciao_restart_writer_.in ());
}
::CORBA::UShort
Sender_exec_i::iterations (void)
{
return this->iterations_;
}
void
Sender_exec_i::iterations (
const ::CORBA::UShort iterations)
{
this->iterations_ = iterations;
}
// Operations from Components::SessionComponent.
void
Sender_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::CoherentWrite_Test::CCM_Sender_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Sender_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Sender_exec_i::ccm_activate (void)
{
try
{
this->reactor ()->notify (this->wh_);
}
catch (const ::CORBA::Exception& ex)
{
ex._tao_print_exception ("Exception caught:");
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ERROR: GET_CONNECTION_START_READER : Exception caught\n")));
}
catch (...)
{
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ERROR: GET_CONNECTION_START_READER : Unknown exception caught\n")));
}
}
void
Sender_exec_i::ccm_passivate (void)
{
/* Your code here. */
}
void
Sender_exec_i::ccm_remove (void)
{
/* Your code here. */
}
extern "C" SENDER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_CoherentWrite_Test_Sender_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Sender_exec_i);
return retval;
}
}
| 23.62782
| 89
| 0.606046
|
qinwang13
|
0c81e9c6cdd0c7ffa40ae96cb31e06601cd9a962
| 3,374
|
hpp
|
C++
|
saga/saga/adaptors/utils/ini/ini.hpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 5
|
2015-09-15T16:24:14.000Z
|
2021-08-12T11:05:55.000Z
|
saga/saga/adaptors/utils/ini/ini.hpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | null | null | null |
saga/saga/adaptors/utils/ini/ini.hpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 3
|
2016-11-17T04:38:38.000Z
|
2021-04-10T17:23:52.000Z
|
// Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net)
// Copyright (c) 2009 João Abecasis
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef _SAGA_INI_H_
#define _SAGA_INI_H_ 1
#include <map>
#include <list>
#include <vector>
#include <iostream>
// other includes from SAGA
#include <saga/saga/util.hpp>
#include <saga/saga/types.hpp>
// suppress warnings about dependent classes not being exported from the dll
#if defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable: 4251 4231 4275 4660)
#endif
//////////////////////////////////////////
//
// C++ interface
//
namespace saga
{
// forward declaration
namespace impl
{
namespace ini
{
class section;
}
}
namespace ini
{
class section;
typedef section ini;
typedef std::map <std::string, std::string> entry_map;
typedef std::map <std::string, section> section_map;
#define SAGA_INI_EXPORT /**/
class SAGA_EXPORT/*SAGA_INI_EXPORT*/ section
{
private:
typedef saga::impl::ini::section impl_sec;
typedef TR1::shared_ptr <impl_sec> shared_sec;
shared_sec impl_;
shared_sec get_impl (void) const { return (impl_); }
explicit section (shared_sec impl);
explicit section (impl_sec * sec);
void debug (std::string = "") const;
public:
section (std::string filename = "");
section (const section & in);
~section (void);
void read (std::string filename);
void parse (std::string sourcename,
std::vector <std::string> lines);
void merge (std::string second);
void merge (
const section & second);
void dump (int ind = 0,
std::ostream& strm = std::cout) const;
void add_section (std::string sec_name,
const section & sec);
bool has_section (std::string sec_name) const;
bool has_section_full (std::string sec_name) const;
section get_section (std::string sec_name) const;
section_map get_sections (void) const;
void add_entry (std::string key,
std::string val);
bool has_entry (std::string key) const;
std::string get_entry (std::string key) const;
std::string get_entry (std::string key,
std::string dflt_val) const;
entry_map get_entries (void) const;
section get_root (void) const;
std::string get_name (void) const;
};
} // namespace ini
} // namespace saga
#endif // _SAGA_INI_H_
| 31.240741
| 85
| 0.496147
|
saga-project
|
0c84a0e6e65d8b30939677ac795d81a0ca6776c2
| 386
|
hpp
|
C++
|
src/include/Window.hpp
|
sglyons2/edu-chat
|
0520c76903a84c1034ec6b83c51f162e195fe74f
|
[
"MIT"
] | null | null | null |
src/include/Window.hpp
|
sglyons2/edu-chat
|
0520c76903a84c1034ec6b83c51f162e195fe74f
|
[
"MIT"
] | null | null | null |
src/include/Window.hpp
|
sglyons2/edu-chat
|
0520c76903a84c1034ec6b83c51f162e195fe74f
|
[
"MIT"
] | null | null | null |
#ifndef WINDOW_HPP
#define WINDOW_HPP
#include <ncurses.h>
#include <vector>
#include <string>
struct Window {
WINDOW *window;
int height;
int width;
int begin_y;
int begin_x;
Window(int height, int width, int begin_y, int begin_x);
~Window();
void print(std::vector<std::string>& lines, bool boxed);
void resize(int height, int width, int begin_y, int begin_x);
};
#endif
| 17.545455
| 62
| 0.715026
|
sglyons2
|
0c8a7d9784c2b2b3f68921b1a452c4081c5ce82a
| 3,888
|
cpp
|
C++
|
util.cpp
|
tpruvot/skminer
|
2dd652461ed8dcce2137547b58376dc2107f6103
|
[
"Apache-2.0"
] | 3
|
2015-10-22T03:11:03.000Z
|
2021-05-26T07:47:48.000Z
|
util.cpp
|
tpruvot/skminer
|
2dd652461ed8dcce2137547b58376dc2107f6103
|
[
"Apache-2.0"
] | null | null | null |
util.cpp
|
tpruvot/skminer
|
2dd652461ed8dcce2137547b58376dc2107f6103
|
[
"Apache-2.0"
] | 2
|
2017-07-14T19:21:17.000Z
|
2017-12-22T08:05:25.000Z
|
/*
* Copyright 2010 Jeff Garzik
* Copyright 2012-2014 pooler
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#define _GNU_SOURCE
#include "cpuminer-config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <unistd.h>
#include <jansson.h>
#include <curl/curl.h>
#include <time.h>
#if defined(WIN32)
#include <winsock2.h>
#include <mstcpip.h>
#else
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#include "compat.h"
#include "miner.h"
#include "elist.h"
void abin2hex(char *s, const unsigned char *p, size_t len)
{
int i;
for (i = 0; i < len; i++)
sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
}
char *bin2hex(const unsigned char *p, size_t len)
{
unsigned int i;
char *s = (char*)malloc((len * 2) + 1);
if (!s)
return NULL;
for (i = 0; i < len; i++)
sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
return s;
}
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
char hex_byte[3];
char *ep;
hex_byte[2] = '\0';
while (*hexstr && len) {
if (!hexstr[1]) {
// applog(LOG_ERR, "hex2bin str truncated");
return false;
}
hex_byte[0] = hexstr[0];
hex_byte[1] = hexstr[1];
*p = (unsigned char) strtol(hex_byte, &ep, 16);
if (*ep) {
// applog(LOG_ERR, "hex2bin failed on '%s'", hex_byte);
return false;
}
p++;
hexstr += 2;
len--;
}
return (len == 0 && *hexstr == 0) ? true : false;
}
/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *x,
struct timeval *y)
{
/* Perform the carry for the later subtraction by updating Y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* `tv_usec' is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
void diff_to_target(uint32_t *target, double diff)
{
uint64_t m;
int k;
for (k = 6; k > 0 && diff > 1.0; k--)
diff /= 4294967296.0;
m = (uint64_t)(4294901760.0 / diff);
if (m == 0 && k == 6)
memset(target, 0xff, 32);
else {
memset(target, 0, 32);
target[k] = (uint32_t)m;
target[k + 1] = (uint32_t)(m >> 32);
}
}
#ifdef WIN32
#define socket_blocks() (WSAGetLastError() == WSAEWOULDBLOCK)
#else
#define socket_blocks() (errno == EAGAIN || errno == EWOULDBLOCK)
#endif
static bool send_line(curl_socket_t sock, char *s)
{
ssize_t len, sent = 0;
len = (ssize_t)strlen(s);
s[len++] = '\n';
while (len > 0) {
struct timeval timeout = {0, 0};
ssize_t n;
fd_set wd;
FD_ZERO(&wd);
FD_SET(sock, &wd);
if (select((int)sock + 1, NULL, &wd, NULL, &timeout) < 1)
return false;
n = send(sock, s + sent, len, 0);
if (n < 0) {
if (!socket_blocks())
return false;
n = 0;
}
sent += n;
len -= n;
}
return true;
}
#define RBUFSIZE 2048
#define RECVSIZE (RBUFSIZE - 4)
#if LIBCURL_VERSION_NUM >= 0x071101
static curl_socket_t opensocket_grab_cb(void *clientp, curlsocktype purpose,
struct curl_sockaddr *addr)
{
curl_socket_t *sock = (curl_socket_t *)clientp;
*sock = socket(addr->family, addr->socktype, addr->protocol);
return *sock;
}
#endif
| 20.145078
| 77
| 0.635288
|
tpruvot
|
0c8c43c713088275106d5fbb860304d038893db2
| 12,668
|
cpp
|
C++
|
coreneuron/mpi/lib/mpispike.cpp
|
phoenixdong/CoreNeuron
|
ff80819b04d5cbe41d9dfc35608b55df961c5646
|
[
"BSD-3-Clause"
] | null | null | null |
coreneuron/mpi/lib/mpispike.cpp
|
phoenixdong/CoreNeuron
|
ff80819b04d5cbe41d9dfc35608b55df961c5646
|
[
"BSD-3-Clause"
] | null | null | null |
coreneuron/mpi/lib/mpispike.cpp
|
phoenixdong/CoreNeuron
|
ff80819b04d5cbe41d9dfc35608b55df961c5646
|
[
"BSD-3-Clause"
] | null | null | null |
/*
# =============================================================================
# Copyright (c) 2016 - 2021 Blue Brain Project/EPFL
#
# See top-level LICENSE file for details.
# =============================================================================.
*/
#include "coreneuron/nrnconf.h"
/* do not want the redef in the dynamic load case */
#include "coreneuron/mpi/nrnmpiuse.h"
#include "coreneuron/mpi/nrnmpi.h"
#include "coreneuron/mpi/nrnmpidec.h"
#include "nrnmpi.hpp"
#include "coreneuron/utils/profile/profiler_interface.h"
#include "coreneuron/utils/nrn_assert.h"
#include <mpi.h>
#include <cstring>
namespace coreneuron {
extern MPI_Comm nrnmpi_comm;
static int np;
static int* displs{nullptr};
static int* byteovfl{nullptr}; /* for the compressed transfer method */
static MPI_Datatype spike_type;
static void* emalloc(size_t size) {
void* memptr = malloc(size);
assert(memptr);
return memptr;
}
// Register type NRNMPI_Spike
void nrnmpi_spike_initialize() {
NRNMPI_Spike s;
int block_lengths[2] = {1, 1};
MPI_Aint addresses[3];
MPI_Get_address(&s, &addresses[0]);
MPI_Get_address(&(s.gid), &addresses[1]);
MPI_Get_address(&(s.spiketime), &addresses[2]);
MPI_Aint displacements[2] = {addresses[1] - addresses[0], addresses[2] - addresses[0]};
MPI_Datatype typelist[2] = {MPI_INT, MPI_DOUBLE};
MPI_Type_create_struct(2, block_lengths, displacements, typelist, &spike_type);
MPI_Type_commit(&spike_type);
}
#if nrn_spikebuf_size > 0
static MPI_Datatype spikebuf_type;
// Register type NRNMPI_Spikebuf
static void make_spikebuf_type() {
NRNMPI_Spikebuf s;
int block_lengths[3] = {1, nrn_spikebuf_size, nrn_spikebuf_size};
MPI_Datatype typelist[3] = {MPI_INT, MPI_INT, MPI_DOUBLE};
MPI_Aint addresses[4];
MPI_Get_address(&s, &addresses[0]);
MPI_Get_address(&(s.nspike), &addresses[1]);
MPI_Get_address(&(s.gid[0]), &addresses[2]);
MPI_Get_address(&(s.spiketime[0]), &addresses[3]);
MPI_Aint displacements[3] = {addresses[1] - addresses[0],
addresses[2] - addresses[0],
addresses[3] - addresses[0]};
MPI_Type_create_struct(3, block_lengths, displacements, typelist, &spikebuf_type);
MPI_Type_commit(&spikebuf_type);
}
#endif
void wait_before_spike_exchange() {
MPI_Barrier(nrnmpi_comm);
}
int nrnmpi_spike_exchange_impl(int* nin,
NRNMPI_Spike* spikeout,
int icapacity,
NRNMPI_Spike** spikein,
int& ovfl,
int nout,
NRNMPI_Spikebuf* spbufout,
NRNMPI_Spikebuf* spbufin) {
nrn_assert(spikein);
Instrumentor::phase_begin("spike-exchange");
{
Instrumentor::phase p("imbalance");
wait_before_spike_exchange();
}
Instrumentor::phase_begin("communication");
if (!displs) {
np = nrnmpi_numprocs_;
displs = (int*) emalloc(np * sizeof(int));
displs[0] = 0;
#if nrn_spikebuf_size > 0
make_spikebuf_type();
#endif
}
#if nrn_spikebuf_size == 0
MPI_Allgather(&nout, 1, MPI_INT, nin, 1, MPI_INT, nrnmpi_comm);
int n = nin[0];
for (int i = 1; i < np; ++i) {
displs[i] = n;
n += nin[i];
}
if (n) {
if (icapacity < n) {
icapacity = n + 10;
free(*spikein);
*spikein = (NRNMPI_Spike*) emalloc(icapacity * sizeof(NRNMPI_Spike));
}
MPI_Allgatherv(spikeout, nout, spike_type, *spikein, nin, displs, spike_type, nrnmpi_comm);
}
#else
MPI_Allgather(spbufout, 1, spikebuf_type, spbufin, 1, spikebuf_type, nrnmpi_comm);
int novfl = 0;
int n = spbufin[0].nspike;
if (n > nrn_spikebuf_size) {
nin[0] = n - nrn_spikebuf_size;
novfl += nin[0];
} else {
nin[0] = 0;
}
for (int i = 1; i < np; ++i) {
displs[i] = novfl;
int n1 = spbufin[i].nspike;
n += n1;
if (n1 > nrn_spikebuf_size) {
nin[i] = n1 - nrn_spikebuf_size;
novfl += nin[i];
} else {
nin[i] = 0;
}
}
if (novfl) {
if (icapacity < novfl) {
icapacity = novfl + 10;
free(*spikein);
*spikein = (NRNMPI_Spike*) emalloc(icapacity * sizeof(NRNMPI_Spike));
}
int n1 = (nout > nrn_spikebuf_size) ? nout - nrn_spikebuf_size : 0;
MPI_Allgatherv(spikeout, n1, spike_type, *spikein, nin, displs, spike_type, nrnmpi_comm);
}
ovfl = novfl;
#endif
Instrumentor::phase_end("communication");
Instrumentor::phase_end("spike-exchange");
return n;
}
/*
The compressed spike format is restricted to the fixed step method and is
a sequence of unsigned char.
nspike = buf[0]*256 + buf[1]
a sequence of spiketime, localgid pairs. There are nspike of them.
spiketime is relative to the last transfer time in units of dt.
note that this requires a mindelay < 256*dt.
localgid is an unsigned int, unsigned short,
or unsigned char in size depending on the range and thus takes
4, 2, or 1 byte respectively. To be machine independent we do our
own byte coding. When the localgid range is smaller than the true
gid range, the gid->PreSyn are remapped into
hostid specific maps. If there are not many holes, i.e just about every
spike from a source machine is delivered to some cell on a
target machine, then instead of a hash map, a vector is used.
The allgather sends the first part of the buf and the allgatherv buffer
sends any overflow.
*/
int nrnmpi_spike_exchange_compressed_impl(int localgid_size,
unsigned char*& spfixin_ovfl,
int send_nspike,
int* nin,
int ovfl_capacity,
unsigned char* spikeout_fixed,
int ag_send_size,
unsigned char* spikein_fixed,
int& ovfl) {
if (!displs) {
np = nrnmpi_numprocs_;
displs = (int*) emalloc(np * sizeof(int));
displs[0] = 0;
}
if (!byteovfl) {
byteovfl = (int*) emalloc(np * sizeof(int));
}
MPI_Allgather(
spikeout_fixed, ag_send_size, MPI_BYTE, spikein_fixed, ag_send_size, MPI_BYTE, nrnmpi_comm);
int novfl = 0;
int ntot = 0;
int bstot = 0;
for (int i = 0; i < np; ++i) {
displs[i] = bstot;
int idx = i * ag_send_size;
int n = spikein_fixed[idx++] * 256;
n += spikein_fixed[idx++];
ntot += n;
nin[i] = n;
if (n > send_nspike) {
int bs = 2 + n * (1 + localgid_size) - ag_send_size;
byteovfl[i] = bs;
bstot += bs;
novfl += n - send_nspike;
} else {
byteovfl[i] = 0;
}
}
if (novfl) {
if (ovfl_capacity < novfl) {
ovfl_capacity = novfl + 10;
free(spfixin_ovfl);
spfixin_ovfl = (unsigned char*) emalloc(ovfl_capacity * (1 + localgid_size) *
sizeof(unsigned char));
}
int bs = byteovfl[nrnmpi_myid_];
/*
note that the spikeout_fixed buffer is one since the overflow
is contiguous to the first part. But the spfixin_ovfl is
completely separate from the spikein_fixed since the latter
dynamically changes its size during a run.
*/
MPI_Allgatherv(spikeout_fixed + ag_send_size,
bs,
MPI_BYTE,
spfixin_ovfl,
byteovfl,
displs,
MPI_BYTE,
nrnmpi_comm);
}
ovfl = novfl;
return ntot;
}
int nrnmpi_int_allmax_impl(int x) {
int result;
MPI_Allreduce(&x, &result, 1, MPI_INT, MPI_MAX, nrnmpi_comm);
return result;
}
extern void nrnmpi_int_alltoall_impl(int* s, int* r, int n) {
MPI_Alltoall(s, n, MPI_INT, r, n, MPI_INT, nrnmpi_comm);
}
extern void nrnmpi_int_alltoallv_impl(const int* s,
const int* scnt,
const int* sdispl,
int* r,
int* rcnt,
int* rdispl) {
MPI_Alltoallv(s, scnt, sdispl, MPI_INT, r, rcnt, rdispl, MPI_INT, nrnmpi_comm);
}
extern void nrnmpi_dbl_alltoallv_impl(double* s,
int* scnt,
int* sdispl,
double* r,
int* rcnt,
int* rdispl) {
MPI_Alltoallv(s, scnt, sdispl, MPI_DOUBLE, r, rcnt, rdispl, MPI_DOUBLE, nrnmpi_comm);
}
/* following are for the partrans */
void nrnmpi_int_allgather_impl(int* s, int* r, int n) {
MPI_Allgather(s, n, MPI_INT, r, n, MPI_INT, nrnmpi_comm);
}
double nrnmpi_dbl_allmin_impl(double x) {
double result;
MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, MPI_MIN, nrnmpi_comm);
return result;
}
double nrnmpi_dbl_allmax_impl(double x) {
double result;
MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, MPI_MAX, nrnmpi_comm);
return result;
}
void nrnmpi_barrier_impl() {
MPI_Barrier(nrnmpi_comm);
}
double nrnmpi_dbl_allreduce_impl(double x, int type) {
double result;
MPI_Op tt;
if (type == 1) {
tt = MPI_SUM;
} else if (type == 2) {
tt = MPI_MAX;
} else {
tt = MPI_MIN;
}
MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, tt, nrnmpi_comm);
return result;
}
void nrnmpi_dbl_allreduce_vec_impl(double* src, double* dest, int cnt, int type) {
MPI_Op tt;
assert(src != dest);
if (type == 1) {
tt = MPI_SUM;
} else if (type == 2) {
tt = MPI_MAX;
} else {
tt = MPI_MIN;
}
MPI_Allreduce(src, dest, cnt, MPI_DOUBLE, tt, nrnmpi_comm);
return;
}
void nrnmpi_long_allreduce_vec_impl(long* src, long* dest, int cnt, int type) {
MPI_Op tt;
assert(src != dest);
if (type == 1) {
tt = MPI_SUM;
} else if (type == 2) {
tt = MPI_MAX;
} else {
tt = MPI_MIN;
}
MPI_Allreduce(src, dest, cnt, MPI_LONG, tt, nrnmpi_comm);
return;
}
#if NRN_MULTISEND
static MPI_Comm multisend_comm;
void nrnmpi_multisend_comm_impl() {
if (!multisend_comm) {
MPI_Comm_dup(MPI_COMM_WORLD, &multisend_comm);
}
}
void nrnmpi_multisend_impl(NRNMPI_Spike* spk, int n, int* hosts) {
//dong
{
Instrumentor::phase p("nrnmpi_multisend");
MPI_Request r;
for (int i = 0; i < n; ++i) {
MPI_Isend(spk, 1, spike_type, hosts[i], 1, multisend_comm, &r);
MPI_Request_free(&r);
}
}
}
//dong
void nrnmpi_multisend_impl_j(NRNMPI_Spike* spk, int n, int* hosts, MPI_Comm* pcomm) {
{
Instrumentor::phase p("nrnmpi_multisend");
MPI_Request r;
for (int i = 0; i < n; ++i) {
MPI_Isend(spk, 1, spike_type, hosts[i], 1, *pcomm, &r);
MPI_Request_free(&r);
}
}
}
int nrnmpi_multisend_single_advance_impl(NRNMPI_Spike* spk) {
int flag = 0;
//dong
{
Instrumentor::phase p("nrnmpi_multisend_advance");
MPI_Status status;
MPI_Iprobe(MPI_ANY_SOURCE, 1, multisend_comm, &flag, &status);
if (flag) {
MPI_Recv(spk, 1, spike_type, MPI_ANY_SOURCE, 1, multisend_comm, &status);
}
}
return flag;
}
//dong
int nrnmpi_multisend_single_advance_impl_j(NRNMPI_Spike* spk, MPI_Comm* pcomm) {
int flag = 0;
{
Instrumentor::phase p("nrnmpi_multisend_advance_j");
MPI_Status status;
MPI_Iprobe(MPI_ANY_SOURCE, 1, *pcomm, &flag, &status);
if (flag) {
MPI_Recv(spk, 1, spike_type, MPI_ANY_SOURCE, 1, *pcomm, &status);
}
}
return flag;
}
int nrnmpi_multisend_conserve_impl(int nsend, int nrecv) {
int tcnts[2];
tcnts[0] = nsend - nrecv;
MPI_Allreduce(tcnts, tcnts + 1, 1, MPI_INT, MPI_SUM, multisend_comm);
return tcnts[1];
}
//dong
int nrnmpi_multisend_conserve_impl_j(int nsend, int nrecv, MPI_Comm* pcomm) {
int tcnts[2];
tcnts[0] = nsend - nrecv;
MPI_Allreduce(tcnts, tcnts + 1, 1, MPI_INT, MPI_SUM, *pcomm);
return tcnts[1];
}
#endif /*NRN_MULTISEND*/
} // namespace coreneuron
| 30.673123
| 100
| 0.570019
|
phoenixdong
|
0c8cffd5adea2a57dd600d70f915d4de39410f54
| 4,060
|
cpp
|
C++
|
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
|
9heart/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 3
|
2018-10-05T15:03:27.000Z
|
2019-03-19T11:01:56.000Z
|
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
|
pakoito/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 1
|
2016-01-28T14:39:49.000Z
|
2016-01-28T22:12:07.000Z
|
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
|
adderly/DT3
|
e2605be091ec903d3582e182313837cbaf790857
|
[
"MIT"
] | 3
|
2016-01-25T16:44:51.000Z
|
2021-01-29T19:59:45.000Z
|
//==============================================================================
///
/// File: MemoryAllocatorTrace_cmd.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/System/Command.hpp"
#ifdef DT3_COMMANDS
#include "DT3Core/System/Factory.hpp"
#include "DT3Core/Types/Utility/CommandResult.hpp"
#include "DT3Core/Types/Utility/CommandRegistry.hpp"
#include "DT3Core/Types/Utility/CommandContext.hpp"
#include "DT3Core/Types/Memory/MemoryAllocatorTrace.hpp"
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
//==============================================================================
class MemoryAllocatorTrace_cmd: public Command {
public:
DEFINE_TYPE(MemoryAllocatorTrace_cmd,Command);
DEFINE_CREATE
void register_commands (void) {
CommandRegistry::register_command("CheckMemory", &MemoryAllocatorTrace_cmd::do_check_memory);
CommandRegistry::register_command("EnableCheckMemory", &MemoryAllocatorTrace_cmd::do_enable_check_memory);
CommandRegistry::register_command("DisableCheckMemory", &MemoryAllocatorTrace_cmd::do_disable_check_memory);
}
static CommandResult do_check_memory (CommandContext &ctx, const CommandParams &p);
static CommandResult do_enable_check_memory (CommandContext &ctx, const CommandParams &p);
static CommandResult do_disable_check_memory (CommandContext &ctx, const CommandParams &p);
};
//==============================================================================
//==============================================================================
IMPLEMENT_FACTORY_COMMAND(MemoryAllocatorTrace_cmd)
//==============================================================================
//==============================================================================
CommandResult MemoryAllocatorTrace_cmd::do_check_memory (CommandContext &ctx, const CommandParams &p)
{
if (p.count() != 1) {
return CommandResult(false, "Usage: CheckMemory", CommandResult::UPDATE_NONE);
}
MemoryAllocatorTrace::check_allocations();
return CommandResult(false, "CheckMemory Done", CommandResult::UPDATE_NONE);
}
//==============================================================================
//==============================================================================
CommandResult MemoryAllocatorTrace_cmd::do_enable_check_memory (CommandContext &ctx, const CommandParams &p)
{
if (p.count() != 1) {
return CommandResult(false, "Usage: EnableCheckMemory", CommandResult::UPDATE_NONE);
}
MemoryAllocatorTrace::enable_check_allocations(true);
return CommandResult(false, "Check Memory Enabled", CommandResult::UPDATE_NONE);
}
//==============================================================================
//==============================================================================
CommandResult MemoryAllocatorTrace_cmd::do_disable_check_memory (CommandContext &ctx, const CommandParams &p)
{
if (p.count() != 1) {
return CommandResult(false, "Usage: DisableCheckMemory", CommandResult::UPDATE_NONE);
}
MemoryAllocatorTrace::enable_check_allocations(false);
return CommandResult(false, "Check Memory Disabled", CommandResult::UPDATE_NONE);
}
//==============================================================================
//==============================================================================
} // DT3
#endif // DT3_COMMANDS
| 40.6
| 121
| 0.49064
|
9heart
|
0c905f8209cd7f77de147527063813523e9fe606
| 4,602
|
cc
|
C++
|
src/libcsg/modules/io/gmxtrajectoryreader.cc
|
vaidyanathanms/votca.csg
|
7af91bfecd620b820968956cd96ce7b3bce28a59
|
[
"Apache-2.0"
] | null | null | null |
src/libcsg/modules/io/gmxtrajectoryreader.cc
|
vaidyanathanms/votca.csg
|
7af91bfecd620b820968956cd96ce7b3bce28a59
|
[
"Apache-2.0"
] | null | null | null |
src/libcsg/modules/io/gmxtrajectoryreader.cc
|
vaidyanathanms/votca.csg
|
7af91bfecd620b820968956cd96ce7b3bce28a59
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* 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 <cstdlib>
#include <iostream>
#include <votca/csg/topology.h>
#include "gmxtrajectoryreader.h"
namespace votca { namespace csg {
using namespace std;
bool GMXTrajectoryReader::Open(const string &file)
{
_filename = file;
return true;
}
void GMXTrajectoryReader::Close()
{
close_trx(_gmx_status);
}
bool GMXTrajectoryReader::FirstFrame(Topology &conf)
{
#if GMX == 50
output_env_t oenv;
// _snew("oenv", oenv, 1);
//oenv = (output_env_t)malloc(sizeof(*oenv));
output_env_init_default (&oenv);
if(!read_first_frame(oenv, &_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F))
throw std::runtime_error(string("cannot open ") + _filename);
//sfree(oenv);
free(oenv);
#elif GMX == 45
set_program_name("VOTCA");
output_env_t oenv;
// _snew("oenv", oenv, 1);
oenv = (output_env_t)malloc(sizeof(*oenv));
output_env_init_default (oenv);
if(!read_first_frame(oenv, &_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F))
throw std::runtime_error(string("cannot open ") + _filename);
//sfree(oenv);
free(oenv);
#elif GMX == 40
set_program_name("VOTCA");
if(!read_first_frame(&_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F))
throw std::runtime_error(string("cannot open ") + _filename);
#else
#error Unsupported GMX version
#endif
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setBox(m);
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
cout << endl;
if(_gmx_frame.natoms != (int)conf.Beads().size())
throw std::runtime_error("number of beads in trajectory do not match topology");
//conf.HasPos(true);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setF(f);
}
if(_gmx_frame.bV) {
double v[3] = { _gmx_frame.v[i][XX], _gmx_frame.v[i][YY], _gmx_frame.v[i][ZZ] };
conf.getBead(i)->setVel(v);
}
}
return true;
}
bool GMXTrajectoryReader::NextFrame(Topology &conf)
{
#if GMX == 50
output_env_t oenv;
//_snew("oenv", oenv, 1);
//oenv = (output_env_t)malloc(sizeof(*oenv));
output_env_init_default (&oenv);
if(!read_next_frame(oenv, _gmx_status,&_gmx_frame))
return false;
//sfree(oenv);
free(oenv);
#elif GMX == 45
output_env_t oenv;
//_snew("oenv", oenv, 1);
oenv = (output_env_t)malloc(sizeof(*oenv));
output_env_init_default (oenv);
if(!read_next_frame(oenv, _gmx_status,&_gmx_frame))
return false;
//sfree(oenv);
free(oenv);
#elif GMX == 40
if(!read_next_frame(_gmx_status,&_gmx_frame))
return false;
#else
#error Unsupported GMX version
#endif
matrix m;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
m[i][j] = _gmx_frame.box[j][i];
conf.setTime(_gmx_frame.time);
conf.setStep(_gmx_frame.step);
conf.setBox(m);
//conf.HasF(_gmx_frame.bF);
for(int i=0; i<_gmx_frame.natoms; i++) {
double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] };
conf.getBead(i)->setPos(r);
if(_gmx_frame.bF) {
double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] };
conf.getBead(i)->setF(f);
}
if(_gmx_frame.bV) {
double v[3] = { _gmx_frame.v[i][XX], _gmx_frame.v[i][YY], _gmx_frame.v[i][ZZ] };
conf.getBead(i)->setVel(v);
}
}
return true;
}
}}
| 29.312102
| 119
| 0.621034
|
vaidyanathanms
|
0c9393362bdc1167bcb1477e53f488fbeb0a6185
| 1,228
|
hpp
|
C++
|
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2015 Sebastian Schlenkrich
*/
/*! \file quasigaussianmodels.hpp
\brief bindings of templatised quasi Gaussian models
*/
#ifndef quantlib_templatequasigaussianmodels_hpp
#define quantlib_templatequasigaussianmodels_hpp
//#include <ql/experimental/templatehullwhite/adtageo/adtageo.hpp>
//#include <ql/experimental/template/auxilliaries/MinimADVariable2.hpp>
#include <ql/types.hpp>
#include <ql/experimental/templatemodels/qgaussian/quasigaussianmodelT.hpp>
#include <ql/experimental/templatemodels/qgaussian/quasigaussianmodelabcdT.hpp>
#include <ql/experimental/templatemodels/stochasticprocessT.hpp>
#include <ql/experimental/templatemodels/qgaussian/qgswaptionmodelT.hpp>
namespace QuantLib {
// basic binding of template parameters
typedef QuasiGaussianModelT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQuasiGaussianModel;
typedef QuasiGaussianModelAbcdT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQuasiGaussianModelAbcd;
typedef QGSwaptionModelT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQGSwaptionModel;
}
#endif /* ifndef quantlib_templatequasigaussianmodels_hpp */
| 32.315789
| 109
| 0.799674
|
sschlenkrich
|
0c974dee941b748e38c15e52c5fc5a2e1a0767e4
| 736
|
hpp
|
C++
|
Boss/Msg/InternetOnline.hpp
|
3nprob/clboss
|
0435b6c074347ce82e490a5988534054e9d7348d
|
[
"MIT"
] | 108
|
2020-10-01T17:12:40.000Z
|
2022-03-30T09:18:03.000Z
|
Boss/Msg/InternetOnline.hpp
|
3nprob/clboss
|
0435b6c074347ce82e490a5988534054e9d7348d
|
[
"MIT"
] | 94
|
2020-10-03T13:40:30.000Z
|
2022-03-30T09:18:00.000Z
|
Boss/Msg/InternetOnline.hpp
|
3nprob/clboss
|
0435b6c074347ce82e490a5988534054e9d7348d
|
[
"MIT"
] | 17
|
2020-10-29T13:27:59.000Z
|
2022-03-18T13:05:03.000Z
|
#ifndef BOSS_MSG_INTERNETONLINE_HPP
#define BOSS_MSG_INTERNETONLINE_HPP
namespace Boss { namespace Msg {
/** struct Boss::Msg::InternetOnline
*
* @brief signals to everyone whether we are
* online or not.
*
* @desc Broadcast whenever online-ness changes.
*
* At startup, we are considered offline, so the
* first `Boss::Msg::InternetOnline` would have
* `online` as `true`.
* Conversely, if you are tracking this in your
* module, you can initialize your module to
* assume offline-ness, and once we do our
* initial online check the
* `Boss::Msg::InternetOnline` will update your
* module if we are online after all.
*/
struct InternetOnline {
bool online;
};
}}
#endif /* !defined(BOSS_MSG_INTERNETONLINE_HPP) */
| 24.533333
| 50
| 0.72962
|
3nprob
|
0ca2705b802f37d31871757c064c9bf7c0034271
| 1,104
|
cpp
|
C++
|
source/main_win64gl.cpp
|
Basez/Agnostik-Engine
|
10171bbeb73c590e75e9db5adf0135e0235f2884
|
[
"MIT"
] | 7
|
2015-06-29T09:45:09.000Z
|
2017-06-06T08:14:09.000Z
|
source/main_win64gl.cpp
|
Basez/Agnostik-Engine
|
10171bbeb73c590e75e9db5adf0135e0235f2884
|
[
"MIT"
] | null | null | null |
source/main_win64gl.cpp
|
Basez/Agnostik-Engine
|
10171bbeb73c590e75e9db5adf0135e0235f2884
|
[
"MIT"
] | null | null | null |
#include "shared.hpp"
#include "application.hpp"
#include "render_api_gl.hpp"
#include "config_manager.hpp"
#include "os_utils.hpp"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
using namespace AGN;
int WINAPI WinMain(HINSTANCE a_hInstance, HINSTANCE a_hPrevInstance, LPSTR a_lpCmdLine, int a_nShowCmd)
{
UNREFERENCED_PARAMETER(a_hInstance);
UNREFERENCED_PARAMETER(a_hPrevInstance);
UNREFERENCED_PARAMETER(a_lpCmdLine);
UNREFERENCED_PARAMETER(a_nShowCmd);
// load configurations
std::string currentFolder = OSUtils::getCurrentFolder();
std::string configFile = OSUtils::findFile("config.ini", currentFolder.c_str(), 3, 3);
std::string rootFolder = OSUtils::getDirectoryOfPath(configFile);
g_configManager.parseConfigFile(configFile);
// show log output
if (g_configManager.getConfigPropertyAsBool("enable_log_window"))
{
g_log.init(ELogTimeType::RunningTime, (uint8_t)ELoggerOutputType::Window | (uint8_t)ELoggerOutputType::OutputDebug);
}
IRenderAPI* renderAPI = new RenderAPIGL();
g_application.run(renderAPI);
g_application.cleanup();
delete renderAPI;
return 0;
}
| 26.926829
| 118
| 0.788043
|
Basez
|
0ca616bef9af611edc84b8db2fe0f0bc671b81e0
| 146
|
cpp
|
C++
|
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
|
Agesyne/HW
|
df9229c7f639f41ed85bae14b666bdaaf2e387b3
|
[
"MIT"
] | null | null | null |
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
|
Agesyne/HW
|
df9229c7f639f41ed85bae14b666bdaaf2e387b3
|
[
"MIT"
] | null | null | null |
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
|
Agesyne/HW
|
df9229c7f639f41ed85bae14b666bdaaf2e387b3
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include <iostream>
int initNumber(char text[])
{
int number = 0;
printf("%s", text);
scanf("%d", &number);
return number;
}
| 14.6
| 27
| 0.630137
|
Agesyne
|
0cab511c4195433c83ee5f153225ccf564c6fdcb
| 20,030
|
cpp
|
C++
|
GMan Map Maker/Unit2.cpp
|
JustoSenka/GMan-RPG-Game
|
d54f10093814fef7908e63f8419bd3fe59694d5d
|
[
"MIT"
] | null | null | null |
GMan Map Maker/Unit2.cpp
|
JustoSenka/GMan-RPG-Game
|
d54f10093814fef7908e63f8419bd3fe59694d5d
|
[
"MIT"
] | null | null | null |
GMan Map Maker/Unit2.cpp
|
JustoSenka/GMan-RPG-Game
|
d54f10093814fef7908e63f8419bd3fe59694d5d
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <SysUtils.hpp> // If exist command here
#include "Unit2.h"
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm2::FormShow(TObject *Sender)
{
// Items
IList->Clear();
for (int i = 1; i <= Form1->itemnum; i++)
IList->Items->Add(Form1->I[i].name);
// Enemies
EList->Clear();
for (int i = 1; i <= Form1->entypenum; i++)
EList->Items->Add(Form1->E[i].name);
}
//---------------------------------------------------------------------------
void __fastcall TForm2::IListClick(TObject *Sender)
{
if (IList->ItemIndex > -1)
{
lvl->Text = Form1->I[IList->ItemIndex + 1].lvl;
att->Text = Form1->I[IList->ItemIndex + 1].att;
def->Text = Form1->I[IList->ItemIndex + 1].def;
dem->Text = Form1->I[IList->ItemIndex + 1].demage;
price->Text = Form1->I[IList->ItemIndex + 1].price;
hp->Text = Form1->I[IList->ItemIndex + 1].hp;
mp->Text = Form1->I[IList->ItemIndex + 1].mp;
sta->Text = Form1->I[IList->ItemIndex + 1].sta;
name->Text = Form1->I[IList->ItemIndex + 1].name;
selicon = Form1->I[IList->ItemIndex + 1].icon;
TypeCombo->ItemIndex = Form1->I[IList->ItemIndex + 1].type;
Image->Picture->Bitmap = Items[selicon];
//Image->Picture->LoadFromFile("Items\\I" + IntToStr(selicon) + ".bmp");
}
TypeComboChange(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TForm2::TypeComboChange(TObject *Sender)
{
lvl->Enabled = true;
att->Enabled = true;
def->Enabled = true;
dem->Enabled = true;
hp->Enabled = true;
mp->Enabled = true;
sta->Enabled = true;
if (TypeCombo->ItemIndex == 0)
{
lvl->Enabled = false; lvl->Text = 0;
att->Enabled = false; att->Text = 0;
def->Enabled = false; def->Text = 0;
dem->Enabled = false; dem->Text = 0;
hp->Enabled = false; hp->Text = 0;
mp->Enabled = false; mp->Text = 0;
sta->Enabled = false; sta->Text = 0;
}
if (TypeCombo->ItemIndex == 10)
{
lvl->Enabled = false; lvl->Text = 0;
att->Enabled = false; att->Text = 0;
def->Enabled = false; def->Text = 0;
dem->Enabled = false; dem->Text = 0;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::addClick(TObject *Sender)
{
Form1->itemnum++;
Form1->I[Form1->itemnum].lvl = StrToInt(lvl->Text);
Form1->I[Form1->itemnum].att = StrToInt(att->Text);
Form1->I[Form1->itemnum].def = StrToInt(def->Text);
Form1->I[Form1->itemnum].demage = StrToInt(dem->Text);
Form1->I[Form1->itemnum].price = StrToInt(price->Text);
Form1->I[Form1->itemnum].hp = StrToInt(hp->Text);
Form1->I[Form1->itemnum].mp = StrToInt(mp->Text);
Form1->I[Form1->itemnum].sta = StrToInt(sta->Text);
Form1->I[Form1->itemnum].type = TypeCombo->ItemIndex;
Form1->I[Form1->itemnum].name = name->Text;
Form1->I[Form1->itemnum].icon = selicon;
IList->Items->Add(Form1->I[Form1->itemnum].name);
IList->ItemIndex = Form1->itemnum - 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::delClick(TObject *Sender)
{
if (IList->ItemIndex > -1)
{
Form1->itemnum--;
for (int h = 1; h <= Form1->entypenum; h++)
if (Form1->E[h].item[IList->ItemIndex + 1] != 0) Form1->E[h].idropc--;
for (int i = IList->ItemIndex + 1; i <= Form1->itemnum; i++)
{
// Delete stats for items
Form1->I[i].lvl = Form1->I[i+1].lvl;
Form1->I[i].att = Form1->I[i+1].att;
Form1->I[i].def = Form1->I[i+1].def;
Form1->I[i].demage = Form1->I[i+1].demage;
Form1->I[i].price = Form1->I[i+1].price;
Form1->I[i].hp = Form1->I[i+1].hp;
Form1->I[i].mp = Form1->I[i+1].mp;
Form1->I[i].sta = Form1->I[i+1].sta;
Form1->I[i].type = Form1->I[i+1].type;
Form1->I[i].name = Form1->I[i+1].name;
Form1->I[i].icon = Form1->I[i+1].icon;
// And delete for enemy drops
for (int h = 1; h <= Form1->entypenum; h++)
Form1->E[h].item[i] = Form1->E[h].item[i + 1];
}
int a = IList->ItemIndex;
IList->Items->Delete(IList->ItemIndex);
IList->ItemIndex = a;
IListClick(Sender);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::saveClick(TObject *Sender)
{
Form1->I[IList->ItemIndex + 1].lvl = StrToInt(lvl->Text);
Form1->I[IList->ItemIndex + 1].att = StrToInt(att->Text);
Form1->I[IList->ItemIndex + 1].def = StrToInt(def->Text);
Form1->I[IList->ItemIndex + 1].demage = StrToInt(dem->Text);
Form1->I[IList->ItemIndex + 1].price = StrToInt(price->Text);
Form1->I[IList->ItemIndex + 1].hp = StrToInt(hp->Text);
Form1->I[IList->ItemIndex + 1].mp = StrToInt(mp->Text);
Form1->I[IList->ItemIndex + 1].sta = StrToInt(sta->Text);
Form1->I[IList->ItemIndex + 1].type = TypeCombo->ItemIndex;
Form1->I[IList->ItemIndex + 1].name = name->Text;
Form1->I[IList->ItemIndex + 1].icon = selicon;
IList->Items->Insert(IList->ItemIndex,name->Text);
int a = IList->ItemIndex - 1;
IList->Items->Delete(IList->ItemIndex);
IList->ItemIndex = a;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::IListMouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if (mouse == 0) sel = IList->ItemIndex;
mouse = 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::IListMouseUp(TObject *Sender, TMouseButton Button,
TShiftState Shift, int X, int Y)
{
mouse = 0;
sel = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::IListMouseMove(TObject *Sender, TShiftState Shift,
int X, int Y)
{
if (mouse == 1 && sel > -1)
{
int a;
AnsiString b;
if (sel > IList->ItemIndex)
{
// Replacing variables for items
a = Form1->I[sel].lvl; Form1->I[sel].lvl = Form1->I[sel + 1].lvl; Form1->I[sel + 1].lvl = a;
a = Form1->I[sel].att; Form1->I[sel].att = Form1->I[sel + 1].att; Form1->I[sel + 1].att = a;
a = Form1->I[sel].def; Form1->I[sel].def = Form1->I[sel + 1].def; Form1->I[sel + 1].def = a;
a = Form1->I[sel].demage; Form1->I[sel].demage = Form1->I[sel + 1].demage; Form1->I[sel + 1].demage = a;
a = Form1->I[sel].price; Form1->I[sel].price = Form1->I[sel + 1].price; Form1->I[sel + 1].price = a;
a = Form1->I[sel].hp; Form1->I[sel].hp = Form1->I[sel + 1].hp; Form1->I[sel + 1].hp = a;
a = Form1->I[sel].mp; Form1->I[sel].mp = Form1->I[sel + 1].mp; Form1->I[sel + 1].mp = a;
a = Form1->I[sel].sta; Form1->I[sel].sta = Form1->I[sel + 1].sta; Form1->I[sel + 1].sta = a;
a = Form1->I[sel].type; Form1->I[sel].type = Form1->I[sel + 1].type; Form1->I[sel + 1].type = a;
b = Form1->I[sel].name; Form1->I[sel].name = Form1->I[sel + 1].name; Form1->I[sel + 1].name = b;
a = Form1->I[sel].icon; Form1->I[sel].icon = Form1->I[sel + 1].icon; Form1->I[sel + 1].icon = a;
// And for enemy drop rates
for (int i = 1; i <= Form1->entypenum; i++)
{a = Form1->E[i].item[sel]; Form1->E[i].item[sel] = Form1->E[i].item[sel + 1]; Form1->E[i].item[sel + 1] = a;}
IList->Items->Exchange(sel ,sel - 1);
sel--;
}
else if (sel < IList->ItemIndex)
{
// Replacing variables for items
a = Form1->I[sel + 2].lvl; Form1->I[sel + 2].lvl = Form1->I[sel + 1].lvl; Form1->I[sel + 1].lvl = a;
a = Form1->I[sel + 2].att; Form1->I[sel + 2].att = Form1->I[sel + 1].att; Form1->I[sel + 1].att = a;
a = Form1->I[sel + 2].def; Form1->I[sel + 2].def = Form1->I[sel + 1].def; Form1->I[sel + 1].def = a;
a = Form1->I[sel + 2].demage; Form1->I[sel + 2].demage = Form1->I[sel + 1].demage; Form1->I[sel + 1].demage = a;
a = Form1->I[sel + 2].price; Form1->I[sel + 2].price = Form1->I[sel + 1].price; Form1->I[sel + 1].price = a;
a = Form1->I[sel + 2].hp; Form1->I[sel + 2].hp = Form1->I[sel + 1].hp; Form1->I[sel + 1].hp = a;
a = Form1->I[sel + 2].mp; Form1->I[sel + 2].mp = Form1->I[sel + 1].mp; Form1->I[sel + 1].mp = a;
a = Form1->I[sel + 2].sta; Form1->I[sel + 2].sta = Form1->I[sel + 1].sta; Form1->I[sel + 1].sta = a;
a = Form1->I[sel + 2].type; Form1->I[sel + 2].type = Form1->I[sel + 1].type; Form1->I[sel + 1].type = a;
b = Form1->I[sel + 2].name; Form1->I[sel + 2].name = Form1->I[sel + 1].name; Form1->I[sel + 1].name = b;
a = Form1->I[sel + 2].icon; Form1->I[sel + 2].icon = Form1->I[sel + 1].icon; Form1->I[sel + 1].icon = a;
// And for enemy drop rates
for (int i = 1; i <= Form1->entypenum; i++)
{a = Form1->E[i].item[sel + 2]; Form1->E[i].item[sel + 2] = Form1->E[i].item[sel + 1]; Form1->E[i].item[sel + 1] = a;}
IList->Items->Exchange(sel,sel + 1);
sel++;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::FormCreate(TObject *Sender)
{
// Items
for (int i = 1; i <= 2000; i++) if (FileExists("Items\\I" + IntToStr(i) + ".bmp")==true)
{
Items[i] = new Graphics::TBitmap;
Items[i]->LoadFromFile("Items\\I" + IntToStr(i) + ".bmp");
Items[i]->Transparent = true;
iconnum = i; // ??? I do not know what it is, but let it be..
}
// Enemies
for (int i = 1; i <= 200; i++) if (FileExists("Enemies\\En" + IntToStr(i) + ".bmp")==true)
{
EnType[i] = new Graphics::TBitmap;
EnType[i]->LoadFromFile("Enemies\\En" + IntToStr(i) + ".bmp");
EnType[i]->Transparent = true;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::loadClick(TObject *Sender)
{
if (OpenDialog1->Execute())
{
Image->Picture->LoadFromFile(OpenDialog1->FileName);
AnsiString s = OpenDialog1->FileName;
char c[15];
while (1)
{
c[0] = s[s.Length() - 4];
if (s[s.Length() - 5] == 'I')break;
c[0] = s[s.Length() - 5]; c[1] = s[s.Length() - 4];
if (s[s.Length() - 6] == 'I')break;
c[0] = s[s.Length() - 6]; c[1] = s[s.Length() - 5]; c[2] = s[s.Length() - 4];
if (s[s.Length() - 7] == 'I')break;
c[0] = s[s.Length() - 7]; c[1] = s[s.Length() - 6]; c[2] = s[s.Length() - 5]; c[3] = s[s.Length() - 4];
break;
}
s = c;
selicon = StrToInt(s);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EListClick(TObject *Sender)
{
if (EList->ItemIndex > -1)
{
Ehp->Text = Form1->E[EList->ItemIndex + 1].hpmax;
Espeed->Text = Form1->E[EList->ItemIndex + 1].speed;
Esight->Text = Form1->E[EList->ItemIndex + 1].sight;
Eatt->Text = Form1->E[EList->ItemIndex + 1].att;
Edef->Text = Form1->E[EList->ItemIndex + 1].def;
Edem->Text = Form1->E[EList->ItemIndex + 1].demage;
Eexp->Text = Form1->E[EList->ItemIndex + 1].exp;
Egold->Text = Form1->E[EList->ItemIndex + 1].gold;
selicon2 = Form1->E[EList->ItemIndex + 1].icon;
Ename->Text = Form1->E[EList->ItemIndex + 1].name;
ItemCombo->Clear();
for (int h = 1; h <= Form1->itemnum; h++)
if (Form1->E[EList->ItemIndex + 1].item[h] != 0)
ItemCombo->Items->Add(Form1->I[h].name);
ItemCombo->ItemIndex = 0;
ItemComboChange(Sender);
Image2->Picture->Bitmap = EnType[selicon2];
//Image2->Picture->LoadFromFile("Enemies\\En" + IntToStr(selicon2) + ".bmp");
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EListMouseDown(TObject *Sender,
TMouseButton Button, TShiftState Shift, int X, int Y)
{
if (mouse == 0) sel = EList->ItemIndex;
mouse = 1;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EListMouseUp(TObject *Sender, TMouseButton Button,
TShiftState Shift, int X, int Y)
{
mouse = 0;
sel = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EListMouseMove(TObject *Sender, TShiftState Shift,
int X, int Y)
{
if (mouse == 1 && sel > -1)
{
int a;
AnsiString b;
if (sel > EList->ItemIndex)
{
a = Form1->E[sel].hpmax; Form1->E[sel].hpmax = Form1->E[sel + 1].hpmax; Form1->E[sel + 1].hpmax = a;
a = Form1->E[sel].speed; Form1->E[sel].speed = Form1->E[sel + 1].speed; Form1->E[sel + 1].speed = a;
a = Form1->E[sel].sight; Form1->E[sel].sight = Form1->E[sel + 1].sight; Form1->E[sel + 1].sight = a;
a = Form1->E[sel].att; Form1->E[sel].att = Form1->E[sel + 1].att; Form1->E[sel + 1].att = a;
a = Form1->E[sel].def; Form1->E[sel].def = Form1->E[sel + 1].def; Form1->E[sel + 1].def = a;
a = Form1->E[sel].demage; Form1->E[sel].demage = Form1->E[sel + 1].demage; Form1->E[sel + 1].demage = a;
a = Form1->E[sel].exp; Form1->E[sel].exp = Form1->E[sel + 1].exp; Form1->E[sel + 1].exp = a;
a = Form1->E[sel].gold; Form1->E[sel].gold = Form1->E[sel + 1].gold; Form1->E[sel + 1].gold = a;
b = Form1->E[sel].name; Form1->E[sel].name = Form1->E[sel + 1].name; Form1->E[sel + 1].name = b;
a = Form1->E[sel].icon; Form1->E[sel].icon = Form1->E[sel + 1].icon; Form1->E[sel + 1].icon = a;
a = Form1->E[sel].idropc; Form1->E[sel].idropc = Form1->E[sel + 1].idropc; Form1->E[sel + 1].idropc = a;
for (int h = 1; h <= Form1->itemnum; h++)
{a = Form1->E[sel].item[h]; Form1->E[sel].item[h] = Form1->E[sel + 1].item[h]; Form1->E[sel + 1].item[h] = a;}
EList->Items->Exchange(sel ,sel - 1);
sel--;
}
else if (sel < EList->ItemIndex)
{
a = Form1->E[sel + 2].hpmax; Form1->E[sel + 2].hpmax = Form1->E[sel + 1].hpmax; Form1->E[sel + 1].hpmax = a;
a = Form1->E[sel + 2].speed; Form1->E[sel + 2].speed = Form1->E[sel + 1].speed; Form1->E[sel + 1].speed = a;
a = Form1->E[sel + 2].sight; Form1->E[sel + 2].sight = Form1->E[sel + 1].sight; Form1->E[sel + 1].sight = a;
a = Form1->E[sel + 2].att; Form1->E[sel + 2].att = Form1->E[sel + 1].att; Form1->E[sel + 1].att = a;
a = Form1->E[sel + 2].def; Form1->E[sel + 2].def = Form1->E[sel + 1].def; Form1->E[sel + 1].def = a;
a = Form1->E[sel + 2].demage; Form1->E[sel + 2].demage = Form1->E[sel + 1].demage; Form1->E[sel + 1].demage = a;
a = Form1->E[sel + 2].exp; Form1->E[sel + 2].exp = Form1->E[sel + 1].exp; Form1->E[sel + 1].exp = a;
a = Form1->E[sel + 2].gold; Form1->E[sel + 2].gold = Form1->E[sel + 1].gold; Form1->E[sel + 1].gold = a;
b = Form1->E[sel + 2].name; Form1->E[sel + 2].name = Form1->E[sel + 1].name; Form1->E[sel + 1].name = b;
a = Form1->E[sel + 2].icon; Form1->E[sel + 2].icon = Form1->E[sel + 1].icon; Form1->E[sel + 1].icon = a;
a = Form1->E[sel + 2].idropc; Form1->E[sel + 2].idropc = Form1->E[sel + 1].idropc; Form1->E[sel + 1].idropc = a;
for (int h = 1; h <= Form1->itemnum; h++)
{a = Form1->E[sel + 2].item[h]; Form1->E[sel + 2].item[h] = Form1->E[sel + 1].item[h]; Form1->E[sel + 1].item[h] = a;}
EList->Items->Exchange(sel ,sel + 1);
sel++;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::ItemComboChange(TObject *Sender)
{
if (ItemCombo->ItemIndex > -1)
{
for (int i = 1; i <= Form1->itemnum; i++)
if (Form1->E[EList->ItemIndex + 1].item[i] != 0 && Form1->I[i].name == ItemCombo->Items->Strings[ItemCombo->ItemIndex])
{
Edrop->Text = Form1->E[EList->ItemIndex + 1].item[i];
selic = i;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EaddClick(TObject *Sender)
{
/*
Form1->itemnum++;
Form1->I[Form1->itemnum].lvl = StrToInt(lvl->Text);
Form1->I[Form1->itemnum].att = StrToInt(att->Text);
Form1->I[Form1->itemnum].def = StrToInt(def->Text);
Form1->I[Form1->itemnum].demage = StrToInt(dem->Text);
Form1->I[Form1->itemnum].price = StrToInt(price->Text);
Form1->I[Form1->itemnum].hp = StrToInt(hp->Text);
Form1->I[Form1->itemnum].mp = StrToInt(mp->Text); Reikia redaguoti
Form1->I[Form1->itemnum].sta = StrToInt(sta->Text); Kaip su menu
Form1->I[Form1->itemnum].type = TypeCombo->ItemIndex; idesi
Form1->I[Form1->itemnum].name = name->Text; pakeisti vietoj
Form1->I[Form1->itemnum].icon = selicon; I - E
IList->Items->Add(Form1->I[Form1->itemnum].name);
IList->ItemIndex = Form1->itemnum - 1;
*/
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EdelClick(TObject *Sender)
{ /*
if (IList->ItemIndex > -1)
{
Form1->itemnum--;
for (int i = IList->ItemIndex + 1; i <= Form1->itemnum; i++)
{
Form1->I[i].lvl = Form1->I[i+1].lvl;
Form1->I[i].att = Form1->I[i+1].att;
Form1->I[i].def = Form1->I[i+1].def;
Form1->I[i].demage = Form1->I[i+1].demage;
Form1->I[i].price = Form1->I[i+1].price;
Form1->I[i].hp = Form1->I[i+1].hp;
Form1->I[i].mp = Form1->I[i+1].mp; Taip pat
Form1->I[i].sta = Form1->I[i+1].sta; redaguoti
Form1->I[i].type = Form1->I[i+1].type;
Form1->I[i].name = Form1->I[i+1].name;
Form1->I[i].icon = Form1->I[i+1].icon;
}
int a = IList->ItemIndex;
IList->Items->Delete(IList->ItemIndex);
IList->ItemIndex = a;
IListClick(Sender);
} */
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EsaveClick(TObject *Sender)
{
Form1->E[EList->ItemIndex + 1].hpmax = StrToInt(Ehp->Text);
Form1->E[EList->ItemIndex + 1].speed = StrToInt(Espeed->Text);
Form1->E[EList->ItemIndex + 1].sight = StrToInt(Esight->Text);
Form1->E[EList->ItemIndex + 1].att = StrToInt(Eatt->Text);
Form1->E[EList->ItemIndex + 1].def = StrToInt(Edef->Text);
Form1->E[EList->ItemIndex + 1].demage = StrToInt(Edem->Text);
Form1->E[EList->ItemIndex + 1].exp = StrToInt(Eexp->Text);
Form1->E[EList->ItemIndex + 1].gold = StrToInt(Egold->Text);
Form1->E[EList->ItemIndex + 1].name = Ename->Text;
Form1->E[EList->ItemIndex + 1].icon = selicon2;
EList->Items->Insert(EList->ItemIndex,Ename->Text);
int a = EList->ItemIndex - 1;
EList->Items->Delete(EList->ItemIndex);
EList->ItemIndex = a;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EloadClick(TObject *Sender)
{
if (OpenDialog1->Execute())
{
Image2->Picture->LoadFromFile(OpenDialog1->FileName);
AnsiString s = OpenDialog1->FileName;
char c[15];
while (1)
{
c[0] = s[s.Length() - 4];
if (s[s.Length() - 5] == 'n')break;
c[0] = s[s.Length() - 5]; c[1] = s[s.Length() - 4];
if (s[s.Length() - 6] == 'n')break;
c[0] = s[s.Length() - 6]; c[1] = s[s.Length() - 5]; c[2] = s[s.Length() - 4];
if (s[s.Length() - 7] == 'n')break;
c[0] = s[s.Length() - 7]; c[1] = s[s.Length() - 6]; c[2] = s[s.Length() - 5]; c[3] = s[s.Length() - 4];
break;
}
s = c;
selicon2 = StrToInt(s);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm2::EokClick(TObject *Sender)
{
Form1->E[EList->ItemIndex + 1].item[selic] = StrToInt(Edrop->Text);
if (StrToInt(Edrop->Text) == 0)
{
ItemCombo->Items->Delete(ItemCombo->ItemIndex);
Form1->E[EList->ItemIndex + 1].idropc--;
}
//ItemCombo->ItemIndex = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
Form1->E[EList->ItemIndex + 1].item[IList->ItemIndex + 1] = 100;
Form1->E[EList->ItemIndex + 1].idropc++;
ItemCombo->Items->Add(IList->Items->Strings[IList->ItemIndex]);
}
//---------------------------------------------------------------------------
| 36.752294
| 127
| 0.522466
|
JustoSenka
|
0cafd91af3f1d372d401af345bc4533839eab7ab
| 10,259
|
cxx
|
C++
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | 3
|
2016-05-30T15:12:16.000Z
|
2022-03-22T08:11:13.000Z
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | 21
|
2016-06-13T11:33:45.000Z
|
2017-05-23T09:46:52.000Z
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimMaterialLayerSet.hxx"
#include "intendedbldgelemtypes.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimMaterialLayerSet
//
const SimMaterialLayerSet::MaterialLayers_optional& SimMaterialLayerSet::
MaterialLayers () const
{
return this->MaterialLayers_;
}
SimMaterialLayerSet::MaterialLayers_optional& SimMaterialLayerSet::
MaterialLayers ()
{
return this->MaterialLayers_;
}
void SimMaterialLayerSet::
MaterialLayers (const MaterialLayers_type& x)
{
this->MaterialLayers_.set (x);
}
void SimMaterialLayerSet::
MaterialLayers (const MaterialLayers_optional& x)
{
this->MaterialLayers_ = x;
}
void SimMaterialLayerSet::
MaterialLayers (::std::auto_ptr< MaterialLayers_type > x)
{
this->MaterialLayers_.set (x);
}
const SimMaterialLayerSet::LayerSetName_optional& SimMaterialLayerSet::
LayerSetName () const
{
return this->LayerSetName_;
}
SimMaterialLayerSet::LayerSetName_optional& SimMaterialLayerSet::
LayerSetName ()
{
return this->LayerSetName_;
}
void SimMaterialLayerSet::
LayerSetName (const LayerSetName_type& x)
{
this->LayerSetName_.set (x);
}
void SimMaterialLayerSet::
LayerSetName (const LayerSetName_optional& x)
{
this->LayerSetName_ = x;
}
void SimMaterialLayerSet::
LayerSetName (::std::auto_ptr< LayerSetName_type > x)
{
this->LayerSetName_.set (x);
}
const SimMaterialLayerSet::IntendedBldgElemTypes_optional& SimMaterialLayerSet::
IntendedBldgElemTypes () const
{
return this->IntendedBldgElemTypes_;
}
SimMaterialLayerSet::IntendedBldgElemTypes_optional& SimMaterialLayerSet::
IntendedBldgElemTypes ()
{
return this->IntendedBldgElemTypes_;
}
void SimMaterialLayerSet::
IntendedBldgElemTypes (const IntendedBldgElemTypes_type& x)
{
this->IntendedBldgElemTypes_.set (x);
}
void SimMaterialLayerSet::
IntendedBldgElemTypes (const IntendedBldgElemTypes_optional& x)
{
this->IntendedBldgElemTypes_ = x;
}
void SimMaterialLayerSet::
IntendedBldgElemTypes (::std::auto_ptr< IntendedBldgElemTypes_type > x)
{
this->IntendedBldgElemTypes_.set (x);
}
const SimMaterialLayerSet::CompositeThermalTrans_optional& SimMaterialLayerSet::
CompositeThermalTrans () const
{
return this->CompositeThermalTrans_;
}
SimMaterialLayerSet::CompositeThermalTrans_optional& SimMaterialLayerSet::
CompositeThermalTrans ()
{
return this->CompositeThermalTrans_;
}
void SimMaterialLayerSet::
CompositeThermalTrans (const CompositeThermalTrans_type& x)
{
this->CompositeThermalTrans_.set (x);
}
void SimMaterialLayerSet::
CompositeThermalTrans (const CompositeThermalTrans_optional& x)
{
this->CompositeThermalTrans_ = x;
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimMaterialLayerSet
//
SimMaterialLayerSet::
SimMaterialLayerSet ()
: ::schema::simxml::SimModelCore::SimResourceObject (),
MaterialLayers_ (this),
LayerSetName_ (this),
IntendedBldgElemTypes_ (this),
CompositeThermalTrans_ (this)
{
}
SimMaterialLayerSet::
SimMaterialLayerSet (const RefId_type& RefId)
: ::schema::simxml::SimModelCore::SimResourceObject (RefId),
MaterialLayers_ (this),
LayerSetName_ (this),
IntendedBldgElemTypes_ (this),
CompositeThermalTrans_ (this)
{
}
SimMaterialLayerSet::
SimMaterialLayerSet (const SimMaterialLayerSet& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimResourceObject (x, f, c),
MaterialLayers_ (x.MaterialLayers_, f, this),
LayerSetName_ (x.LayerSetName_, f, this),
IntendedBldgElemTypes_ (x.IntendedBldgElemTypes_, f, this),
CompositeThermalTrans_ (x.CompositeThermalTrans_, f, this)
{
}
SimMaterialLayerSet::
SimMaterialLayerSet (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::SimModelCore::SimResourceObject (e, f | ::xml_schema::flags::base, c),
MaterialLayers_ (this),
LayerSetName_ (this),
IntendedBldgElemTypes_ (this),
CompositeThermalTrans_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimMaterialLayerSet::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::SimModelCore::SimResourceObject::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// MaterialLayers
//
if (n.name () == "MaterialLayers" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< MaterialLayers_type > r (
MaterialLayers_traits::create (i, f, this));
if (!this->MaterialLayers_)
{
this->MaterialLayers_.set (r);
continue;
}
}
// LayerSetName
//
if (n.name () == "LayerSetName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< LayerSetName_type > r (
LayerSetName_traits::create (i, f, this));
if (!this->LayerSetName_)
{
this->LayerSetName_.set (r);
continue;
}
}
// IntendedBldgElemTypes
//
if (n.name () == "IntendedBldgElemTypes" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< IntendedBldgElemTypes_type > r (
IntendedBldgElemTypes_traits::create (i, f, this));
if (!this->IntendedBldgElemTypes_)
{
this->IntendedBldgElemTypes_.set (r);
continue;
}
}
// CompositeThermalTrans
//
if (n.name () == "CompositeThermalTrans" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->CompositeThermalTrans_)
{
this->CompositeThermalTrans_.set (CompositeThermalTrans_traits::create (i, f, this));
continue;
}
}
break;
}
}
SimMaterialLayerSet* SimMaterialLayerSet::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimMaterialLayerSet (*this, f, c);
}
SimMaterialLayerSet& SimMaterialLayerSet::
operator= (const SimMaterialLayerSet& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::SimModelCore::SimResourceObject& > (*this) = x;
this->MaterialLayers_ = x.MaterialLayers_;
this->LayerSetName_ = x.LayerSetName_;
this->IntendedBldgElemTypes_ = x.IntendedBldgElemTypes_;
this->CompositeThermalTrans_ = x.CompositeThermalTrans_;
}
return *this;
}
SimMaterialLayerSet::
~SimMaterialLayerSet ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 28.497222
| 127
| 0.615167
|
EnEff-BIM
|
0cb357f43d5613478f4a975d5b5d8ec61c4b4c4c
| 3,256
|
cpp
|
C++
|
test/test02.cpp
|
subject721/flow-orchestrator
|
cadc646db5eece510c1dc1edf7bacf5060a7915c
|
[
"BSD-3-Clause"
] | 3
|
2021-10-05T08:13:56.000Z
|
2022-02-07T22:41:03.000Z
|
test/test02.cpp
|
subject721/flow-orchestrator
|
cadc646db5eece510c1dc1edf7bacf5060a7915c
|
[
"BSD-3-Clause"
] | null | null | null |
test/test02.cpp
|
subject721/flow-orchestrator
|
cadc646db5eece510c1dc1edf7bacf5060a7915c
|
[
"BSD-3-Clause"
] | 1
|
2022-02-07T22:41:05.000Z
|
2022-02-07T22:41:05.000Z
|
/*
* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2021, Stefan Seitz
*
*/
#include <common/common.hpp>
#include <dpdk/dpdk_common.hpp>
#include <flow_executor.hpp>
class executor_test
{
public:
executor_test() : executor(*this) {}
void run_test(const std::vector< lcore_info >& available_lcores) {
try {
executor.setup({0, 0}, 1, available_lcores);
executor.start(&executor_test::run_endpoint_tasks, &executor_test::run_distributor_tasks);
rte_delay_us_sleep(10000);
executor.stop();
} catch ( const std::exception& e ) { log(LOG_ERROR, "test failed: {}", e.what()); }
}
private:
void run_endpoint_tasks(const size_t* indicies, size_t num_indicies, std::atomic_bool& run_flag) {
for ( size_t i = 0; i < num_indicies; ++i ) {
size_t index = indicies[i];
log(LOG_INFO, "Running endpoint task: {} on lcore {}", index, rte_lcore_id());
rte_delay_us_sleep(200);
}
}
void run_distributor_tasks(const size_t* indicies, size_t num_indicies, std::atomic_bool& run_flag) {
for ( size_t i = 0; i < num_indicies; ++i ) {
size_t index = indicies[i];
log(LOG_INFO, "Running distributor task: {} on lcore {}", index, rte_lcore_id());
rte_delay_us_sleep(200);
}
}
flow_executor< reduced_core_policy, executor_test > executor;
};
int main(int argc, char** argv) {
try {
dpdk_eal_init({"--no-shconf", "--in-memory", "-l", "1,2,3,4"});
} catch ( const std::exception& e ) {
log(LOG_ERROR, "could not init dpdk eal: {}", e.what());
return 1;
}
executor_test test;
test.run_test(lcore_info::get_available_worker_lcores());
try {
mbuf_ring ring("my_ring", 0, 512);
dpdk_packet_mempool mempool(512, 0, 1024, 32);
static_mbuf_vec< 32 > mbuf_vec;
static_mbuf_vec< 32 > mbuf_vec_out;
uint16_t burst_size = 16;
log(LOG_INFO, "mempool alloc stats after init: {}/{}", mempool.get_num_allocated(), mempool.get_capacity());
if ( mempool.bulk_alloc(mbuf_vec, burst_size) ) {
throw std::runtime_error("could not alloc mbufs");
}
log(LOG_INFO, "mempool alloc stats after alloc: {}/{}", mempool.get_num_allocated(), mempool.get_capacity());
if ( ring.enqueue(mbuf_vec) != burst_size ) {
throw std::runtime_error("queuing failed");
}
log(LOG_INFO, "mempool alloc stats after queue: {}/{}", mempool.get_num_allocated(), mempool.get_capacity());
if ( ring.dequeue(mbuf_vec_out) != burst_size ) {
throw std::runtime_error("dequeuing failed");
}
log(LOG_INFO, "mempool alloc stats after dequeue: {}/{}", mempool.get_num_allocated(), mempool.get_capacity());
if ( mbuf_vec_out.size() != burst_size ) {
throw std::runtime_error("mbuf vec wrong size");
}
mbuf_vec_out.free();
log(LOG_INFO, "mempool alloc stats after free: {}/{}", mempool.get_num_allocated(), mempool.get_capacity());
} catch ( const std::exception& e ) { log(LOG_ERROR, "error while testing ring: {}", e.what()); }
return 0;
}
| 30.148148
| 119
| 0.610258
|
subject721
|
0cb706c5b94022177ade165039b90ff253dd2ca7
| 675
|
cpp
|
C++
|
Codeforces/459D.cpp
|
Alipashaimani/Competitive-programming
|
5d55567b71ea61e69a6450cda7323c41956d3cb9
|
[
"MIT"
] | null | null | null |
Codeforces/459D.cpp
|
Alipashaimani/Competitive-programming
|
5d55567b71ea61e69a6450cda7323c41956d3cb9
|
[
"MIT"
] | null | null | null |
Codeforces/459D.cpp
|
Alipashaimani/Competitive-programming
|
5d55567b71ea61e69a6450cda7323c41956d3cb9
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
constexpr int MAXN = 1e6 + 10;
map <int, int> f1, f2, cnt;
int n, a[MAXN], fw[MAXN];
long long ans = 0;
void update (int i){
for (; i <= n; i += i&(-i))
++fw[i];
}
int query (int i) {
int x = 0;
for (--i; ~i+1; i -= i&(-i))
x += fw[i];
return x;
}
int main () {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 1; i <= n; ++i)
cin >> a[i], f1[i] = ++cnt[a[i]];
for(int i = 1; i <= n; ++i)
f2[i] = cnt[a[i]]--;
for(int i = n; ~i+1; --i)
ans += query(f1[i]), update(f2[i]);
cout << ans << endl;
}
| 17.763158
| 46
| 0.441481
|
Alipashaimani
|
0cbfb4a61188286604772331ea7b281a262932e4
| 314
|
cpp
|
C++
|
Source/Async/Utils.cpp
|
loudedtwist/cpp-task-loop
|
71795ad6916bf35ddca5dc04fd291d2affb2ffff
|
[
"MIT"
] | null | null | null |
Source/Async/Utils.cpp
|
loudedtwist/cpp-task-loop
|
71795ad6916bf35ddca5dc04fd291d2affb2ffff
|
[
"MIT"
] | null | null | null |
Source/Async/Utils.cpp
|
loudedtwist/cpp-task-loop
|
71795ad6916bf35ddca5dc04fd291d2affb2ffff
|
[
"MIT"
] | null | null | null |
#include <Async/Utils.hpp>
#include <chrono>
namespace utils {
unique_id GenerateTimestampID() {
return (unique_id) std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch() + std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
}
}
| 22.428571
| 119
| 0.719745
|
loudedtwist
|
0cc076f8a92c4a68c1353295b8ed1a3953f66df2
| 2,085
|
cpp
|
C++
|
luogu/3804/me.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
luogu/3804/me.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
luogu/3804/me.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
/*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=300005;
int sz=1,lst=1;
ll ans=0;
struct SAM{
int link[N],maxlen[N],trans[N][26]; ll f[N];
void extend(int id){
int cur=++sz,p;
maxlen[cur]=maxlen[lst]+1;
for(p=lst;p&&!trans[p][id];p=link[p]) trans[p][id]=cur;
if(!p) link[cur]=1;
else{
int q=trans[p][id];
if(maxlen[q]==maxlen[p]+1) link[cur]=q;
else{
int tmp=++sz;
maxlen[tmp]=maxlen[p]+1;
copy(trans[q],trans[q]+26,trans[tmp]);
link[tmp]=link[q];
for(;p&&trans[p][id]==q;p=link[p]) trans[p][id]=tmp;
link[cur]=link[q]=tmp;
}
}
lst=cur;
}
int vis[N];
vector<int> v[N];
void dfs(int u){
f[u]=1; vis[u]=1;
for(int i=0;i<26;i++) if(trans[u][i]){
if(!vis[trans[u][i]]) dfs(trans[u][i]);
f[u]+=f[trans[u][i]];
}
}
}tree;
char s[N]; int n;
int main()
{
n=read();
scanf("%s",s+1);
for(int i=1;i<=n;i++) tree.extend(s[i]-'a');
tree.dfs(1);
cout<<tree.f[1]-1<<endl;
return 0;
}
| 28.175676
| 98
| 0.506475
|
jinzhengyu1212
|
0cc084f33ed98c9f36480c7082e9cff7a5c937a7
| 2,347
|
cpp
|
C++
|
policy.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | 3
|
2020-09-14T19:39:53.000Z
|
2021-01-19T11:58:27.000Z
|
policy.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | null | null | null |
policy.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | null | null | null |
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: MIT
#include "policy.h"
#include "ui_policy.h"
Policy::Policy(QWidget *parent) :
QWidget(parent),
ui(new Ui::Policy)
{
ui->setupUi(this);
}
Policy::~Policy()
{
delete ui;
}
void Policy::setName(const QString n)
{
name = n;
ui->label_name->setText(n);
}
void Policy::setDescription(const QString d)
{
description = d;
ui->label_name->setToolTip(d);
}
void Policy::setUi(bool b)
{
if (b) {
ui->label_ui->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;");
ui->label_ui->setText("UI\nON");
} else {
ui->label_ui->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;");
ui->label_ui->setText("UI\nOFF");
}
}
void Policy::setGoLive(bool b)
{
ui->label_go_live->setAlignment(Qt::AlignCenter);
ui->label_go_live->setMargin(2);
if (b) {
ui->label_go_live->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;");
ui->label_go_live->setText(" Go Live \nON");
} else {
ui->label_go_live->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;");
ui->label_go_live->setText(" Go Live \nOFF");
}
}
void Policy::setRulesNumber(int n)
{
if (n > 0) {
ui->label_rules->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;");
} else {
ui->label_rules->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;");
}
QString s = QString("Rules:\n%1").arg(n);
ui->label_rules->setText(s);
}
void Policy::setLog(bool b)
{
if (b) {
ui->label_log->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;");
ui->label_log->setText("LOG\nON");
} else {
ui->label_log->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;");
ui->label_log->setText("LOG\nOFF");
}
}
void Policy::on_checkBox_stateChanged(int arg1)
{
switch (arg1) {
case Qt::Unchecked:
emit pol_deselected(name);
break;
case Qt::Checked:
emit pol_selected(name);
break;
}
}
void Policy::unselect()
{
ui->checkBox->setChecked(false);
}
| 24.705263
| 113
| 0.633575
|
slist
|
0cc669d3fe485bedc8e1dbc9d9c4d2f1afaa24b7
| 2,333
|
cpp
|
C++
|
Problems/36_Valide_Sudoku/main.cpp
|
camelboat/LeetCode_Archive
|
c29d263e068752a9ad355925f326b56f672bb584
|
[
"MIT"
] | 3
|
2019-09-21T16:25:44.000Z
|
2021-08-29T20:43:57.000Z
|
Problems/36_Valide_Sudoku/main.cpp
|
camelboat/LeetCode_Archive
|
c29d263e068752a9ad355925f326b56f672bb584
|
[
"MIT"
] | null | null | null |
Problems/36_Valide_Sudoku/main.cpp
|
camelboat/LeetCode_Archive
|
c29d263e068752a9ad355925f326b56f672bb584
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
vector<bool> base(27*9, false);
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
int tar = board[i][j] - '0';
if (tar != '.'-'0')
{
// cout << "i " << i << '\n';
// cout << "j " << j << '\n';
int fir = 9*i+tar-1;
if (base[fir]) return false;
else base[fir] = true;
int sec = 81 + j*9 + tar-1;
if (base[sec]) return false;
else base[sec] = true;
int thi = 162 + ((i/3)*3+j/3)*9+tar-1;
if (base[thi]) return false;
else base[thi] = true;
}
}
}
return true;
// typedef unordered_map<char, int> hashmap;
// vector<hashmap> base;
// for (int i = 0; i < 27; ++i)
// {
// hashmap tmp;
// base.emplace_back(tmp);
// }
// for (int i = 0; i < 9; ++i)
// {
// for (int j = 0; j < 9; ++j)
// {
// // hashmap i (row)
// // hashmap 9+j (column)
// // hashmap 18+(i/3)*3+j/3 (grid)
// if (board[i][j] != '.')
// {
// if (base[i].find(board[i][j])!=base[i].end()) return false;
// else base[i][board[i][j]]++;
// int sec = 9+j;
// if (base[sec].find(board[i][j])!=base[sec].end()) return false;
// else
// {
// base[sec][board[i][j]]++;
// }
// int thi = 18+(i/3)*3+(j/3);
// if (base[thi].find(board[i][j])!=base[thi].end()) return false;
// else base[thi][board[i][j]]++;
// }
// }
// }
// return true;
}
};
// for (int k = 0; k < 27; ++k)
// {
// cout << "group " << k << '\n';
// for (auto& x: base[k]) std::cout << " " << x.first << ":" << x.second << '\n';
// }
| 30.697368
| 86
| 0.328333
|
camelboat
|
0cc7cd6722f67bb702ca9abb75124bd8fa896670
| 2,236
|
hpp
|
C++
|
android-31/java/time/chrono/JapaneseDate.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/java/time/chrono/JapaneseDate.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/java/time/chrono/JapaneseDate.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
namespace java::io
{
class ObjectInputStream;
}
class JObject;
class JString;
namespace java::time
{
class Clock;
}
namespace java::time
{
class LocalDate;
}
namespace java::time
{
class LocalTime;
}
namespace java::time
{
class ZoneId;
}
namespace java::time::chrono
{
class JapaneseChronology;
}
namespace java::time::chrono
{
class JapaneseEra;
}
namespace java::time::temporal
{
class ValueRange;
}
namespace java::time::chrono
{
class JapaneseDate : public JObject
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit JapaneseDate(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
JapaneseDate(QJniObject obj);
// Constructors
// Methods
static java::time::chrono::JapaneseDate from(JObject arg0);
static java::time::chrono::JapaneseDate now();
static java::time::chrono::JapaneseDate now(java::time::Clock arg0);
static java::time::chrono::JapaneseDate now(java::time::ZoneId arg0);
static java::time::chrono::JapaneseDate of(jint arg0, jint arg1, jint arg2);
static java::time::chrono::JapaneseDate of(java::time::chrono::JapaneseEra arg0, jint arg1, jint arg2, jint arg3);
JObject atTime(java::time::LocalTime arg0) const;
jboolean equals(JObject arg0) const;
java::time::chrono::JapaneseChronology getChronology() const;
java::time::chrono::JapaneseEra getEra() const;
jlong getLong(JObject arg0) const;
jint hashCode() const;
jboolean isSupported(JObject arg0) const;
jint lengthOfMonth() const;
jint lengthOfYear() const;
java::time::chrono::JapaneseDate minus(JObject arg0) const;
java::time::chrono::JapaneseDate minus(jlong arg0, JObject arg1) const;
java::time::chrono::JapaneseDate plus(JObject arg0) const;
java::time::chrono::JapaneseDate plus(jlong arg0, JObject arg1) const;
java::time::temporal::ValueRange range(JObject arg0) const;
jlong toEpochDay() const;
JString toString() const;
JObject until(JObject arg0) const;
jlong until(JObject arg0, JObject arg1) const;
java::time::chrono::JapaneseDate with(JObject arg0) const;
java::time::chrono::JapaneseDate with(JObject arg0, jlong arg1) const;
};
} // namespace java::time::chrono
| 27.268293
| 153
| 0.731664
|
YJBeetle
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.