blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
c59cbf0147cf14b5008bf568c0823726293fa688
e1b8c362dc9f8d09b056eff59bbe4c33cc418fd1
/common/include/MemoryPool.hxx
6b9d703d768ed0def763ca019abdb08e0302b8ee
[ "MIT" ]
permissive
zhaoyaogit/matching-engine
ab36fe75bb5076e0c17b29d1096db1c3b50a118a
090a7e7414f478f1424a50668e3f5c2417646ba7
refs/heads/master
2022-01-05T06:06:37.152603
2018-09-29T14:08:43
2018-09-29T14:08:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,787
hxx
/*- * Copyright (c) 2013 Cosku Acay, http://www.coskuacay.com * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #pragma once template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::size_type MemoryPool<T, BlockSize>::padPointer(data_pointer_ p, size_type align) const noexcept { uintptr_t result = reinterpret_cast<uintptr_t>(p); return ((align - result) % align); } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool() noexcept { currentBlock_ = nullptr; currentSlot_ = nullptr; lastSlot_ = nullptr; freeSlots_ = nullptr; } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool(const MemoryPool& memoryPool) noexcept : MemoryPool() {} template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::MemoryPool(MemoryPool&& memoryPool) noexcept { currentBlock_ = memoryPool.currentBlock_; memoryPool.currentBlock_ = nullptr; currentSlot_ = memoryPool.currentSlot_; lastSlot_ = memoryPool.lastSlot_; freeSlots_ = memoryPool.freeSlots; } template <typename T, size_t BlockSize> template<class U> MemoryPool<T, BlockSize>::MemoryPool(const MemoryPool<U>& memoryPool) noexcept : MemoryPool() {} template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>& MemoryPool<T, BlockSize>::operator=(MemoryPool&& memoryPool) noexcept { if (this != &memoryPool) { std::swap(currentBlock_, memoryPool.currentBlock_); currentSlot_ = memoryPool.currentSlot_; lastSlot_ = memoryPool.lastSlot_; freeSlots_ = memoryPool.freeSlots; } return *this; } template <typename T, size_t BlockSize> MemoryPool<T, BlockSize>::~MemoryPool() noexcept { slot_pointer_ curr = currentBlock_; while (curr != nullptr) { slot_pointer_ prev = curr->next; operator delete(reinterpret_cast<void*>(curr)); curr = prev; } } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::address(reference x) const noexcept { return &x; } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::const_pointer MemoryPool<T, BlockSize>::address(const_reference x) const noexcept { return &x; } template <typename T, size_t BlockSize> void MemoryPool<T, BlockSize>::allocateBlock() { // Allocate space for the new block and store a pointer to the previous one data_pointer_ newBlock = reinterpret_cast<data_pointer_> (operator new(BlockSize)); reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_; currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock); // Pad block body to staisfy the alignment requirements for elements data_pointer_ body = newBlock + sizeof(slot_pointer_); size_type bodyPadding = padPointer(body, alignof(slot_type_)); currentSlot_ = reinterpret_cast<slot_pointer_>(body + bodyPadding); lastSlot_ = reinterpret_cast<slot_pointer_> (newBlock + BlockSize - sizeof(slot_type_) + 1); } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::allocate(size_type /* n */, const_pointer /* hint */) { if (freeSlots_ != nullptr) { pointer result = reinterpret_cast<pointer>(freeSlots_); freeSlots_ = freeSlots_->next; return result; } else { if (currentSlot_ >= lastSlot_) allocateBlock(); return reinterpret_cast<pointer>(currentSlot_++); } } template <typename T, size_t BlockSize> inline void MemoryPool<T, BlockSize>::deallocate(pointer p, size_type /* n */) { if (p != nullptr) { reinterpret_cast<slot_pointer_>(p)->next = freeSlots_; freeSlots_ = reinterpret_cast<slot_pointer_>(p); } } template <typename T, size_t BlockSize> inline typename MemoryPool<T, BlockSize>::size_type MemoryPool<T, BlockSize>::max_size() const noexcept { size_type maxBlocks = -1 / BlockSize; return (BlockSize - sizeof(data_pointer_)) / sizeof(slot_type_) * maxBlocks; } template <typename T, size_t BlockSize> template <class U, class... Args> inline void MemoryPool<T, BlockSize>::construct(U* p, Args&&... args) { new (p) U (std::forward<Args>(args)...); } template <typename T, size_t BlockSize> template <class U> inline void MemoryPool<T, BlockSize>::destroy(U* p) { p->~U(); } template <typename T, size_t BlockSize> template <class... Args> inline typename MemoryPool<T, BlockSize>::pointer MemoryPool<T, BlockSize>::newElement(Args&&... args) { pointer result = allocate(); construct<value_type>(result, std::forward<Args>(args)...); return result; } template <typename T, size_t BlockSize> inline void MemoryPool<T, BlockSize>::deleteElement(pointer p) { if (p != nullptr) { p->~value_type(); deallocate(p); } }
[ "faulaire@pc-ubuntu.home" ]
faulaire@pc-ubuntu.home
293fb0b8c85cc4c985ab43c176fdd1fc9be7f543
d1f11d6a04b115e57dc0a2e517b9bb81c7a0a31b
/K_引用和拷贝构造函数/B_C++中的引用/B_Reference.cpp
a2eb46b2e2013dc08c69a35122736dcce4ee49bc
[]
no_license
syzwdong/ThinkingInCppNote
36973cd20a167d845128a2b6b6e9aed0f187d86c
7cd23b72c0e2253773df57bc19d32f5a29278192
refs/heads/master
2023-03-19T23:31:49.422074
2018-02-14T17:44:55
2018-02-14T17:44:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
// // Created by 何时夕 on 2018/1/1. // int *f(int *x) { (*x)++; return x; } int &g(int &x) { x++; return x; } int &h() { int q; // return q; q的内存在函数结束的时候 就被回收了 所以引用就不知道指向那一块内存 static int x; return x;// 安全 因为static的 内存在程序结束的时候才回收 } int main() { int a = 0; f(&a); g(a); } /** * 1.把一个引用给一个引用的时候 传递的是 引用指向内存的地址 * 2.把一个 变量 给一个 引用的时候 传递的是 变量的地址 * 3.对于指针只能将 地址给指针 * 4.所以引用比指针用起来方便 安全 */
[ "a1018998632@gmail.com" ]
a1018998632@gmail.com
43e6ec4e1f0241081fba36f331a9ed6bc19c2416
648522d1909a6120cb6018ba832e16980797288e
/src/yappari-application/Gui/profilepicturewindow.cpp
5bd4821d91f9abc7170cd5d771a503ff0454425f
[]
no_license
agamez/yappari
169b64a6dd227feef5fb4fb7baee24b35f5346cf
8880b5f77112351852d19a86462b082b2b3ffca3
refs/heads/master
2021-01-17T09:00:49.990383
2016-04-15T09:12:36
2016-04-15T09:12:36
26,725,930
21
9
null
2015-03-30T08:26:58
2014-11-16T19:53:06
C++
UTF-8
C++
false
false
8,260
cpp
/* Copyright 2013 Naikel Aparicio. 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. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''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 EELI REILIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation * are those of the author and should not be interpreted as representing * official policies, either expressed or implied, of the copyright holder. */ #include <QMaemo5InformationBox> #include <QPainter> #include <QTimer> #include "profilepicturewindow.h" #include "ui_profilepicturewindow.h" #include "Whatsapp/util/utilities.h" #define MAX_HEIGHT 480 #define MAX_WIDTH 800 #define MIN_PHOTO_WIDTH 224 #define MIN_PHOTO_HEIGHT 224 #define MAX_PHOTO_HEIGHT 640 #define MAX_PHOTO_WIDTH 640 #define DEFAULT_BAND_WIDTH 350 #define DEFAULT_BAND_HEIGHT 350 ProfilePictureWindow::ProfilePictureWindow(QImage photo, QWidget *parent) : QMainWindow(parent), ui(new Ui::ProfilePictureWindow) { ui->setupUi(this); this->photo = photo; // Create preview photo QImage preview = photo; if (preview.height() > MAX_HEIGHT || preview.width() > MAX_WIDTH) { preview = preview.scaled(QSize(MAX_WIDTH,MAX_HEIGHT), Qt::KeepAspectRatio,Qt::SmoothTransformation); } // Create 800x480 background QImage background(MAX_WIDTH, MAX_HEIGHT, QImage::Format_RGB32); QPainter painter(&background); painter.setCompositionMode((QPainter::CompositionMode_SourceOver)); screenPhotoSize = preview.size(); screenPhotoRect = QRect(QPoint(0,0),screenPhotoSize); // Center preview photo in the background image if (preview.width() < MAX_WIDTH) screenPhotoRect.moveLeft( (MAX_WIDTH/2) - (preview.width()/2)); if (preview.height() < MAX_HEIGHT) screenPhotoRect.moveTop( (MAX_HEIGHT/2) - (preview.height()/2)); // Paing background image painter.drawImage(screenPhotoRect, preview); QPalette palette = this->palette(); palette.setBrush(QPalette::Background, QBrush(background)); setPalette(palette); setWindowFlags(Qt::FramelessWindowHint); // Create selection rectangle rubberBandRect.setRect(0, 0, DEFAULT_BAND_WIDTH, DEFAULT_BAND_HEIGHT); // Adjust rectangle if image is smaller if (rubberBandRect.width() > screenPhotoSize.width() || rubberBandRect.height() > screenPhotoSize.height()) { int newSize = screenPhotoSize.width(); if (newSize > screenPhotoSize.height()) newSize = screenPhotoSize.height(); rubberBandRect.setWidth(newSize); rubberBandRect.setHeight(newSize); } // Center rectangle rubberBandRect.moveLeft( (MAX_WIDTH/2) - (rubberBandRect.width()/2)); rubberBandRect.moveTop( (MAX_HEIGHT/2) - (rubberBandRect.height()/2)); // Create a rubber band from the selection rectangle rubberBand = new QRubberBand(QRubberBand::Rectangle,this); rubberBand->setGeometry(rubberBandRect); rubberBand->show(); connect(ui->cancelButton,SIGNAL(clicked()),this,SLOT(close())); connect(ui->okButton,SIGNAL(clicked()),this,SLOT(finishedSelection())); connect(ui->upButton,SIGNAL(clicked()),this,SLOT(increaseSelection())); connect(ui->downButton,SIGNAL(clicked()),this,SLOT(decreaseSelection())); } ProfilePictureWindow::~ProfilePictureWindow() { delete ui; } void ProfilePictureWindow::mousePressEvent(QMouseEvent *event) { if (rubberBandRect.contains(event->globalPos())) { origin = event->globalPos(); ui->upButton->hide(); ui->downButton->hide(); ui->okButton->hide(); ui->cancelButton->hide(); } else origin = QPoint(-1,-1); } void ProfilePictureWindow::mouseMoveEvent(QMouseEvent *event) { if (origin != QPoint(-1,-1)) { QPoint newPos = rubberBand->pos() + (event->globalPos() - origin); if (newPos.x() < screenPhotoRect.left()) newPos.setX(screenPhotoRect.left()); if (newPos.y() < screenPhotoRect.top()) newPos.setY(screenPhotoRect.top()); if (newPos.x() + rubberBandRect.width() > screenPhotoRect.right()) newPos.setX(screenPhotoRect.right() - rubberBandRect.width()); if (newPos.y() + rubberBandRect.height() > screenPhotoRect.bottom()) newPos.setY(screenPhotoRect.bottom() - rubberBandRect.height()); rubberBandRect.moveTo(newPos); rubberBand->setGeometry(rubberBandRect); origin = event->globalPos(); } } void ProfilePictureWindow::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event); ui->upButton->show(); ui->downButton->show(); ui->okButton->show(); ui->cancelButton->show(); } QRect ProfilePictureWindow::mapSelectionToSource(QRect& selection) { // Calculate aspect ratio qreal xratio = (qreal)photo.width() / (qreal)screenPhotoSize.width(); qreal yratio = (qreal)photo.height() / (qreal)screenPhotoSize.height(); return QRect((selection.x() - screenPhotoRect.left()) * xratio, (selection.y() - screenPhotoRect.top()) * yratio, selection.width() * xratio, selection.height() * yratio); } void ProfilePictureWindow::finishedSelection() { QMaemo5InformationBox::information(this,"Processing image"); QTimer::singleShot(100,this,SLOT(cropImage())); } void ProfilePictureWindow::cropImage() { // Start cropping QRect rect = mapSelectionToSource(rubberBandRect); QImage croppedImage = photo.copy(rect); if (croppedImage.height() > MAX_PHOTO_HEIGHT || croppedImage.width() > MAX_PHOTO_WIDTH) { croppedImage = croppedImage.scaled(QSize(MAX_PHOTO_WIDTH, MAX_PHOTO_HEIGHT), Qt::KeepAspectRatio,Qt::SmoothTransformation); } emit finished(croppedImage); close(); } void ProfilePictureWindow::increaseSelection() { QRect newRect = rubberBandRect; if (rubberBandRect.right() + 1 <= screenPhotoRect.right() && rubberBandRect.bottom() + 1 <= screenPhotoRect.bottom() && rubberBandRect.top() - 1 >= screenPhotoRect.top() && rubberBandRect.right() - 1 >= screenPhotoRect.left()) { newRect.setWidth(rubberBandRect.width() + 2); newRect.setHeight(rubberBandRect.height() + 2); newRect.moveTo(newRect.topLeft() - QPoint(1,1)); rubberBandRect = newRect; rubberBand->setGeometry(rubberBandRect); } } void ProfilePictureWindow::decreaseSelection() { QRect newRect = rubberBandRect; newRect.setWidth(rubberBandRect.width() - 2); newRect.setHeight(rubberBandRect.height() - 2); newRect.moveTo(newRect.topLeft() + QPoint(1,1)); QRect sourceRect = mapSelectionToSource(newRect); if (sourceRect.width() >= MIN_PHOTO_WIDTH && sourceRect.height() >= MIN_PHOTO_HEIGHT) { rubberBandRect = newRect; rubberBand->setGeometry(rubberBandRect); } }
[ "alvaro.gamez@hazent.com" ]
alvaro.gamez@hazent.com
5a2755d72cfd6fa313268e684106389776c81adb
d4d5a0bc519294e4b3f312048dd52cf9264b7e29
/HDU/6180/18974911_WA_0ms_0kB.cpp
119f2d5869210d34bec037b2cf502eb632d8d859
[]
no_license
imhdx/My-all-code-of-Vjudge-Judge
fc625f83befbaeda7a033fd271fd4f61d295e807
b0db5247db09837be9866f39b183409f0a02c290
refs/heads/master
2020-04-29T08:16:24.607167
2019-07-24T01:17:15
2019-07-24T01:17:15
175,981,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include<bits/stdc++.h> using namespace std; struct ac { int x,y; }que[100005]; bool cmp(ac q,ac p) { if (q.y==p.y) return q.x<p.x; return q.y<p.y; } multiset<int> s; int main() { int T; scanf("%d",&T); while (T--) { s.clear(); int n; scanf("%d",&n); for (int i=0;i<n;i++) scanf("%d%d",&que[i].x,&que[i].y); sort(que,que+n,cmp); long long sum=0; int cnt=0; for (int i=0;i<n;i++) { if (s.size()==0) { sum+=que[i].y-que[i].x; cnt++; s.insert(que[i].y); } else{ auto it=s.upper_bound(que[i].x); if (it==s.begin()) { sum+=que[i].y-que[i].x; cnt++; s.insert(que[i].y); } else{ --it; sum+=que[i].y-*it; s.erase(it); s.insert(que[i].y); } } } printf("%d %lld\n",cnt,sum); } return 0; }
[ "mhdxacmer@126.com" ]
mhdxacmer@126.com
654b69a6e07287446162df5fdcf7a83c417c0840
1d8c4bcdb559d46b9fc8d01facdb80a93bf6727d
/src/third_party/zlib-1.2.11/contrib/iostream2/zstream_test.cpp
aed0154a20654d9787603d3a4e389f8570ce24a6
[ "Zlib", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
lxy0xff/OpenArkCompiler
b7ca2986c38f38a14a105ce3ffcece7b4e02fe9e
ed0e189d61154f7d057184e0c16ebd4c250413d9
refs/heads/master
2020-07-15T01:49:10.870511
2019-08-30T20:57:49
2019-08-30T20:57:49
205,452,468
0
0
null
2019-08-30T20:28:07
2019-08-30T20:28:07
null
UTF-8
C++
false
false
1,289
cpp
/* * Copyright (c) [2019] Huawei Technologies Co.,Ltd.All rights reverved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "zstream.h" #include <math.h> #include <stdlib.h> #include <iomanip.h> void main() { char h[256] = "Hello"; char* g = "Goodbye"; ozstream out("temp.gz"); out < "This works well" < h < g; out.close(); izstream in("temp.gz"); // read it back char *x = read_string(in), *y = new char[256], z[256]; in > y > z; in.close(); cout << x << endl << y << endl << z << endl; out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl; out << z << endl << y << endl << x << endl; out << 1.1234567890123456789 << endl; delete[] x; delete[] y; }
[ "himself65@outlook.com" ]
himself65@outlook.com
8ef5a203656a7056354fc28f8e70b4b23795ff63
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_2716_last_repos.cpp
4fa3a5b4d5da6230b0ccf028f41268f882485fdb
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
317
cpp
static void ev_pre_close(h2_proxy_session *session, int arg, const char *msg) { switch (session->state) { case H2_PROXYS_ST_DONE: case H2_PROXYS_ST_LOCAL_SHUTDOWN: /* nop */ break; default: session_shutdown(session, arg, msg); break; } }
[ "993273596@qq.com" ]
993273596@qq.com
fabca5af02e564273e084b7ab671dbceaf11e666
87aba51b1f708b47d78b5c4180baf731d752e26d
/Replication/DataFileSystem/PRODUCT_SOURCE_CODE/chromium/webkit/plugins/npapi/plugin_list_posix.cc
28fe5a93577c7203302e7567adb08b893956d2a5
[]
no_license
jstavr/Architecture-Relation-Evaluator
12c225941e9a4942e83eb6d78f778c3cf5275363
c63c056ee6737a3d90fac628f2bc50b85c6bd0dc
refs/heads/master
2020-12-31T05:10:08.774893
2016-05-14T16:09:40
2016-05-14T16:09:40
58,766,508
0
0
null
null
null
null
UTF-8
C++
false
false
12,217
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/plugins/npapi/plugin_list.h" #include <algorithm> #include "base/cpu.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/sha1.h" #include "base/stringprintf.h" #include "base/string_split.h" #include "base/string_util.h" #include "build/build_config.h" namespace webkit { namespace npapi { namespace { // We build up a list of files and mtimes so we can sort them. typedef std::pair<FilePath, base::Time> FileAndTime; typedef std::vector<FileAndTime> FileTimeList; enum PluginQuirk { // No quirks - plugin is outright banned. PLUGIN_QUIRK_NONE = 0, // Plugin is using SSE2 instructions without checking for SSE2 instruction // support. Ban the plugin if the system has no SSE2 support. PLUGIN_QUIRK_MISSING_SSE2_CHECK = 1 << 0, }; // Comparator used to sort by descending mtime then ascending filename. bool CompareTime(const FileAndTime& a, const FileAndTime& b) { if (a.second == b.second) { // Fall back on filename sorting, just to make the predicate valid. return a.first < b.first; } // Sort by mtime, descending. return a.second > b.second; } // Checks to see if the current environment meets any of the condtions set in // |quirks|. Returns true if any of the conditions are met, or if |quirks| is // PLUGIN_QUIRK_NONE. bool CheckQuirks(PluginQuirk quirks) { if (quirks == PLUGIN_QUIRK_NONE) return true; if ((quirks & PLUGIN_QUIRK_MISSING_SSE2_CHECK) != 0) { base::CPU cpu; if (!cpu.has_sse2()) return true; } return false; } // Return true if |path| matches a known (file size, sha1sum) pair. // Also check against any PluginQuirks the bad plugin may have. // The use of the file size is an optimization so we don't have to read in // the entire file unless we have to. bool IsBlacklistedBySha1sumAndQuirks(const FilePath& path) { const struct BadEntry { int64 size; std::string sha1; PluginQuirk quirks; } bad_entries[] = { // Flash 9 r31 - http://crbug.com/29237 { 7040080, "fa5803061125ca47846713b34a26a42f1f1e98bb", PLUGIN_QUIRK_NONE }, // Flash 9 r48 - http://crbug.com/29237 { 7040036, "0c4b3768a6d4bfba003088e4b9090d381de1af2b", PLUGIN_QUIRK_NONE }, // Flash 11.2.202.236, 32-bit - http://crbug.com/140086 { 17406436, "1e07eac912faf9426c52a288c76c3b6238f90b6b", PLUGIN_QUIRK_MISSING_SSE2_CHECK }, // Flash 11.2.202.238, 32-bit - http://crbug.com/140086 { 17410532, "e9401097e97c8443a7d9156be62184ffe1addd5c", PLUGIN_QUIRK_MISSING_SSE2_CHECK }, }; int64 size; if (!file_util::GetFileSize(path, &size)) return false; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(bad_entries); i++) { if (bad_entries[i].size != size) continue; std::string file_content; if (!file_util::ReadFileToString(path, &file_content)) continue; std::string sha1 = base::SHA1HashString(file_content); std::string sha1_readable; for (size_t j = 0; j < sha1.size(); j++) base::StringAppendF(&sha1_readable, "%02x", sha1[j] & 0xFF); if (bad_entries[i].sha1 == sha1_readable) return CheckQuirks(bad_entries[i].quirks); } return false; } // Some plugins are shells around other plugins; we prefer to use the // real plugin directly, if it's available. This function returns // true if we should prefer other plugins over this one. We'll still // use a "undesirable" plugin if no other option is available. bool IsUndesirablePlugin(const WebPluginInfo& info) { std::string filename = info.path.BaseName().value(); const char* kUndesiredPlugins[] = { "npcxoffice", // Crossover "npwrapper", // nspluginwrapper }; for (size_t i = 0; i < arraysize(kUndesiredPlugins); i++) { if (filename.find(kUndesiredPlugins[i]) != std::string::npos) { return true; } } return false; } // Return true if we shouldn't load a plugin at all. // This is an ugly hack to blacklist Adobe Acrobat due to not supporting // its Xt-based mainloop. // http://code.google.com/p/chromium/issues/detail?id=38229 bool IsBlacklistedPlugin(const FilePath& path) { const char* kBlackListedPlugins[] = { "nppdf.so", // Adobe PDF }; std::string filename = path.BaseName().value(); for (size_t i = 0; i < arraysize(kBlackListedPlugins); i++) { if (filename.find(kBlackListedPlugins[i]) != std::string::npos) { return true; } } return IsBlacklistedBySha1sumAndQuirks(path); } } // namespace void PluginList::PlatformInit() { } void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) { // See http://groups.google.com/group/chromium-dev/browse_thread/thread/7a70e5fcbac786a9 // for discussion. // We first consult Chrome-specific dirs, then fall back on the logic // Mozilla uses. // Note: "extra" plugin dirs, including the Plugins subdirectory of // your Chrome config, are examined before these. See the logic // related to extra_plugin_dirs in plugin_list.cc. // The Chrome binary dir + "plugins/". FilePath dir; PathService::Get(base::DIR_EXE, &dir); plugin_dirs->push_back(dir.Append("plugins")); // Chrome OS only loads plugins from /opt/google/chrome/plugins. #if !defined(OS_CHROMEOS) // Mozilla code to reference: // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST // and tens of accompanying files (mxr is very helpful). // This code carefully matches their behavior for compat reasons. // 1) MOZ_PLUGIN_PATH env variable. const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH"); if (moz_plugin_path) { std::vector<std::string> paths; base::SplitString(moz_plugin_path, ':', &paths); for (size_t i = 0; i < paths.size(); ++i) plugin_dirs->push_back(FilePath(paths[i])); } // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins. // This is a de-facto standard, so even though we're not Mozilla, let's // look in there too. FilePath home = file_util::GetHomeDir(); if (!home.empty()) plugin_dirs->push_back(home.Append(".mozilla/plugins")); // 3) NS_SYSTEM_PLUGINS_DIR: // This varies across different browsers and versions, so check 'em all. plugin_dirs->push_back(FilePath("/usr/lib/browser-plugins")); plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins")); plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins")); plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins")); #if defined(ARCH_CPU_64_BITS) // On my Ubuntu system, /usr/lib64 is a symlink to /usr/lib. // But a user reported on their Fedora system they are separate. plugin_dirs->push_back(FilePath("/usr/lib64/browser-plugins")); plugin_dirs->push_back(FilePath("/usr/lib64/mozilla/plugins")); plugin_dirs->push_back(FilePath("/usr/lib64/firefox/plugins")); plugin_dirs->push_back(FilePath("/usr/lib64/xulrunner-addons/plugins")); #endif // defined(ARCH_CPU_64_BITS) #endif // !defined(OS_CHROMEOS) } void PluginList::GetPluginsInDir( const FilePath& dir_path, std::vector<FilePath>* plugins) { // See ScanPluginsDirectory near // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052 // Construct and stat a list of all filenames under consideration, for // later sorting by mtime. FileTimeList files; file_util::FileEnumerator enumerator(dir_path, false, // not recursive file_util::FileEnumerator::FILES); for (FilePath path = enumerator.Next(); !path.value().empty(); path = enumerator.Next()) { // Skip over Mozilla .xpt files. if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt"))) continue; // Java doesn't like being loaded through a symlink, since it uses // its path to find dependent data files. // file_util::AbsolutePath calls through to realpath(), which resolves // symlinks. FilePath orig_path = path; file_util::AbsolutePath(&path); LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Resolved " << orig_path.value() << " -> " << path.value(); if (std::find(plugins->begin(), plugins->end(), path) != plugins->end()) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Skipping duplicate instance of " << path.value(); continue; } if (IsBlacklistedPlugin(path)) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Skipping blacklisted plugin " << path.value(); continue; } // Flash stops working if the containing directory involves 'netscape'. // No joke. So use the other path if it's better. static const char kFlashPlayerFilename[] = "libflashplayer.so"; static const char kNetscapeInPath[] = "/netscape/"; if (path.BaseName().value() == kFlashPlayerFilename && path.value().find(kNetscapeInPath) != std::string::npos) { if (orig_path.value().find(kNetscapeInPath) == std::string::npos) { // Go back to the old path. path = orig_path; } else { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Flash misbehaves when used from a directory containing " << kNetscapeInPath << ", so skipping " << orig_path.value(); continue; } } // Get mtime. base::PlatformFileInfo info; if (!file_util::GetFileInfo(path, &info)) continue; files.push_back(std::make_pair(path, info.last_modified)); } // Sort the file list by time (and filename). std::sort(files.begin(), files.end(), CompareTime); // Load the files in order. for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) { plugins->push_back(i->first); } } // TODO(ibraaaa): DELETE. http://crbug.com/124396 bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info, ScopedVector<PluginGroup>* plugin_groups) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Considering " << info.path.value() << " (" << info.name << ")"; if (IsUndesirablePlugin(info)) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << info.path.value() << " is undesirable."; // See if we have a better version of this plugin. for (size_t i = 0; i < plugin_groups->size(); ++i) { const std::vector<WebPluginInfo>& plugins = (*plugin_groups)[i]->web_plugin_infos(); for (size_t j = 0; j < plugins.size(); ++j) { if (plugins[j].name == info.name && !IsUndesirablePlugin(plugins[j])) { // Skip the current undesirable one so we can use the better one // we just found. LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Skipping " << info.path.value() << ", preferring " << plugins[j].path.value(); return false; } } } } // TODO(evanm): prefer the newest version of flash, etc. here? VLOG_IF(1, PluginList::DebugPluginLoading()) << "Using " << info.path.value(); return true; } bool PluginList::ShouldLoadPluginUsingPluginList( const WebPluginInfo& info, std::vector<webkit::WebPluginInfo>* plugins) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Considering " << info.path.value() << " (" << info.name << ")"; if (IsUndesirablePlugin(info)) { LOG_IF(ERROR, PluginList::DebugPluginLoading()) << info.path.value() << " is undesirable."; // See if we have a better version of this plugin. for (size_t j = 0; j < plugins->size(); ++j) { if ((*plugins)[j].name == info.name && !IsUndesirablePlugin((*plugins)[j])) { // Skip the current undesirable one so we can use the better one // we just found. LOG_IF(ERROR, PluginList::DebugPluginLoading()) << "Skipping " << info.path.value() << ", preferring " << (*plugins)[j].path.value(); return false; } } } // TODO(evanm): prefer the newest version of flash, etc. here? VLOG_IF(1, PluginList::DebugPluginLoading()) << "Using " << info.path.value(); return true; } } // namespace npapi } // namespace webkit
[ "jstavr2@gmail.com" ]
jstavr2@gmail.com
9c3d36e44c0426215866d7215a9bfd035b1ce706
d415331f79554c3384ed5e31b82b3f06722f7c3c
/LongRmDir.cpp
8cd951f5687608d4a6b0081189f9a2ded817dc91
[ "MIT" ]
permissive
chentiangemalc/LongRmDir
74d360b4d00a436c2f72d10041e79f9c7cb5e994
4a870688f10620b7368a528af761a58e3430f29a
refs/heads/main
2023-02-28T01:54:56.511930
2021-02-04T11:25:04
2021-02-04T11:25:04
335,884,790
1
0
null
null
null
null
UTF-8
C++
false
false
15,587
cpp
// LongRmDir.cpp : This file contains the 'main' function. Program execution begins and ends there. // #define _WIN32_WINNT 0x0501 #include <iostream> #include <Windows.h> #include <accctrl.h> #include <aclapi.h> #pragma comment (lib,"Advapi32.lib") #define IsDirectory(a) ((a) & FILE_ATTRIBUTE_DIRECTORY) #define IsReparse(a) ((a) & FILE_ATTRIBUTE_REPARSE_POINT) #define LONG_MAX_PATH 32768 BOOL bRebootRequired = FALSE; BOOL SetPrivilege( HANDLE hToken, // access token handle LPCTSTR lpszPrivilege, // name of privilege to enable/disable BOOL bEnablePrivilege // to enable or disable privilege ) { TOKEN_PRIVILEGES tp; LUID luid; if (!LookupPrivilegeValue( NULL, // lookup privilege on local system lpszPrivilege, // privilege to lookup &luid)) // receives LUID of privilege { std::wcerr << L"LookupPrivilegeValue error: " << GetLastError() << std::endl; return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // Enable the privilege or disable all privileges. if (!AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { std::wcerr << L"AdjustTokenPrivileges error: " << GetLastError() << std::endl; return FALSE; } if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) { std::wcerr << L"The token does not have the specified privilege." << std::endl; return FALSE; } return TRUE; } BOOL TakeOwnership(const WCHAR* lpszOwnFile) { BOOL bRetval = FALSE; HANDLE hToken = NULL; PSID pSIDAdmin = NULL; PSID pSIDEveryone = NULL; PACL pACL = NULL; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; const int NUM_ACES = 2; EXPLICIT_ACCESS ea[NUM_ACES]; DWORD dwResult; // Specify the DACL to use. // Create a SID for the Everyone group. if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSIDEveryone)) { std::wcerr << L"AllocateAndInitializeSid (Everyone) error " << GetLastError() << std::endl; goto Cleanup; } // Create a SID for the BUILTIN\Administrators group. if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSIDAdmin)) { std::wcerr << L"AllocateAndInitializeSid (Admin) error " << GetLastError() << std::endl; goto Cleanup; } ZeroMemory(&ea, NUM_ACES * sizeof(EXPLICIT_ACCESS)); // Set read access for Everyone. ea[0].grfAccessPermissions = GENERIC_READ; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR)pSIDEveryone; // Set full control for Administrators. ea[1].grfAccessPermissions = GENERIC_ALL; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP; ea[1].Trustee.ptstrName = (LPTSTR)pSIDAdmin; dwResult = SetEntriesInAcl(NUM_ACES, ea, NULL, &pACL); if (dwResult != ERROR_SUCCESS) { std::wcerr << L"Failed SetEntriesInAcl Error: " << dwResult << std::endl; goto Cleanup; } // Try to modify the object's DACL. dwResult = SetNamedSecurityInfoW( (LPWSTR)lpszOwnFile, // name of the object SE_FILE_OBJECT, // type of object DACL_SECURITY_INFORMATION, // change only the object's DACL NULL, NULL, // do not change owner or group pACL, // DACL specified NULL); // do not change SACL if (dwResult == ERROR_SUCCESS) { std::wcout << L"Successfully changed DACL" << std::endl; bRetval = TRUE; // No more processing needed. goto Cleanup; } if (dwResult != ERROR_ACCESS_DENIED) { std::wcerr << L"First SetNamedSecurityInfo call failed: " << dwResult << std::endl; goto Cleanup; } // If the preceding call failed because access was denied, // enable the SE_TAKE_OWNERSHIP_NAME privilege, create a SID for // the Administrators group, take ownership of the object, and // disable the privilege. Then try again to set the object's DACL. // Open a handle to the access token for the calling process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { std::wcerr << L"OpenProcessToken failed: " << GetLastError() << std::endl; goto Cleanup; } // Enable the SE_TAKE_OWNERSHIP_NAME privilege. if (!SetPrivilege(hToken, SE_TAKE_OWNERSHIP_NAME, TRUE)) { std::wcerr << L"You must be logged on as Administrator." << std::endl; goto Cleanup; } // Set the owner in the object's security descriptor. dwResult = SetNamedSecurityInfo( (LPWSTR)lpszOwnFile, // name of the object SE_FILE_OBJECT, // type of object OWNER_SECURITY_INFORMATION, // change only the object's owner pSIDAdmin, // SID of Administrator group NULL, NULL, NULL); if (dwResult != ERROR_SUCCESS) { std::wcerr << L"Could not set owner. Error: " << dwResult << std::endl; goto Cleanup; } // Disable the SE_TAKE_OWNERSHIP_NAME privilege. if (!SetPrivilege(hToken, SE_TAKE_OWNERSHIP_NAME, FALSE)) { dwResult = GetLastError(); std::wcerr << L"Failed SetPrivilege call unexpectedly. Error: " << dwResult << std::endl; goto Cleanup; } // Try again to modify the object's DACL, // now that we are the owner. dwResult = SetNamedSecurityInfo( (LPWSTR)lpszOwnFile, // name of the object SE_FILE_OBJECT, // type of object DACL_SECURITY_INFORMATION, // change only the object's DACL NULL, NULL, // do not change owner or group pACL, // DACL specified NULL); // do not change SACL if (dwResult == ERROR_SUCCESS) { std::wcout << L"Successfully updated DACL" << std::endl; bRetval = TRUE; } else { std::wcerr << L"Second SetNamedSecurityInfo call failed. Error: " << dwResult << std::endl; } Cleanup: if (pSIDAdmin) FreeSid(pSIDAdmin); if (pSIDEveryone) FreeSid(pSIDEveryone); if (pACL) LocalFree(pACL); if (hToken) CloseHandle(hToken); return bRetval; } LSTATUS RemoveDirectoryForce( const WCHAR* pszDirectory ) { LSTATUS Status = ERROR_SUCCESS; DWORD Attr; WCHAR szRootPath[4]; WCHAR* pFilePart; if (GetFullPathName(pszDirectory, 4, szRootPath, &pFilePart) == 3 && szRootPath[1] == ':' && szRootPath[2] == '\\' ) { // don't delete root directory return ERROR_SUCCESS; } if (!RemoveDirectoryW(pszDirectory)) { Status = (LSTATUS)GetLastError(); switch (Status) { case ERROR_SHARING_VIOLATION: std::wcout << L"Directory '" << pszDirectory << "' is in use. Will remove on reboot." << std::endl; if (!MoveFileExW(pszDirectory, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { std::wcerr << L"Unable to remove on reboot Error: " << GetLastError() << std::endl; } else { bRebootRequired = true; Status = ERROR_SUCCESS; } break; case ERROR_ACCESS_DENIED: std::wcout << L"Taking ownership of '" << pszDirectory << L"'" << std::endl; TakeOwnership(pszDirectory); Attr = GetFileAttributesW(pszDirectory); if (Attr != 0xFFFFFFFF) { if (Attr & FILE_ATTRIBUTE_READONLY) { std::wcout << L"Clearing READ ONLY attribute on '" << pszDirectory << L"'" << std::endl; Attr &= ~FILE_ATTRIBUTE_READONLY; } if (Attr & FILE_ATTRIBUTE_SYSTEM) { std::wcout << L"Clearing SYSTEM attribute on '" << pszDirectory << L"'" << std::endl; Attr &= ~FILE_ATTRIBUTE_SYSTEM; } if (SetFileAttributesW(pszDirectory, Attr)) { if (RemoveDirectoryW(pszDirectory)) { Status = ERROR_SUCCESS; } else { Status = GetLastError(); std::wcerr << "FAILED TO CHANGE FILE ATTRIBUTES ERR#" << Status << std::endl; } } } break; } } return Status; } LSTATUS RemoveDirectoryAndSubdirectories( std::wstring pszDirectory, OUT BOOL* AllEntriesDeleted ) { HANDLE find_handle; DWORD attr; DWORD s; BOOL all_deleted; int dir_len, new_len; std::wstring new_str; WIN32_FIND_DATA find_data; std::wstring pszFileBuffer; DWORD dwResult; BOOL bResult; *AllEntriesDeleted = TRUE; dir_len = pszDirectory.length(); if (dir_len == 0) { return ERROR_BAD_PATHNAME; } if (dir_len + 3 > LONG_MAX_PATH) { return RemoveDirectoryForce(pszDirectory.c_str()); } pszFileBuffer = std::wstring(pszDirectory); if (dir_len && pszDirectory[dir_len - 1] != ':' && pszDirectory[dir_len - 1] != '\\') { pszFileBuffer += L"\\"; dir_len++; } pszFileBuffer += L"*"; find_handle = FindFirstFile(pszFileBuffer.c_str(), &find_data); if (find_handle == INVALID_HANDLE_VALUE) { return RemoveDirectoryForce(pszDirectory.c_str()); } do { new_str = std::wstring(find_data.cFileName); new_len = new_str.length(); if (dir_len + new_len >= LONG_MAX_PATH) { *AllEntriesDeleted = FALSE; std::wcerr << L"ERROR: PATH TOO LONG '" << new_str.c_str() << L"'" << std::endl; break; } pszFileBuffer = pszFileBuffer.substr(0,dir_len) + new_str; // display filename being processed if (pszFileBuffer.find(L"\\\\?\\UNC\\") == 0) { std::wcout << pszFileBuffer.c_str() + 8 << std::endl; } else if (pszFileBuffer.find(L"\\\\?\\") == 0) { std::wcout << pszFileBuffer.c_str() + 4 << std::endl; } else { std::wcout << pszFileBuffer.c_str() << std::endl; } attr = find_data.dwFileAttributes; if (!wcscmp(find_data.cFileName, L".") || !wcscmp(find_data.cFileName, L"..")) { continue; } DWORD attr = GetFileAttributesW(pszFileBuffer.c_str()); if (attr == 0xFFFFFFFF) { dwResult = GetLastError(); std::wcerr << L"Unale to get file attributes for '" << pszFileBuffer.c_str() << L"' Err#" << dwResult << std::endl; } if (IsDirectory(attr) && !IsReparse(attr)) { s = RemoveDirectoryAndSubdirectories(pszFileBuffer, &all_deleted); if (s != ERROR_SUCCESS) { *AllEntriesDeleted = FALSE; if (s != ERROR_DIR_NOT_EMPTY || all_deleted) { std::wcerr << L"ERROR: FAILED TO DELETE '" << pszFileBuffer.c_str() << L"' Err#" << s << std::endl; } } } else { if (attr & FILE_ATTRIBUTE_READONLY) { SetFileAttributes(pszFileBuffer.c_str(), attr & (~FILE_ATTRIBUTE_READONLY)); } if (attr & FILE_ATTRIBUTE_SYSTEM) { SetFileAttributes(pszFileBuffer.c_str(), attr & (~FILE_ATTRIBUTE_SYSTEM)); } if (!(IsDirectory(attr))) { bResult = DeleteFileW(pszFileBuffer.c_str()); if (!bResult) { dwResult = GetLastError(); switch (dwResult) { case ERROR_ACCESS_DENIED: std::wcout << L"Taking ownership of '" << pszFileBuffer.c_str() << "'" << std::endl; // take ownership of file and grant access TakeOwnership(pszFileBuffer.c_str()); attr = GetFileAttributesW(pszFileBuffer.c_str()); if (attr != 0xFFFFFFFF) { if (attr & FILE_ATTRIBUTE_READONLY) { SetFileAttributes(pszFileBuffer.c_str(), attr & (~FILE_ATTRIBUTE_READONLY)); } if (attr & FILE_ATTRIBUTE_SYSTEM) { SetFileAttributes(pszFileBuffer.c_str(), attr & (~FILE_ATTRIBUTE_SYSTEM)); } } bResult = DeleteFileW(pszFileBuffer.c_str()); if (bResult != ERROR_SUCCESS) { std::wcout << L"Unable to delete file '" << pszFileBuffer.c_str() << "'. Will attempt to remove on reboot." << std::endl; if (!MoveFileExW(pszFileBuffer.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { std::wcerr << L"Unable to remove on reboot Error: " << GetLastError() << std::endl; } else { bRebootRequired = true; bResult = ERROR_SUCCESS; } } break; case ERROR_SHARING_VIOLATION: std::wcout << L"File '" << pszFileBuffer.c_str() << "' is in use. Will remove on reboot." << std::endl; if (!MoveFileExW(pszFileBuffer.c_str(), NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { std::wcerr << L"Unable to remove on reboot Error: " << GetLastError() << std::endl; } else { bRebootRequired = true; bResult = ERROR_SUCCESS; } break; } if (bResult != ERROR_SUCCESS) { std::wcerr << L"ERROR: FAILED TO DELETE '" << pszFileBuffer.c_str() << L"' Err#" << dwResult << std::endl; } } } if ((IsDirectory(attr) && IsReparse(attr) && RemoveDirectoryForce(pszFileBuffer.c_str()) != ERROR_SUCCESS)) { s = GetLastError(); if (s == ERROR_REQUEST_ABORTED) break; dwResult = GetLastError(); std::wcerr << L"ERROR: FAILED TO DELETE '" << pszFileBuffer.c_str() << L"' Err#" << dwResult << std::endl; SetFileAttributesW(pszFileBuffer.c_str(), attr); *AllEntriesDeleted = FALSE; } } } while (FindNextFile(find_handle, &find_data)); FindClose(find_handle); return RemoveDirectoryForce(pszDirectory.c_str()); } int wmain(int argc, wchar_t* argv[]) { // disable wow64 redirection if API is present // not imported to prevent breaking on 32-bit OS typedef BOOL WINAPI fntype_Wow64DisableWow64FsRedirection(PVOID * OldValue); auto pfnWow64DisableWow64FsRedirection = (fntype_Wow64DisableWow64FsRedirection*)GetProcAddress(GetModuleHandleA("kernel32.dll"), "Wow64DisableWow64FsRedirection"); if (pfnWow64DisableWow64FsRedirection) { // function found, call it via pointer PVOID arg; (*pfnWow64DisableWow64FsRedirection)(&arg); } else { // function was missing ... don't care } if (argc == 2) { WCHAR* initialPath = argv[1]; std::wcout << L"Removing dirctory : '" << initialPath << L"'" << std::endl; WCHAR targetPath[LONG_MAX_PATH]; BOOL allDeleted = false; if (initialPath[0] == '\\' && initialPath[1] == '\\' && initialPath[2] != '?') { wcscpy_s(targetPath, LONG_MAX_PATH, L"\\\\?\\UNC\\"); wcscat_s(targetPath, LONG_MAX_PATH - 8, initialPath+2); } if (initialPath[1] == ':') { wcscpy_s(targetPath, LONG_MAX_PATH, L"\\\\?\\"); wcscat_s(targetPath, LONG_MAX_PATH - 4, initialPath); } RemoveDirectoryAndSubdirectories(targetPath, &allDeleted); if (bRebootRequired) { std::wcout << L"REBOOT REQUIRED to complete deletion." << std::endl; } } else { std::wcout << L"Removes (deletes) a directory and all subdirectories." << std::endl; std::wcout << std::endl; std::wcout << "LONGRMDIR [drive:]path" << std::endl; std::wcout << std::endl; std::wcout << "Removes all directories and files in the specified directory" << std::endl; std::wcout << "in addition to the directory itself. Used to remove a directory" << std::endl; std::wcout << "tree." << std::endl; } }
[ "noreply@github.com" ]
chentiangemalc.noreply@github.com
8582636588b1989d294802fb7f700cef1bdbb1d2
0f41a3350f5267b25b1757142b430fe7b838a124
/SRC/game/pacman/Pacman.cpp
0ece95e298ca57ca2d791251f360f6f5d16a0dd0
[]
no_license
imadKimouche/Arcade
d99d4f98de819b5ff5479f8549107a0acd118d51
13f0d6037d5eb9e665bd95286388981f93e0bf5d
refs/heads/master
2020-03-24T08:44:56.558623
2018-07-27T17:49:17
2018-07-27T17:49:17
142,606,210
1
0
null
null
null
null
UTF-8
C++
false
false
3,327
cpp
/* ** EPITECH PROJECT, 2018 ** Arcade - Pacman ** File description: ** PacmanPlayer.cpp */ #include "Pacman.hpp" Pacman::Pacman(Data *data, PacBoard *board, PacGame *game) { setCoordImg({1 * 32, 4 * 32}); setSize({32, 32}); setFont(PFont_t{255, 255, 0, 255, 1, ""}); setTermpic("C"); _life = 3; _game = game; _data = data; _board = board; _super = false; _directionW = 'R'; _direction = 'R'; } Pacman::~Pacman() { } bool Pacman::moveValid(const int &x, const int &y) { return (x >= 0 && y >= 0 && x < _data->getMapX() && y < _data->getMapY() - 1 && !_board->getBlock(x, y)->isSolid()); } void Pacman::eat() { double x = getCoord().x; double y = getCoord().y; switch (_board->getBlock(x, y)->getType()) { case Block::GUM: _board->getBlock(x, y)->setType(Block::BACKGROUND); _data->setScore(_data->getScore() + 10); break; case Block::SUPERGUM: _board->getBlock(x, y)->setType(Block::BACKGROUND); _data->setScore(_data->getScore() + 50); _super = true; break; default: break; } } void Pacman::kill() { _life--; _game->getLives()->setLives(); if (!_life) _game->stop(); else _game->restart(); } bool Pacman::isSuper() const { return _super; } void Pacman::look() { if (_data->isKey(M_KEY_UP)) _directionW = 'U'; if (_data->isKey(M_KEY_DOWN)) _directionW = 'D'; if (_data->isKey(M_KEY_LEFT)) _directionW = 'L'; if (_data->isKey(M_KEY_RIGHT)) _directionW = 'R'; } void Pacman::move() { double x = getCoord().x; double y = getCoord().y; switch (_direction) { case 'U': if (moveValid(x, y - 1)) go({x, y - 1}); break; case 'D': if (moveValid(x, y + 1)) go({x, y + 1}); break; case 'L': if (moveValid(x - 1, y)) go({x - 1, y}); break; case 'R': if (moveValid(x + 1, y)) go({x + 1, y}); break; default: go({x, y}); break; } } void Pacman::update() { double x = getCoord().x; double y = getCoord().y; look(); if (x != getTogo().x || y != getTogo().y) return; eat(); switch (_directionW) { case 'U': if (moveValid(x, y - 1)) _direction = _directionW; break; case 'D': if (moveValid(x, y + 1)) _direction = _directionW; break; case 'L': if (moveValid(x - 1, y)) _direction = _directionW; break; case 'R': if (moveValid(x + 1, y)) _direction = _directionW; break; default: break; } move(); } void Pacman::saveScore() { std::ifstream file; file.open("ressources/score/score.sc"); std::string score1; std::string score2; std::string score3; std::getline(file, score1); std::getline(file, score1); std::getline(file, score2); std::getline(file, score2); std::getline(file, score3); std::getline(file, score3); file.close(); std::ofstream file_out; file_out.open("ressources/score/score.sc"); if (stoi(score2) < _data->getScore()) score2 = std::to_string(_data->getScore()); file_out << "snake" << "\n"; file_out << score1 << "\n"; file_out << "pacman" << "\n"; file_out << score2 << "\n"; file_out << "qix" << "\n"; file_out << score3 << "\n"; }
[ "imad.kimouche@epitech.eu" ]
imad.kimouche@epitech.eu
aa20b7b8da181c375f63c7600c46751604769ba6
88f6c3cb02a0d7ddbc391d659d662dda5c5f0ba3
/List/Last.h
1c9d480c917c14ed086c6fed9e26014fa8680488
[]
no_license
LYN088286/Data_Structure_Algorithm_Cpp
4677e11a69f2ce2143a796bc7dc581544c91aaf4
0a598589bcb86d6e06fe4838b70213370ebfce34
refs/heads/main
2023-07-16T19:17:26.335917
2021-08-28T09:23:10
2021-08-28T09:23:10
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
111
h
#pragma once template <typename T> listnode<T>* List<T>::Last() { return tailer->pred; //·µ»ØÎ²²¿ }
[ "1306014226@qq.com" ]
1306014226@qq.com
b24e4a190d5e292ae205027b91f44190a7999303
d6f9c24876b4856cf8b696fac435b4a573e21888
/display.hpp
00082f4cd62c92e56d10be32577f44fdbe6090e4
[]
no_license
antonyalkmim/Thermometer
d1d508f0336d968094dd36cdb6eeef59d40e45b9
7313f61cad13aff76d1e89d1cf0df2447c8a4dcf
refs/heads/master
2021-01-20T20:11:01.653856
2016-06-29T22:14:06
2016-06-29T22:14:06
61,497,972
0
0
null
null
null
null
UTF-8
C++
false
false
2,349
hpp
/** * Biblioteca DISPLAY */ #include <avr/pgmspace.h> #define LCD_COMMAND 0 #define LCD_DATA 1 #define LCD_CLEAR 0x01 //limpa o display //cursor commands #define LCD_CURSOR_RESET 0x02 //volta o cursor para primeira coluna e primeira linha #define LCD_CURSOR_ON 0x0E; //liga cursor #define LCD_CURSOR_OFF 0x0C; //desliga cursor #define LCD_CURSOR_LEFT 0x10; //desloca cursor para esquerda #define LCD_CURSOR_RIGHT 0x14 //desloca cursor para direita #define LCD_CURSOR_LN1 0x80 //cursor no inicio da linha 1 #define LCD_CURSOR_LN2 0xC0 //cursor no inicio da linha 2 /* * Enviar caracteres e comandos ao LCD com via de dados de 8 bits. * c é o dado e cd indica se é instrução ou caractere (0 ou 1). **/ void lcd_exec(unsigned char c, int cd); /* Inicialização do LCD com via de dados de 8 bits*/ void lcd_init(); /* Escrita no LCD – dados armazenados na RAM */ void lcd_print(char *c); /* Escrita no LCD – dados armazenados na FLASH */ void lcd_print_flash(const char *c); /* Executa um comando no display */ void lcd_command(const uint8_t command); /* Gera o pulso para habilitar comanando */ void lcd_pulse(); void lcd_init(){ _delay_us(40); PORTA &= ~0x02; //negar RS PORTC = 7 << 3; lcd_pulse(); //function set _delay_us(39); PORTA &= ~0x02; //negar RS PORTC = 7 << 3; lcd_pulse(); //display control _delay_us(37); PORTA &= ~0x02; //negar RS PORTC = 0x0f; //display clear _delay_us(37); PORTA &= ~0x02; //negar RS PORTC = 0x01; lcd_pulse(); //mode set _delay_us(1600); PORTA &= ~0x02; //negar RS PORTC = 3 << 1; lcd_pulse(); } void lcd_exec(unsigned char c, int cd){ //identifica se e dados ou comando PORTA = cd == 1 ? (PORTA | 2) : (PORTA & ~2); PORTC = c; //transfere o dado //gerar pulso de habilitacao lcd_pulse(); //gerar delay extra para funcoes de limpar if(cd == 0 && (c == 0x01 || c == 0x02)){ _delay_us(1600); } } void lcd_command(const uint8_t command){ lcd_exec(command, LCD_COMMAND); } void lcd_print(char *c){ int ch = 0; while (c[ch] != 0) { lcd_exec(c[ch], LCD_DATA); ++ch; } } void lcd_print_flash(const char *c){ int ch = 0; char word = pgm_read_byte(&c[ch]); while (word != 0) { lcd_exec(word, LCD_DATA); word = pgm_read_byte(&c[++ch]);; } } void lcd_pulse(){ _delay_us(1); PORTA |= 1; _delay_us(1); PORTA &= ~(1); _delay_us(45); }
[ "antony-alkmim@hotmail.com" ]
antony-alkmim@hotmail.com
b3e0c0e7c349c169ef09c676359119fe28950e0e
6e59bf5c3f287024ac3eaa4e1e45bb703f3ce545
/QtCreator/FindCrap/main.cpp
4e13df21d6b0be3a51c532955e3a60de2e2353cf
[]
no_license
N0683858/Code_files
47062ed1f0ef43a113da2641d27fab5e622681ee
7d4e25dfa5a609c464ae4c61a46315deb37b3857
refs/heads/master
2022-09-21T20:58:37.049220
2019-10-21T23:12:18
2019-10-21T23:12:18
128,095,939
0
0
null
2022-08-31T22:22:20
2018-04-04T17:20:31
CSS
UTF-8
C++
false
false
1,687
cpp
#include "findcrap.h" #include <QApplication> #include <QFile> #include <QTextStream> #include <QDebug> #include <iostream> #include <vector> void Write(QString fileName); void Read(QString fileName); int main(int argc, char *argv[]) { QApplication a(argc, argv); // FindCrap w; // w.show(); Write("TextFile.txt"); Read("TextFile.txt"); return a.exec(); } void Write(QString fileName) { QFile myFile(fileName); if(!myFile.open(QIODevice::WriteOnly | QIODevice::Append)) { qDebug() << "The file could not open"; return; } QTextStream writing (&myFile); for(int i = 0; i < 5; i++) { writing << "HEllo" << " "; writing << "WorlD" << " "; writing << "!" << " " << i << "\n"; } myFile.close(); } void Read(QString fileName) { QFile myFile(fileName); if(!myFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Could not open the file"; return; } QTextStream reading(&myFile); //reading.setCodec("UTF-8"); //while(!reading.atEnd()) for(int i = 0; i < 5; i++) { QString myText = reading.readLine(); QRegExp rx("[, \n]"); // match a comma or a space QStringList list = myText.split(rx, QString::SkipEmptyParts); // for(int x = 0; x < list.size(); x++) // { qDebug() << list.at(0); qDebug() << list.at(1); qDebug() << list.at(2); qDebug() << list.at(3); // } // myText.remove(','); // qDebug()<<myText; // auto commaFree = myText.split(','); // qDebug() << commaFree; } myFile.close(); }
[ "N0683858@my.ntu.ac.uk" ]
N0683858@my.ntu.ac.uk
a244d92d62507395dc6ea0b99029978cc116aca5
364e5cd1ce6948183e6ebb38bd8f555511b54495
/LIWorks/vernal/server/include/LIWorksServer.h
7cbe1206d613f451475d6044b3c0d70858cc8417
[]
no_license
danelumax/CPP_study
c38e37f0d2cebe4adccc65ad1064aa338913f044
22124f8d83d59e5b351f16983d638a821197b7ae
refs/heads/master
2021-01-22T21:41:11.867311
2017-03-19T09:01:11
2017-03-19T09:01:11
85,462,945
0
0
null
null
null
null
UTF-8
C++
false
false
803
h
/* * LIWorksServer.h * * Created on: 2016年1月31日 * Author: root */ #ifndef LIWORKSSERVER_H_ #define LIWORKSSERVER_H_ #include <iostream> #include <string> #include "EPCWorker.h" #include "MessageQ.h" #include "TcpServerSocket.h" #include "XMLParse.h" #include "WorkEngine.h" #include <WorkEngineManager.h> #define LOCALHOST "127.0.0.1" #define POOLNUM 5 class LIWorksServer { public: virtual ~LIWorksServer(); int init(); int run(); static void destory(); static LIWorksServer* getInstance(); int setupTcpServer(const char* addr, int port); int initWorkEngine(); void destroyWorkEngine(); void cleanUpResources(); protected: LIWorksServer(); private: static LIWorksServer *_instance; TcpServerSocket* _tcp_server; MessageQ *_msgQ; }; #endif /* LIWORKSSERVER_H_ */
[ "474198699@qq.com" ]
474198699@qq.com
6919c05a76f103e8d95257c2b6123e0fa5770027
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_new_hunk_2862.cpp
02c3649d6888910f7ddf098ffbab56cebf8e63eb
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
*/ refresh_cache(REFRESH_QUIET); if (allow_trivial && fast_forward != FF_ONLY) { /* See if it is really trivial. */ git_committer_info(IDENT_STRICT); printf(_("Trying really trivial in-index merge...\n")); if (!read_tree_trivial(common->item->object.oid.hash, head_commit->object.oid.hash, remoteheads->item->object.oid.hash)) { ret = merge_trivial(head_commit, remoteheads); goto done; } printf(_("Nope.\n")); } } else {
[ "993273596@qq.com" ]
993273596@qq.com
8c2278b729f7248091467daf6fe263751a5ac2e0
c0d88ca5fb78d9ce2b0162bf7967466f8eefacb6
/stc_embed_c.cpp
94742f33118babf6872213e0fbd4d80a50aafdc8
[]
no_license
zhangling48/pySTC
cfaa84786a9657d9bfbcd83341009fe479745a8f
5bec5e97bf3a8556b7554a1638ee50df4c271f4d
refs/heads/master
2022-04-18T05:15:21.219843
2019-03-18T12:04:00
2019-03-18T12:04:00
255,926,495
0
0
null
2020-04-15T13:33:20
2020-04-15T13:33:19
null
UTF-8
C++
false
false
18,149
cpp
#include <cstdlib> #include <cstring> #include <cmath> #include <cfloat> #include <limits> #include <emmintrin.h> #include <cstdio> #include <sstream> #include "stc_embed_c.h" void *aligned_malloc( unsigned int bytes, int align ) { int shift; char *temp = (char *) malloc( bytes + align ); if ( temp == NULL ) return temp; shift = align - (int) (((unsigned long long) temp) & (align - 1)); temp = temp + shift; temp[-1] = shift; return (void *) temp; } void aligned_free( void *vptr ) { char *ptr = (char *) vptr; free( ptr - ptr[-1] ); return; } inline __m128i maxLessThan255( const __m128i v1, const __m128i v2 ) { register __m128i mask = _mm_set1_epi32( 0xffffffff ); return _mm_max_epu8( _mm_andnot_si128( _mm_cmpeq_epi8( v1, mask ), v1 ), _mm_andnot_si128( _mm_cmpeq_epi8( v2, mask ), v2 ) ); } inline u8 max16B( __m128i maxp ) { u8 mtemp[4]; maxp = _mm_max_epu8( maxp, _mm_srli_si128(maxp, 8) ); maxp = _mm_max_epu8( maxp, _mm_srli_si128(maxp, 4) ); *((int*) mtemp) = _mm_cvtsi128_si32( maxp ); if ( mtemp[2] > mtemp[0] ) mtemp[0] = mtemp[2]; if ( mtemp[3] > mtemp[1] ) mtemp[1] = mtemp[3]; if ( mtemp[1] > mtemp[0] ) return mtemp[1]; else return mtemp[0]; } inline u8 min16B( __m128i minp ) { u8 mtemp[4]; minp = _mm_min_epu8( minp, _mm_srli_si128(minp, 8) ); minp = _mm_min_epu8( minp, _mm_srli_si128(minp, 4) ); *((int*) mtemp) = _mm_cvtsi128_si32( minp ); if ( mtemp[2] < mtemp[0] ) mtemp[0] = mtemp[2]; if ( mtemp[3] < mtemp[1] ) mtemp[1] = mtemp[3]; if ( mtemp[1] < mtemp[0] ) return mtemp[1]; else return mtemp[0]; } double stc_embed( const u8 *vector, int vectorlength, const u8 *syndrome, int syndromelength, const void *pricevectorv, bool usefloat, u8 *stego, int matrixheight ) { int height, i, k, l, index, index2, parts, m, sseheight, altm, pathindex; u32 column, colmask, state; double totalprice; u8 *ssedone; u32 *path, *columns[2]; int *matrices, *widths; if ( matrixheight > 31 ) { // throw stc_exception( "Submatrix height must not exceed 31.", 1 ); printf("Exception: Submatrix height must not exceed 31.\n"); exit(0); } height = 1 << matrixheight; colmask = height - 1; height = (height + 31) & (~31); parts = height >> 5; if ( stego != NULL ) { path = (u32*) malloc( vectorlength * parts * sizeof(u32) ); if ( path == NULL ) { std::stringstream ss; ss << "Not enough memory (" << (unsigned int) (vectorlength * parts * sizeof(u32)) << " byte array could not be allocated)."; throw stc_exception( ss.str(), 2 ); } pathindex = 0; } { int shorter, longer, worm; double invalpha; matrices = (int *) malloc( syndromelength * sizeof(int) ); widths = (int *) malloc( syndromelength * sizeof(int) ); invalpha = (double) vectorlength / syndromelength; if ( invalpha < 1 ) { //free( matrices ); //free( widths ); //if ( stego != NULL ) free( path ); printf("Exception111: The message cannot be longer than the cover object.\n"); //exit(0); //throw stc_exception( "The message cannot be longer than the cover object.", 3 ); } /* THIS IS OBSOLETE. Algorithm still works for alpha >1/2. You need to take care of cases with too many Infs in cost vector. if(invalpha < 2) { printf("The relative payload is greater than 1/2. This may result in poor embedding efficiency.\n"); } */ shorter = (int) floor( invalpha ); longer = (int) ceil( invalpha ); if ( (columns[0] = getMatrix( shorter, matrixheight )) == NULL ) { free( matrices ); free( widths ); if ( stego != NULL ) free( path ); return -1; } if ( (columns[1] = getMatrix( longer, matrixheight )) == NULL ) { free( columns[0] ); free( matrices ); free( widths ); if ( stego != NULL ) free( path ); return -1; } worm = 0; for ( i = 0; i < syndromelength; i++ ) { if ( worm + longer <= (i + 1) * invalpha + 0.5 ) { matrices[i] = 1; widths[i] = longer; worm += longer; } else { matrices[i] = 0; widths[i] = shorter; worm += shorter; } } } if ( usefloat ) { /* SSE FLOAT VERSION */ int pathindex8 = 0; int shift[2] = { 0, 4 }; u8 mask[2] = { 0xf0, 0x0f }; float *prices; u8 *path8 = (u8*) path; double *pricevector = (double*) pricevectorv; double total = 0; float inf = std::numeric_limits< float >::infinity(); sseheight = height >> 2; ssedone = (u8*) malloc( sseheight * sizeof(u8) ); prices = (float*) aligned_malloc( height * sizeof(float), 16 ); { __m128 fillval = _mm_set1_ps( inf ); for ( i = 0; i < height; i += 4 ) { _mm_store_ps( &prices[i], fillval ); ssedone[i >> 2] = 0; } } prices[0] = 0.0f; for ( index = 0, index2 = 0; index2 < syndromelength; index2++ ) { register __m128 c1, c2; for ( k = 0; k < widths[index2]; k++, index++ ) { column = columns[matrices[index2]][k] & colmask; if ( vector[index] == 0 ) { c1 = _mm_setzero_ps(); c2 = _mm_set1_ps( (float) pricevector[index] ); } else { c1 = _mm_set1_ps( (float) pricevector[index] ); c2 = _mm_setzero_ps(); } total += pricevector[index]; for ( m = 0; m < sseheight; m++ ) { if ( !ssedone[m] ) { register __m128 v1, v2, v3, v4; altm = (m ^ (column >> 2)); v1 = _mm_load_ps( &prices[m << 2] ); v2 = _mm_load_ps( &prices[altm << 2] ); v3 = v1; v4 = v2; ssedone[m] = 1; ssedone[altm] = 1; switch ( column & 3 ) { case 0: break; case 1: v2 = _mm_shuffle_ps(v2, v2, 0xb1); v3 = _mm_shuffle_ps(v3, v3, 0xb1); break; case 2: v2 = _mm_shuffle_ps(v2, v2, 0x4e); v3 = _mm_shuffle_ps(v3, v3, 0x4e); break; case 3: v2 = _mm_shuffle_ps(v2, v2, 0x1b); v3 = _mm_shuffle_ps(v3, v3, 0x1b); break; } v1 = _mm_add_ps( v1, c1 ); v2 = _mm_add_ps( v2, c2 ); v3 = _mm_add_ps( v3, c2 ); v4 = _mm_add_ps( v4, c1 ); v1 = _mm_min_ps( v1, v2 ); v4 = _mm_min_ps( v3, v4 ); _mm_store_ps( &prices[m << 2], v1 ); _mm_store_ps( &prices[altm << 2], v4 ); if ( stego != NULL ) { v2 = _mm_cmpeq_ps( v1, v2 ); v3 = _mm_cmpeq_ps( v3, v4 ); path8[pathindex8 + (m >> 1)] = (path8[pathindex8 + (m >> 1)] & mask[m & 1]) | (_mm_movemask_ps( v2 ) << shift[m & 1]); path8[pathindex8 + (altm >> 1)] = (path8[pathindex8 + (altm >> 1)] & mask[altm & 1]) | (_mm_movemask_ps( v3 ) << shift[altm & 1]); } } } for ( i = 0; i < sseheight; i++ ) { ssedone[i] = 0; } pathindex += parts; pathindex8 += parts << 2; } if ( syndrome[index2] == 0 ) { for ( i = 0, l = 0; i < sseheight; i += 2, l += 4 ) { _mm_store_ps( &prices[l], _mm_shuffle_ps(_mm_load_ps(&prices[i << 2]), _mm_load_ps(&prices[(i + 1) << 2]), 0x88) ); } } else { for ( i = 0, l = 0; i < sseheight; i += 2, l += 4 ) { _mm_store_ps( &prices[l], _mm_shuffle_ps(_mm_load_ps(&prices[i << 2]), _mm_load_ps(&prices[(i + 1) << 2]), 0xdd) ); } } if ( syndromelength - index2 <= matrixheight ) colmask >>= 1; { register __m128 fillval = _mm_set1_ps( inf ); for ( l >>= 2; l < sseheight; l++ ) { _mm_store_ps( &prices[l << 2], fillval ); } } } totalprice = prices[0]; aligned_free( prices ); free( ssedone ); if ( totalprice >= total ) { free( matrices ); free( widths ); free( columns[0] ); free( columns[1] ); if ( stego != NULL ) free( path ); //throw stc_exception( "No solution exist.", 4 ); printf("Exception: No solution exist.\n"); exit(0); } } else { /* SSE UINT8 VERSION */ int pathindex16 = 0, subprice = 0; u8 maxc = 0, minc = 0; u8 *prices, *pricevector = (u8*) pricevectorv; u16 *path16 = (u16 *) path; __m128i *prices16B; sseheight = height >> 4; ssedone = (u8*) malloc( sseheight * sizeof(u8) ); prices = (u8*) aligned_malloc( height * sizeof(u8), 16 ); prices16B = (__m128i *) prices; { __m128i napln = _mm_set1_epi32( 0xffffffff ); for ( i = 0; i < sseheight; i++ ) { _mm_store_si128( &prices16B[i], napln ); ssedone[i] = 0; } } prices[0] = 0; for ( index = 0, index2 = 0; index2 < syndromelength; index2++ ) { register __m128i c1, c2, maxp, minp; if ( (u32) maxc + pricevector[index] >= 254 ) { aligned_free( path ); free( ssedone ); free( matrices ); free( widths ); free( columns[0] ); free( columns[1] ); if ( stego != NULL ) free( path ); // throw stc_exception( "Price vector limit exceeded.", 5 ); printf("Exception: Pirce vector limit exceeded.\n"); exit(0); } for ( k = 0; k < widths[index2]; k++, index++ ) { column = columns[matrices[index2]][k] & colmask; if ( vector[index] == 0 ) { c1 = _mm_setzero_si128(); c2 = _mm_set1_epi8( pricevector[index] ); } else { c1 = _mm_set1_epi8( pricevector[index] ); c2 = _mm_setzero_si128(); } minp = _mm_set1_epi8( -1 ); maxp = _mm_setzero_si128(); for ( m = 0; m < sseheight; m++ ) { if ( !ssedone[m] ) { register __m128i v1, v2, v3, v4; altm = (m ^ (column >> 4)); v1 = _mm_load_si128( &prices16B[m] ); v2 = _mm_load_si128( &prices16B[altm] ); v3 = v1; v4 = v2; ssedone[m] = 1; ssedone[altm] = 1; if ( column & 8 ) { v2 = _mm_shuffle_epi32(v2, 0x4e); v3 = _mm_shuffle_epi32(v3, 0x4e); } if ( column & 4 ) { v2 = _mm_shuffle_epi32(v2, 0xb1); v3 = _mm_shuffle_epi32(v3, 0xb1); } if ( column & 2 ) { v2 = _mm_shufflehi_epi16(v2, 0xb1); v3 = _mm_shufflehi_epi16(v3, 0xb1); v2 = _mm_shufflelo_epi16(v2, 0xb1); v3 = _mm_shufflelo_epi16(v3, 0xb1); } if ( column & 1 ) { v2 = _mm_or_si128( _mm_srli_epi16( v2, 8 ), _mm_slli_epi16( v2, 8 ) ); v3 = _mm_or_si128( _mm_srli_epi16( v3, 8 ), _mm_slli_epi16( v3, 8 ) ); } v1 = _mm_adds_epu8( v1, c1 ); v2 = _mm_adds_epu8( v2, c2 ); v3 = _mm_adds_epu8( v3, c2 ); v4 = _mm_adds_epu8( v4, c1 ); v1 = _mm_min_epu8( v1, v2 ); v4 = _mm_min_epu8( v3, v4 ); _mm_store_si128( &prices16B[m], v1 ); _mm_store_si128( &prices16B[altm], v4 ); minp = _mm_min_epu8( minp, _mm_min_epu8( v1, v4 ) ); maxp = _mm_max_epu8( maxp, maxLessThan255( v1, v4 ) ); if ( stego != NULL ) { v2 = _mm_cmpeq_epi8( v1, v2 ); v3 = _mm_cmpeq_epi8( v3, v4 ); path16[pathindex16 + m] = (u16) _mm_movemask_epi8( v2 ); path16[pathindex16 + altm] = (u16) _mm_movemask_epi8( v3 ); } } } maxc = max16B( maxp ); minc = min16B( minp ); maxc -= minc; subprice += minc; { register __m128i mask = _mm_set1_epi32( 0xffffffff ); register __m128i m = _mm_set1_epi8( minc ); for ( i = 0; i < sseheight; i++ ) { register __m128i res; register __m128i pr = prices16B[i]; res = _mm_andnot_si128( _mm_cmpeq_epi8( pr, mask ), m ); prices16B[i] = _mm_sub_epi8( pr, res ); ssedone[i] = 0; } } pathindex += parts; pathindex16 += parts << 1; } { register __m128i mask = _mm_set1_epi32( 0x00ff00ff ); if ( minc == 255 ) { aligned_free( path ); free( ssedone ); free( matrices ); free( widths ); free( columns[0] ); free( columns[1] ); if ( stego != NULL ) free( path ); //throw stc_exception( "The syndrome is not in the syndrome matrix range.", 4 ); printf("Exception: The syndrome is not in the syndrome matrix range.\n"); exit(0); } if ( syndrome[index2] == 0 ) { for ( i = 0, l = 0; i < sseheight; i += 2, l++ ) { _mm_store_si128( &prices16B[l], _mm_packus_epi16( _mm_and_si128( _mm_load_si128( &prices16B[i] ), mask ), _mm_and_si128( _mm_load_si128( &prices16B[i + 1] ), mask ) ) ); } } else { for ( i = 0, l = 0; i < sseheight; i += 2, l++ ) { _mm_store_si128( &prices16B[l], _mm_packus_epi16( _mm_and_si128( _mm_srli_si128(_mm_load_si128(&prices16B[i]), 1), mask ), _mm_and_si128( _mm_srli_si128(_mm_load_si128(&prices16B[i + 1]), 1), mask ) ) ); } } if ( syndromelength - index2 <= matrixheight ) colmask >>= 1; register __m128i fillval = _mm_set1_epi32( 0xffffffff ); for ( ; l < sseheight; l++ ) _mm_store_si128( &prices16B[l], fillval ); } } totalprice = subprice + prices[0]; aligned_free( prices ); free( ssedone ); } if ( stego != NULL ) { pathindex -= parts; index--; index2--; state = 0; // unused // int h = syndromelength; state = 0; colmask = 0; for ( ; index2 >= 0; index2-- ) { for ( k = widths[index2] - 1; k >= 0; k--, index-- ) { if ( k == widths[index2] - 1 ) { state = (state << 1) | syndrome[index2]; if ( syndromelength - index2 <= matrixheight ) colmask = (colmask << 1) | 1; } if ( path[pathindex + (state >> 5)] & (1 << (state & 31)) ) { stego[index] = 1; state = state ^ (columns[matrices[index2]][k] & colmask); } else { stego[index] = 0; } pathindex -= parts; } } free( path ); } free( matrices ); free( widths ); free( columns[0] ); free( columns[1] ); return totalprice; }
[ "dlerch@gmail.com" ]
dlerch@gmail.com
0e52232a5f0c78b952c52a84b326d6bf062c7e08
1106985164494c361c6ef017189cd6f53f6009d4
/06 Array/Source Files/Z_others/FindtheSmallestPositiveNoinUnsortedArraywithNegativeNums.cpp
e8f4bffd6281ea6f73a873a6a5e41fa40d429dda
[]
no_license
SlickHackz/famous-problems-cpp-solutions
b7f0066a03404a20c1a4b483acffda021595c530
f954b4a8ca856cc749e232bd9d8894a672637ae2
refs/heads/master
2022-08-25T23:14:11.975270
2022-07-17T22:07:03
2022-07-17T22:07:03
71,126,427
1
0
null
null
null
null
UTF-8
C++
false
false
792
cpp
#include<iostream> using namespace std; void Swap(int *a,int *b) { if(a!=b) { int temp = *a; *a = *b; *b = temp; } } int segregatePosNeg(int arr[],int n) { int i=0,j=n-1; while(i<j) { if(arr[i] < 0) { Swap(&arr[i],&arr[j]); j--; } else i++; } return j; } int getSmallestPositiveNum(int arr[],int n) { int len = segregatePosNeg(arr,n); for(int i=0 ; i<=len-1 ; i++) { if(abs(arr[i])<len && arr[abs(arr[i])-1] > 0 ) arr[abs(arr[i])-1] = arr[abs(arr[i])-1]*-1; } for(int i=0 ; i<=len ; i++) { if(arr[i] > 0) return i+1; } return len; } int main() { int arr[] = {1, 1, 0, -1, -2}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"The smallest +ve number missing is : "<<getSmallestPositiveNum(arr,n); cin.get(); cin.get(); return 0; }
[ "prasath17101990@gmail.com" ]
prasath17101990@gmail.com
5ac93a73bff1a24f971cab8d009a8a123c9f7ab1
47e1c788b47ca546fb19367c44204bdc9763d3ad
/include/pbj/sw/resource_id.inl
36b4c8e391be17cb0ef40ab98a3c42b1897a20be
[ "MIT" ]
permissive
bcrist/PBJgame
9a1bb00d9690a647e30a9ebc89e99926820c066b
74682c061a96e90a41ae3c54f21da6f7cee17db5
refs/heads/master
2021-01-25T05:16:09.284707
2013-07-22T22:38:03
2013-07-22T22:38:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,348
inl
// Copyright (c) 2013 PBJ^2 Productions // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// /// \file pbj/sw/resource_id.inl /// \author Benjamin Crist /// /// \brief Implementations of pbj::sw::ResourceId template functions. #if !defined(PBJ_SW_RESOURCE_ID_H_) && !defined(DOXYGEN) #include "pbj/sw/resource_id.h" #elif !defined(PBJ_SW_RESOURCE_ID_INL_) #define PBJ_SW_RESOURCE_ID_INL_ /////////////////////////////////////////////////////////////////////////////// /// \brief \c std::hash specialization for utilizing ResourceId objects in /// \c std::unordered_set and \c std::unordered_map containers. template<> struct std::hash<pbj::sw::ResourceId> { public: //////////////////////////////////////////////////////////////////////////// /// \brief Calculates the hashcode of the provided ResourceId. /// \details Just XORs the \c std::hash values of the two Ids that make up /// the ResourceId. /// \param id The ResourceId to hash. /// \return A hashcode suitable for use in hashtable-based data structures. size_t operator()(const pbj::sw::ResourceId& id) const { std::hash<be::Id> hash_id; return hash_id(id.sandwich) ^ hash_id(id.resource); } }; #endif
[ "ben@magicmoremagic.com" ]
ben@magicmoremagic.com
f1735b747247563086256b7494dea19faccd1e56
d3c777fffba101d399459f389d2bdf7ee47315f8
/LinkedList/Remove_Duplicates_FromSortedListII.cpp
869593a23237581c937ac8c0eb0f8ac5fe22cc64
[]
no_license
zhangkeplus/LeetCode
db54601217c71fea86336cffcbe66eba33c299d5
389e268d143490ce03707291007a34263ccdd810
refs/heads/master
2021-01-01T15:30:24.895147
2014-12-11T07:29:01
2014-12-11T07:29:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode *first = deleteSameHead(head); if (first == NULL){ return NULL; } ListNode *r = first; while(r!=NULL){ ListNode *temp = deleteSameHead(r->next); r->next = temp; r = temp; } return first; } ListNode *deleteSameHead(ListNode *t){ if(t == NULL || t->next == NULL){ return t; } if (t->val != t->next->val){ return t; } while(t->val == t->next->val){ t = t->next; if(t->next == NULL){ return NULL; } } return deleteSameHead(t->next); } };
[ "zhangkeplus@gmail.com" ]
zhangkeplus@gmail.com
612d17766cc98299a0cf9b3fec07d9001a7d7024
59672651deb4521a866bed9ce4648a1448c602c6
/c++ programs/structured c++/pages of book read/main.cpp
94a4fa54a2213d63c881359de12588bda8469244
[]
no_license
muhammadahmadazhar/my-whole-programing
46b4bbdc2091a192089a302f6520987351115fa4
5ffcbd9999085f1795a12e419845c9a3ec4397b4
refs/heads/master
2020-09-06T00:17:59.437892
2020-03-24T19:49:49
2020-03-24T19:49:49
220,252,900
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include <iostream> #include<conio.h> using namespace std; int main() { int tp,rp,remp,days; cout<<"input total number of pages of a book ,no of pages read a person output no of pages read and no of pages remaining"<<endl; cout<<"total pages="; cin>>tp; cout<<"read pages="; cin>>rp; cout<<"no of days="; cin>>days; rp=rp*days; remp=tp-rp; cout<<"remaining pages="<<remp<<endl; return 0; }
[ "muhammadahmadazhar16@gmail.com" ]
muhammadahmadazhar16@gmail.com
1dd77f5de96fb582a8c3cca1b68404932fd7fc4f
3fc856fb394f76bb1b58401abde83d13b8ac8df1
/testing/JSBatteryLevel/Unit1.cpp
bcc3e0c368179d3f3677cbf54cf09038855381b8
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSL-1.0" ]
permissive
TotteKarlsson/ArrayBot
69d9ad26f7614ce36eb0aee919fd4868daef953c
d0e11186abd5b380ebba6e432f642d04a947e5aa
refs/heads/master
2022-11-18T17:33:35.411944
2018-12-18T17:41:08
2018-12-18T17:41:08
57,317,749
2
1
null
null
null
null
UTF-8
C++
false
false
3,653
cpp
#include <vcl.h> #pragma hdrstop #include <XInput.h> #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { HINSTANCE l = LoadLibrary("xinput1_3.dll"); if(l) { MessageDlg("Loaded dll", mtWarning, TMsgDlgButtons() << mbOK, 0); } // // Dummy call to ensure the system activates the controller XINPUT_STATE state; //DWORD WINAPI XInputGetState //( // DWORD dwUserIndex, // [in] Index of the gamer associated with the device // XINPUT_STATE* pState // [out] Receives the current state //); typedef DWORD (CALLBACK* XInputGetStateFP)(DWORD, XINPUT_STATE*); XInputGetStateFP test = NULL; test = (XInputGetStateFP) (GetProcAddress(l, "XInputGetState")); if(test) { MessageDlg("Loaded dll", mtWarning, TMsgDlgButtons() << mbOK, 0); } XInputGetStateFP(0, &state); // if(stateGamepad) // { // MessageDlg("Loaded dll", mtWarning, TMsgDlgButtons() << mbOK, 0); // } if(state.dwPacketNumber != 0) { MessageDlg("Loaded dll", mtWarning, TMsgDlgButtons() << mbOK, 0); } // Get the actual battery info // XINPUT_BATTERY_INFORMATION info; // if (XInputGetBatteryInformation(0, BATTERY_DEVTYPE_GAMEPAD, &info) != ERROR_SUCCESS) // { // info.BatteryType = BATTERY_TYPE_DISCONNECTED; // } //// const wchar_t *tip = icon_label; //// wired_ = false; // switch (info.BatteryType) // { // case BATTERY_TYPE_WIRED: //// batlevel_ = 1; //// nocontroller_ = false; //// unknown_ = false; //// wired_ = true; //// tip = L"Wired Controller"; // break; // // case BATTERY_TYPE_ALKALINE: // case BATTERY_TYPE_NIMH: //// switch (info.BatteryLevel) //// { //// case BATTERY_LEVEL_EMPTY: ////// batlevel_ = 0; ////// tip = L"Controller battery is empty"; //// break; //// case BATTERY_LEVEL_LOW: //// batlevel_ = 0.3f; //// tip = L"Controller battery is getting low"; //// break; //// case BATTERY_LEVEL_MEDIUM: //// batlevel_ = 0.6f; //// tip = L"Controller battery is OK"; //// break; //// case BATTERY_LEVEL_FULL: //// batlevel_ = 1; //// tip = L"Controller battery is full"; //// break; //// } //// nocontroller_ = false; //// unknown_ = false; // break; // // case BATTERY_TYPE_UNKNOWN: //// batlevel_ = 0; //// nocontroller_ = false; //// unknown_ = true; //// tip = L"Battery level couldn't be read"; // // case BATTERY_TYPE_DISCONNECTED: // default: //// batlevel_ = 0; //// nocontroller_ = true; //// unknown_ = false; //// wired_ = true; //// tip = L"No controller connected"; // break; // } // //// NOTIFYICONDATAW idata = { sizeof(idata) }; //// idata.hWnd = hwnd_; //// idata.uID = icon_id; //// idata.hIcon = MakeIcon(true); //// idata.uFlags = NIF_ICON | NIF_TIP; //// wcscpy_s(idata.szTip, tip); } //---------------------------------------------------------------------------
[ "v-matsk@alleninstitute.org" ]
v-matsk@alleninstitute.org
46237cc0ee730087a6ba53f253b0aa2b37899d7b
6d2170b2e4413bd8a6e64472d679e04a4b7083d9
/Labs/Lab15/Human.h
4c44507ac31f5ef3799d2eea896e3ad8488ecd60
[]
no_license
clbx/CS222
ba817059401a1cc4d4defa3f9a24bbd031ce537e
c9663c9a084f044bf15ba0128cc4e05ad39ddd01
refs/heads/master
2021-03-24T10:01:59.397469
2018-05-08T17:24:21
2018-05-08T17:24:21
118,042,886
1
0
null
null
null
null
UTF-8
C++
false
false
382
h
#ifndef HUMAN_H #define HUMAN_H #include <string> using namespace std; #define HUMAN_DEFAULT_STRENGTH 50 class Human { public: /* Constructors */ Human(void); Human(const string &name, int strength); /* Destructor */ virtual ~Human(void); string getName(); int getStrength(); int hurt(int damage); int makeAttack(); private: int strength; string name; }; #endif
[ "clay@clbx.io" ]
clay@clbx.io
ef63154bf61fa78adb437462a9d3bb69fb950228
42ff9c702e19ecc8f6b6905eb51f2f4832e2ba9f
/src/qt/forms/ui_blockexplorer.h
1d777903bfa67be45ebfdc54d7d332c326b95939
[ "MIT" ]
permissive
jgeofil/stakinglab-coin
1abb409c0bba5c43ce3a58983441a4ae2d619c9f
7f7c70590e85882deef15ad4c26940f24953d385
refs/heads/master
2022-11-05T16:11:01.140229
2020-06-29T18:29:45
2020-06-29T18:29:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,726
h
/******************************************************************************** ** Form generated from reading UI file 'blockexplorer.ui' ** ** Created by: Qt User Interface Compiler version 5.9.7 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_BLOCKEXPLORER_H #define UI_BLOCKEXPLORER_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QStatusBar> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_BlockExplorer { public: QWidget *centralwidget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QPushButton *back; QPushButton *forward; QLineEdit *searchBox; QPushButton *pushSearch; QScrollArea *scrollArea; QWidget *scrollAreaWidgetContents; QHBoxLayout *horizontalLayout_2; QLabel *content; QMenuBar *menubar; QStatusBar *statusbar; void setupUi(QMainWindow *BlockExplorer) { if (BlockExplorer->objectName().isEmpty()) BlockExplorer->setObjectName(QStringLiteral("BlockExplorer")); BlockExplorer->resize(800, 600); BlockExplorer->setStyleSheet(QStringLiteral("")); centralwidget = new QWidget(BlockExplorer); centralwidget->setObjectName(QStringLiteral("centralwidget")); centralwidget->setStyleSheet(QStringLiteral("")); verticalLayout = new QVBoxLayout(centralwidget); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setSizeConstraint(QLayout::SetMinimumSize); back = new QPushButton(centralwidget); back->setObjectName(QStringLiteral("back")); QIcon icon; icon.addFile(QStringLiteral(":/icons/back"), QSize(), QIcon::Normal, QIcon::Off); back->setIcon(icon); back->setFlat(false); horizontalLayout->addWidget(back); forward = new QPushButton(centralwidget); forward->setObjectName(QStringLiteral("forward")); QIcon icon1; icon1.addFile(QStringLiteral(":/icons/forward"), QSize(), QIcon::Normal, QIcon::Off); forward->setIcon(icon1); horizontalLayout->addWidget(forward); searchBox = new QLineEdit(centralwidget); searchBox->setObjectName(QStringLiteral("searchBox")); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(5); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(searchBox->sizePolicy().hasHeightForWidth()); searchBox->setSizePolicy(sizePolicy); searchBox->setMinimumSize(QSize(0, 0)); horizontalLayout->addWidget(searchBox); pushSearch = new QPushButton(centralwidget); pushSearch->setObjectName(QStringLiteral("pushSearch")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Fixed); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(pushSearch->sizePolicy().hasHeightForWidth()); pushSearch->setSizePolicy(sizePolicy1); pushSearch->setMinimumSize(QSize(0, 0)); pushSearch->setMaximumSize(QSize(16777215, 16777215)); pushSearch->setAutoDefault(false); pushSearch->setFlat(false); horizontalLayout->addWidget(pushSearch); verticalLayout->addLayout(horizontalLayout); scrollArea = new QScrollArea(centralwidget); scrollArea->setObjectName(QStringLiteral("scrollArea")); scrollArea->setWidgetResizable(true); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QStringLiteral("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 780, 489)); horizontalLayout_2 = new QHBoxLayout(scrollAreaWidgetContents); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); content = new QLabel(scrollAreaWidgetContents); content->setObjectName(QStringLiteral("content")); QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding); sizePolicy2.setHorizontalStretch(0); sizePolicy2.setVerticalStretch(0); sizePolicy2.setHeightForWidth(content->sizePolicy().hasHeightForWidth()); content->setSizePolicy(sizePolicy2); content->setTextFormat(Qt::RichText); content->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop); content->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse); horizontalLayout_2->addWidget(content); scrollArea->setWidget(scrollAreaWidgetContents); verticalLayout->addWidget(scrollArea); BlockExplorer->setCentralWidget(centralwidget); menubar = new QMenuBar(BlockExplorer); menubar->setObjectName(QStringLiteral("menubar")); menubar->setGeometry(QRect(0, 0, 800, 27)); BlockExplorer->setMenuBar(menubar); statusbar = new QStatusBar(BlockExplorer); statusbar->setObjectName(QStringLiteral("statusbar")); BlockExplorer->setStatusBar(statusbar); retranslateUi(BlockExplorer); pushSearch->setDefault(false); QMetaObject::connectSlotsByName(BlockExplorer); } // setupUi void retranslateUi(QMainWindow *BlockExplorer) { BlockExplorer->setWindowTitle(QApplication::translate("BlockExplorer", "Blockchain Explorer", Q_NULLPTR)); back->setText(QApplication::translate("BlockExplorer", "Back", Q_NULLPTR)); forward->setText(QApplication::translate("BlockExplorer", "Forward", Q_NULLPTR)); searchBox->setInputMask(QString()); searchBox->setText(QString()); searchBox->setPlaceholderText(QApplication::translate("BlockExplorer", "Address / Block / Transaction", Q_NULLPTR)); pushSearch->setText(QApplication::translate("BlockExplorer", "Search", Q_NULLPTR)); content->setText(QApplication::translate("BlockExplorer", "TextLabel", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class BlockExplorer: public Ui_BlockExplorer {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_BLOCKEXPLORER_H
[ "codemaster@stakinglab.io" ]
codemaster@stakinglab.io
451ca51b0dd9909f96ee200d970f046b5cc108c3
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/106/249/CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_67b.cpp
585e6b1d2f8e18d1a1f49ff11e71546844a02018
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,306
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_67b.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml Template File: sources-sink-67b.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: static Data buffer is declared static on the stack * GoodSource: Allocate memory on the heap * Sinks: * BadSink : Print then free data * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_67 { typedef struct _structType { char * structFirst; } structType; #ifndef OMITBAD void badSink(structType myStruct) { char * data = myStruct.structFirst; printLine(data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(structType myStruct) { char * data = myStruct.structFirst; printLine(data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete [] data; } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
7ee5c2c3eb3190fc8546f418ba3294a24989d80a
39b003b15d9cdf42483f43ee59293a935cd26ef1
/RemoteV/RTSA_Remote/RemoteGuiPlugin/RtsaRemoteView/rtsa_dialog_tracesetup.cpp
8f8467538bb3229a44b1cfa659ab53bd99e6c7f9
[]
no_license
hanqianjin/kang
f16fb3835ecd850a3a86bb93f0679c878c82acab
cc40e6be18287a7a3269e50371f2850cd03bfb5d
refs/heads/master
2021-06-25T23:47:54.108574
2020-11-20T02:46:25
2020-11-20T02:46:25
142,751,390
1
0
null
null
null
null
UTF-8
C++
false
false
12,497
cpp
#include "rtsa_dialog_tracesetup.h" #include "ui_rtsa_dialog_tracesetup.h" #include <QListView> RtSa_Dialog_TraceSetup::RtSa_Dialog_TraceSetup(Rtsa_Remote_Interface *RtsaRemoteInterface,RtSa_Dialog_Digitinput *Input, QWidget *parent) : QWidget(parent), ui(new Ui::RtSa_Dialog_TraceSetup), RemoteInterfaceObj(RtsaRemoteInterface), mInputDialog(Input), mUpDownFlag(0) { ui->setupUi(this); setWindowFlags(Qt::FramelessWindowHint); // this->setAttribute(Qt::WA_NoChildEventsForParent,true); ui->pb_Detector->setView(new QListView()); ui->pb_TraceType->setView(new QListView()); //Albert 03/05 for insert Vertical scroll bar ui->pb_Detector->setEditable(false); // this->setAttribute(Qt::WA_DeleteOnClose); this->hide(); mCurSelTraceIndex = RemoteInterfaceObj->getCurTrace(); InitDisplay(); connect(RemoteInterfaceObj,SIGNAL(BitViewChanged(quint32)),this,SLOT(on_Update())); connect(mInputDialog,SIGNAL(finishEntry(qint32)),this,SLOT(finishEntry_trace(qint32))); connect(mInputDialog,SIGNAL(ClockWiseDown(QKeyEvent*)),this,SLOT(DigitalKeyRespond(QKeyEvent*))); timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(on_timeOut())); setProperty("status",rtsa_qssMode[RemoteInterfaceObj->GetDisplayMode()]); } RtSa_Dialog_TraceSetup::~RtSa_Dialog_TraceSetup() { // delete mTraceTypeGroup; delete ui; } void RtSa_Dialog_TraceSetup::keyPressEvent(QKeyEvent *event) { qint32 keyvalue = event->key(); if(event->key() == Qt::Key_PowerOff) { if(!event->isAutoRepeat()) { QApplication::sendEvent(this->parent(),event); } return; } // qint32 curTrace = RemoteInterfaceObj->getCurTrace(); switch (keyvalue) { case Qt::Key_Escape: if(!mInputDialog->isHidden()) { mInputDialog->hide(); return; } this->close(); break; case Qt::Key_Shift: RemoteInterfaceObj->setShiftKeyEnable(true); if(!mInputDialog->isHidden()) { mInputDialog->hide(); } this->close(); break; case Qt::Key_0: case Qt::Key_1: case Qt::Key_2: case Qt::Key_3: case Qt::Key_4: case Qt::Key_5: case Qt::Key_6: case Qt::Key_7: case Qt::Key_8: case Qt::Key_9: case Qt::Key_Period: case Qt::Key_Minus: // - Minus // case Qt::Key_F2: // +/- case Qt::Key_F6://key_left case Qt::Key_Right: case Qt::Key_F7: if(mInputDialog->isHidden()) { showInputDialog(RTSA_INPUT_AVERAGE_COUNT); mInputDialog->clearEdit(); } mInputDialog->keyresponse(keyvalue); break; case Qt::Key_F3: case Qt::Key_Up: case Qt::Key_F8: mUpDownFlag = 0; if(timer->isActive()) { } else { timer->start(100); } break; case Qt::Key_Down: case Qt::Key_F9: case Qt::Key_F4: mUpDownFlag = 1; if(timer->isActive()) { } else { timer->start(100); } break; } return; } void RtSa_Dialog_TraceSetup::InitDisplay() { InitTraceOnOff(); InitTraceType(); InitDector(); InitCurTrace(); refreshInfo(); return; } void RtSa_Dialog_TraceSetup::InitTraceOnOff() { mTraceOnOffGroup[RTSA_TR1] = ui->pb_TR1; mTraceOnOffGroup[RTSA_TR2] = ui->pb_TR2; mTraceOnOffGroup[RTSA_TR3] = ui->pb_TR3; mTraceOnOffGroup[RTSA_TR4] = ui->pb_TR4; mTraceOnOffGroup[RTSA_TR5] = ui->pb_TR5; mTraceOnOffGroup[RTSA_TR6] = ui->pb_TR6; return; } void RtSa_Dialog_TraceSetup::InitTraceType() { // mTraceTypeGroup = new QButtonGroup; // mTraceTypeGroup->addButton(ui->pb_Off,RTSA_TRACE_OFF); // mTraceTypeGroup->addButton(ui->pb_ClearWrite,RTSA_CLEAR_WRITE); // mTraceTypeGroup->addButton(ui->pb_MaxHold,RTSA_MAX_HOLD); // mTraceTypeGroup->addButton(ui->pb_MinHold,RTSA_MIN_HOLD); // mTraceTypeGroup->addButton(ui->pb_View,RTSA_VIEW); // connect(mTraceTypeGroup,SIGNAL(buttonClicked(int)),this,SLOT(on_pb_TraceType_currentIndexChanged(qint32))); // mTraceTypeGroup->button(mControl->getTraceType(mControl->getCurTrace()))->setChecked(true); return; } void RtSa_Dialog_TraceSetup::InitDector() { ui->pb_Detector->setCurrentIndex(RemoteInterfaceObj->getDectorType()); connect(ui->pb_Detector,SIGNAL(currentIndexChanged(qint32)),this,SLOT(TraceDec_Change(qint32))); return; } void RtSa_Dialog_TraceSetup::InitCurTrace() { mTraceSelectGroup = new QButtonGroup(); mTraceSelectGroup->addButton(ui->pb_TR1,RTSA_TR1); mTraceSelectGroup->addButton(ui->pb_TR2,RTSA_TR2); mTraceSelectGroup->addButton(ui->pb_TR3,RTSA_TR3); mTraceSelectGroup->addButton(ui->pb_TR4,RTSA_TR4); mTraceSelectGroup->addButton(ui->pb_TR5,RTSA_TR5); mTraceSelectGroup->addButton(ui->pb_TR6,RTSA_TR6); // mTraceSelectGroup->addButton(ui->pb_allon,RTSA_TRACE_ALL); connect(mTraceSelectGroup,SIGNAL(buttonClicked(qint32)),this,SLOT(TraceSelect_Change(qint32))); mTraceSelectGroup->button(RemoteInterfaceObj->getCurTrace())->setChecked(true); return; } void RtSa_Dialog_TraceSetup::on_pb_cancel_clicked() { this->close(); return; } //void RtSa_Dialog_TraceSetup::on_pb_allon_clicked() //{ // for(qint32 i = 0; i < RTSA_NUM_TRACE; i++) // { // if(mControl->getTraceType(i) == RTSA_TRACE_OFF) // { // mControl->setTraceType(i,RTSA_CLEAR_WRITE); // } // } // ui->pb_allon->setChecked(true); // ui->pb_clearall->setChecked(false); // mTraceTypeGroup->button(mControl->getTraceType(mControl->getCurTrace()))->setChecked(true); // on_Update(); // return; //} //void RtSa_Dialog_TraceSetup::on_pb_clearall_clicked() //{ // for(qint32 i = 0; i < RTSA_NUM_TRACE; i++) // { // mControl->setTraceType(i,RTSA_TRACE_OFF); // } // ui->pb_allon->setChecked(false); //// mTraceTypeGroup->button(RTSA_TRACE_OFF)->setChecked(true); // on_Update(); // return; //} void RtSa_Dialog_TraceSetup::refreshInfo() { // qint32 nCurTrace = RemoteInterfaceObj->getCurTrace(); qint32 nCurTraceType = RemoteInterfaceObj->getTraceType(mCurSelTraceIndex); // bool nIsAvgOn = RemoteInterfaceObj->IsAvgOn(mCurSelTraceIndex); qint32 nAvgNum = RemoteInterfaceObj->getAvgNum(mCurSelTraceIndex); ui->averageEdit->setText(QString::number(nAvgNum)); if(nCurTraceType != RTSA_TRACE_OFF) { ui->pb_toggle->setChecked(true); } else { ui->pb_toggle->setChecked(false); } if(nCurTraceType <= RTSA_CLEAR_WRITE) { ui->pb_TraceType->setCurrentIndex(0); } else { ui->pb_TraceType->setCurrentIndex(nCurTraceType - 1); } return; } void RtSa_Dialog_TraceSetup::on_Update() { refreshInfo(); // ui->pb_TraceType->setCurrentIndex(nCurTraceType + 1); // mTraceTypeGroup->button(nCurTraceType)->setChecked(true); return; } //void RtSa_Dialog_TraceSetup::TraceType_Change(qint32 index) //{ // mControl->setTraceType(mControl->getCurTrace(),index); // on_Update(); // return; //} void RtSa_Dialog_TraceSetup::TraceDec_Change(qint32 index) { RemoteInterfaceObj->setDectorType(index); return; } void RtSa_Dialog_TraceSetup::TraceSelect_Change(qint32 index) { mCurSelTraceIndex = index; if(RemoteInterfaceObj->getTraceType(mCurSelTraceIndex) != RTSA_TRACE_OFF) { RemoteInterfaceObj->setCurTrace(mCurSelTraceIndex); } // if(index != RTSA_TRACE_ALL) // { // mControl->setCurTrace(index); // } // ui->TraceTypeBar->setTitle(QString("Current Trace: T%1").arg(QString::number(index+1))); // ui->pb_allon->setChecked(false); refreshInfo(); return; } void RtSa_Dialog_TraceSetup::on_pb_TraceType_currentIndexChanged(int index) { if(RemoteInterfaceObj->getTraceType(mCurSelTraceIndex) == RTSA_TRACE_OFF) return; // mControl->setCurTrace(mCurSelTraceIndex); qint32 nCurTrace = RemoteInterfaceObj->getCurTrace(); qint32 nCurTraceType = RemoteInterfaceObj->getTraceType(nCurTrace); if(nCurTraceType == (index + 1)) { return; } RemoteInterfaceObj->setTraceType(RemoteInterfaceObj->getCurTrace(),index + 1); // if(nCurTraceType != RTSA_TRACE_OFF) // { // ui->pb_toggle->setChecked(true); // } // else // { // ui->pb_toggle->setChecked(false); // } // on_Update(); return; } void RtSa_Dialog_TraceSetup::on_pb_toggle_toggled(bool checked) { qint32 traceType = 0; // qint32 traceID = 0; // if(ui->pb_allon->isChecked()) // { // for(qint32 i = 0; i < RTSA_NUM_TRACE; i++) // { // if(checked) // { // ui->pb_toggle->setText("On"); // traceType = mControl->getTraceType(i); // if(traceType == RTSA_TRACE_OFF) // { // mControl->setTraceType(i,RTSA_CLEAR_WRITE); // } // } // else // { // ui->pb_toggle->setText("Off"); // mControl->setTraceType(i,RTSA_TRACE_OFF); // } // } // } // else // { // traceID = mControl->getCurTrace(); // traceType = mControl->getTraceType(mCurSelTraceIndex); if(checked) { RemoteInterfaceObj->setCurTrace(mCurSelTraceIndex); traceType = RemoteInterfaceObj->getTraceType(mCurSelTraceIndex); ui->pb_toggle->setText("On"); if(traceType == RTSA_TRACE_OFF) { RemoteInterfaceObj->setTraceType(mCurSelTraceIndex,RTSA_CLEAR_WRITE); } } else { ui->pb_toggle->setText("Off"); RemoteInterfaceObj->setTraceType(mCurSelTraceIndex,RTSA_TRACE_OFF); } // } refreshInfo(); return; } void RtSa_Dialog_TraceSetup::finishEntry_trace(qint32 index) { qint32 nAvgNum = RemoteInterfaceObj->getAvgNum(RemoteInterfaceObj->getCurTrace()); ui->averageEdit->setText(QString::number(nAvgNum)); return; } void RtSa_Dialog_TraceSetup::DigitalKeyRespond(QKeyEvent *event) { keyPressEvent(event); return; } void RtSa_Dialog_TraceSetup::showInputDialog(qint32 index) { if(mInputDialog->isHidden()) { mInputDialog->setGeometry(mapToGlobal(QPoint(0,0)).x()/*+this->width()*//*-RTSA_DIGITAL_DIALOG_WIDTH*/,\ mapToGlobal(QPoint(0,0)).y(),RTSA_DIGITAL_DIALOG_WIDTH,RTSA_DIGITAL_DIALOG_HEIGHT); } mInputDialog->initDisplay(index); mInputDialog->setProperty("status", rtsa_qssMode[RemoteInterfaceObj->GetDisplayMode()]); mInputDialog->setStyle(QApplication::style()); if(mInputDialog->isHidden()) mInputDialog->show(); return; } void RtSa_Dialog_TraceSetup::on_averageEdit_clicked() { showInputDialog(RTSA_INPUT_AVERAGE_COUNT); return; } void RtSa_Dialog_TraceSetup::on_pb_traceAllOn_clicked() { qint32 traceType; for(qint32 i = 0; i < RTSA_NUM_TRACE; i++) { ui->pb_toggle->setChecked(true); ui->pb_toggle->setText("On"); traceType = RemoteInterfaceObj->getTraceType(i); if(traceType == RTSA_TRACE_OFF) { RemoteInterfaceObj->setTraceType(i,RTSA_CLEAR_WRITE); } } return; } void RtSa_Dialog_TraceSetup::on_pb_clearall_clicked() { RtSa_Dialog_Warning message("Notice","Are you sure to clear all traces?",this,RemoteInterfaceObj->GetDisplayMode()); message.setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::FramelessWindowHint); if(message.exec() != QDialog::Accepted) { return; } for(qint32 i = 0; i < RTSA_NUM_TRACE; i++) { RemoteInterfaceObj->setTraceType(i,RTSA_TRACE_OFF); } refreshInfo(); return; } /** * @brief * @param * @Author Albert * @date 2019-07-30 */ void RtSa_Dialog_TraceSetup::on_timeOut() { timer->stop(); qint32 curTrace = RemoteInterfaceObj->getCurTrace(); if(!mInputDialog->isHidden()) { mInputDialog->hide(); } if(!mUpDownFlag) { RemoteInterfaceObj->setAvgNum(curTrace,RemoteInterfaceObj->getAvgNum(curTrace) + 1); refreshInfo(); } else { RemoteInterfaceObj->setAvgNum(curTrace,RemoteInterfaceObj->getAvgNum(curTrace) - 1); refreshInfo(); } return; }
[ "41859296+hanqianjin@users.noreply.github.com" ]
41859296+hanqianjin@users.noreply.github.com
2662098b2e6afc92996323f9aaf720bc69c5d345
10d33b9b5af6883568b293d0a81a79f3f422998f
/C++/模板方法模式/模板方法模式/main.cpp
8facd560d5060081f2d5552607f35a6faed54ec3
[]
no_license
wovert/CTutorials
25d4f713e3be760838ce31c518413f4009b0f224
a897587f111490d63b1c901ee4beab98c9a0b4bf
refs/heads/master
2023-05-25T22:09:59.046479
2023-05-15T01:57:28
2023-05-15T01:57:28
127,814,474
6
3
null
null
null
null
UTF-8
C++
false
false
1,566
cpp
#include <iostream> using namespace std; class Drink { public: Drink() { cout << "Drink 构造函数" << endl; } ~Drink() { cout << "Drink 析构函数" << endl; } virtual void Boil() = 0; // 煮水 virtual void Brew() = 0; // 冲泡 virtual void PourInCup() = 0; // 导入杯中 virtual void AddSonm() = 0; // 加点辅料 // 模板方法 void func() { Boil(); Brew(); PourInCup(); AddSonm(); } }; class Coffee : public Drink { public: virtual void Boil() { cout << "煮点热水" << endl; } virtual void Brew() { cout << "拿铁" << endl; } virtual void PourInCup() { cout << "倒入咖啡杯中" << endl; } virtual void AddSonm() { cout << "加点糖" << endl; } Coffee() { cout << "Coffee 构造函数" << endl; pName = new char[64]; memset(pName, 0, 64); strcpy_s(pName, 64, "咖啡"); } ~Coffee() { cout << "Coffee 析构函数" << endl; if (this->pName != NULL) { delete[] pName; pName = NULL; } } public: char *pName; }; class Tea : public Drink { public: virtual void Boil() { cout << "煮点自来水" << endl; } virtual void Brew() { cout << "铁观音" << endl; } virtual void PourInCup() { cout << "倒入茶杯中" << endl; } virtual void AddSonm() { cout << "不加任何..." << endl; } public: char *pName; }; void demo01() { Drink *d = NULL; d = new Coffee; d->func(); d = new Tea; d->func(); delete d; d = NULL; } void demo02() { Drink *d = new Coffee; delete d; // 缺少子类的析构函数 } int main() { //demo01(); demo02(); return 0; }
[ "wovert@126.com" ]
wovert@126.com
d6620ef1ca64729d1429e367ebc09540890c458d
7bb0e220876aa343b93d264f74059a5582c42581
/assignment2/referee.h
db3fc2ca7c42b61a2c2f247bc2a7f37a2bfa0b6f
[]
no_license
hansenAdds/Algorithm-Design-and-Data-Structures
84b04f28e70ef1234d56bb7fe5dc2c484f8145c7
5611ad4bbad1fff836078bf1e0ca377108be6d9b
refs/heads/master
2022-12-06T06:13:29.378372
2020-08-04T01:11:48
2020-08-04T01:11:48
271,754,846
0
0
null
null
null
null
UTF-8
C++
false
false
249
h
#ifndef referee_H #define referee_H #include "human.h" #include "computer.h" #include <string> class referee{ std::string u; public: referee(); referee(std::string uu); std::string compare(std::string n1,std::string n2); ~referee(); }; #endif
[ "noreply@github.com" ]
hansenAdds.noreply@github.com
0c10d98624197482363eb049f7d2526cb4aa2887
2672edf16ce85ddaa63e9b2b2fc3d3eededa0736
/driver/driver/MAIN.cpp
22622430c0d545a59a5664d03df4cd417edbcec9
[]
no_license
2103962345/driver
75d0e2546b2286c011289ce565413326698bb688
86aa327229a6cc6d6cc702b1ac5f7a41b2cab809
refs/heads/master
2020-03-22T19:40:52.414038
2018-07-11T08:27:31
2018-07-11T08:27:31
140,543,691
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
11,811
cpp
//Использование классов #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <string> #include <Windows.h> #include <iomanip> using namespace std; #include "Auto.hpp" #include "Person.hpp" #include "Driver.hpp" #include "B.hpp" #include "BE.hpp" #include "B1.hpp" #include "LicenseTag.hpp" //Прототипы функций void ab_pro(); void ab_au(); void change(); void comp_age(); void cr_base(); void create_obj(); void create_sys(); void FIO(); void help(); void getin(); void main_menu(); void menu_help(); void menu_obj(); void menu_sys(); void LoadCaption(int k); void op_man(); void over_sta(); void show_sys(); void sset(); void read_f(); void view(); void write_f(); void zastavka(); // Строка сообщения char any_key[]="Press any key to continue..."; char ex[]="Press Esc to exit"; const int CCAPT=50; const int LCAPT=50; int k; char mas_cap[CCAPT][LCAPT]; int lang = 0; int reply; // Объекты Person person; Driver driver; Auto aut; B b; // Главный кадр интерфейса void zastavka() { system("cls"); cout <<endl; LoadCaption(1); reply=_getch(); if(reply==109){ system("cls"); main_menu();} else if(reply==108){if(lang)lang=0; else lang=1;} system("cls"); zastavka(); } // Главное меню void main_menu() { LoadCaption(3); cout << endl; reply=_getch(); switch(reply) { case 49: zastavka(); break; case 50: view(); break; case 51: menu_help(); break; case 52:case 101:case 27: exit(-1); break; case 108: if(lang)lang=0; else lang=1; LoadCaption(3); main_menu();break; default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); main_menu(); } cout << any_key << endl; getch(); } // Меню помощи void menu_help() { system("cls"); cout <<endl; LoadCaption(4); cout << endl; reply=_getch(); switch(reply) { case 49: help(); break; //1 условие case 50: ab_pro(); break; //2 о программе case 51: ab_au(); break; //3 об авторе case 52: op_man(); break; //4 перегрузка оператора case 109: case 27: system("cls"); main_menu(); break;//m меню case 108: if(lang)lang=0; else lang=1; LoadCaption(4); menu_help();break; // l смена языка default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); menu_help(); } cout << any_key << endl; getch(); } //показ файл условия void help() { system("cls"); cout <<endl; LoadCaption(2); cout << endl; reply=_getch(); if(reply==109||reply==8){ system("cls"); menu_help();} else if(reply==108){if(lang)lang=0; else lang=1;} system("cls"); help(); } //показ файла о программе void ab_pro() { system("cls"); cout <<endl; LoadCaption(5); cout << endl; reply=_getch(); if(reply==109||reply==8){ system("cls"); menu_help();} else if(reply==108){if(lang)lang=0; else lang=1;} system("cls"); ab_pro(); } //показ файла об авторе void ab_au() { system("cls"); cout <<endl; LoadCaption(6); cout << endl; reply=_getch(); if(reply==109||reply==8){ system("cls"); menu_help();} else if(reply==108){if(lang)lang=0; else lang=1;} system("cls"); ab_au(); } //показ файла перегрузка операторов void op_man() { system("cls"); cout <<endl; LoadCaption(7); cout << endl; reply=_getch(); if(reply==109||reply==8){ system("cls"); menu_help();} else if(reply==108){if(lang)lang=0; else lang=1;} system("cls"); op_man(); } //смена языка void LoadCaption(int k) {char nfile[16], * nfile_r, * nfile_a; string line; if(k==1) {nfile_a="condition_a.txt"; nfile_r="condition_r.txt";} if(k==2) {nfile_a="caption_a.txt"; nfile_r="caption_r.txt";} if(k==3) {nfile_a="menu_a.txt"; nfile_r="menu_r.txt";} if(k==4) {nfile_a="menu_h_a.txt"; nfile_r="menu_h_r.txt";} if(k==5) {nfile_a="abpro_a.txt"; nfile_r="abpro_r.txt";} if(k==6) {nfile_a="abau_a.txt"; nfile_r="abau_r.txt";} if(k==7) {nfile_a="opm_a.txt"; nfile_r="opm_r.txt";} if(k==8) {nfile_a="result_a.txt"; nfile_r="result_r.txt";} if(k==9) {nfile_a="menu_obj_a.txt"; nfile_r="menu_obj_r.txt";} if(k==10) {nfile_a="view_a.txt"; // menu system nfile_r="view_r.txt";} if(k==11) {nfile_a="menu_sys_a.txt"; // menu driver nfile_r="menu_sys_r.txt";} if(lang) strcpy(nfile, nfile_r); else strcpy(nfile, nfile_a); ifstream fcapt; fcapt.open(nfile); if(fcapt.fail()) { cerr<<"File "<<nfile<<"isn`t open"<<endl; getch(); exit(-1); } system("cls"); while ( getline (fcapt,line) ) { cout << line << '\n'; } } // Меню void view() { LoadCaption(10); cout << endl; cout << ex << endl; reply=_getch(); switch(reply) { case 49: menu_sys(); break;//1 Меню Пользователя case 50: menu_obj(); break;//2 Меню объектов case 51: write_f(); cout<<endl<<"Done"; view(); break;//3 Запись в файл case 52:system("cls"); read_f(); view(); break;//4 Чтение из файла case 53: case 27: case 109: main_menu();//5 case 108: if(lang)lang=0; else lang=1; LoadCaption(10); view();break;//l default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); view(); } cout << any_key << endl; getch(); reply=_getch(); if(reply==109||reply==8){ system("cls"); main_menu(); } } //Меню Пользователя void menu_sys() { LoadCaption(11); cout << endl; cout << ex << endl; reply=_getch(); switch(reply) { case 49: create_sys(); break;//1 Создать объекты case 50: show_sys();menu_sys(); break;//2 Показать систему case 51: write_f(); cout<<endl<<"Done"; menu_sys(); break;//3 Записать в файл case 52: system("cls");read_f(); menu_sys(); break;//4 Прочитать файл case 53: case 27: case 109: view();//5 case 108: if(lang)lang=0; else lang=1; LoadCaption(11); menu_sys();break; default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); menu_sys(); } cout << any_key << endl; getch(); reply=_getch(); if(reply==109||reply==8){ system("cls"); view();} } //создать все объекты void create_sys(){ system("cls"); cout << "Do you have lisence tag?(Press y for yes) : " << endl; reply=_getch(); if (reply=='y') {driver.Add();} else{ person.Add();} cout << "For repeat enter write y" << endl; reply=_getch(); if (reply=='y') { create_sys();} else menu_sys(); } //показать объекты void show_sys() {system("cls"); person.Display(); driver.Display(); cout << any_key << endl; getch(); } //меню объектов void menu_obj() { LoadCaption(9); cout << endl; cout << ex << endl; reply=_getch(); switch(reply) { case 49: create_obj(); break;//1 case 50: show_sys(); menu_obj(); break;//2 показать какой-то один объект case 51: case 27: case 109: view();//5 case 108: if(lang)lang=0; else lang=1; LoadCaption(9); menu_obj();break; default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); menu_obj(); } cout << any_key << endl; getch(); reply=_getch(); if(reply==109||reply==8){ system("cls"); main_menu();} } //вызов перегрузки операторов void create_obj() { cr_base(); } // функции для работы с объектами void cr_base() { system("cls"); cout<<"1.Overload Stage(++)(Увеличить стаж(++))"<<endl; cout<<"2.Compare ages(<)(Сравнить возрасты(<))"<<endl; cout<<"3.Middle Age(Средний возраст)"<<endl; cout<<"4.FIO(Ф.И.О.)"<<endl; cout<<"5.Get driver info(получить информацию о водителе)"<<endl; cout<<"6.Change person(Изменить данные человека)"<<endl; cout<<"7.Set code(Установить код)"<<endl; cout<<"8.Exit(Выход)"<<endl; reply=_getch(); switch(reply) { case 49: over_sta(); break;//1 увеличить стаж case 50: comp_age(); break;//2 сравнить возрасты case 51: person.MidAge(); break; //3 средний возраст case 52: FIO();break; //4 фио case 53: getin();break;//5 info driver case 54: change();break;//6 изменить человека case 55: sset();break;//7 установить код case 56:case 27: case 109:system("cls");menu_obj();//8 default: cerr<<"You are mistaken. Press any "<< " key and then type the option "<< " number." <<endl; getch(); system("cls"); menu_obj(); } cout << any_key << endl; getch(); reply=_getch(); if(reply==109||reply==8){ system("cls"); main_menu();} } //записать в файл void write_f() { person.write(); driver.write(); } //чтение из файла void read_f() { person.read(); cout << any_key << endl; getch(); } //получить инфо водителя void getin() {int nn; nn=driver.Ret(); if(nn==0)cout<<"Error"<<endl; else{ int n; do{ cout<<"\nEnter number driver: "; cout<<"\nВведите номер водителя: "; cin>>n; }while(n<=0||n>nn); driver.GetAr1(n-1); cout<<endl;} } //изменить инфо человека void change() { int n,nn; nn=person.Ret(); if(nn==0)cout<<"Error"<<endl; else { do{ cout<<"\nEnter number person: "; cout<<"\nВведите номер человека: "; cin>>n; } while(n<=0||n>nn); person.oper(n-1); } cout<<endl; } //установить код void sset() { int nn; nn=driver.Ret(); if(nn==0)cout<<"Error"<<endl; else{ int n; do{ cout<<"\nEnter number driver: "; cout<<"\nВведите номер водителя: "; cin>>n; }while(n<=0||n>nn); driver.sset1(n-1); cout<<endl;} } //вывод Ф.И.О человека void FIO(){ int n,nn; nn=person.Ret(); if(nn==0)cout<<"Error"<<endl; else { do{ cout<<"\nEnter number person: "; cout<<"\nВведите номер человека: "; cin>>n; } while(n<=0||n>nn); person.GetAr(n-1); } cout<<endl; } //сравнить возрасты void comp_age() { int nn; nn=person.Ret(); if(nn==0||nn==1)cout<<"Error"<<endl; else { int n; int k; do{ cout<<"\nEnter number person 1: "; cout<<"\nВведите номер 1 человека: "; cin>>n; }while(n>nn||n<=0); do{ cout<<"\nEnter number person 2:"; cout<<"\nВведите номер 2 человека: "; cin>>k; }while(k>nn||k<=0||n==k); person.GetAr2(n-1,k-1); cout<<endl;} } //увеличить стаж void over_sta() { int nn; nn=driver.Ret(); if(nn==0)cout<<"Error"<<endl; else{ int n; do{ cout<<"\nEnter number driver: "; cout<<"\nВведите номер водителя: "; cin>>n; }while(n<=0||n>nn); driver.GetAr(n-1); cout<<endl;} } // главная функция int main() { driver.File(); person.File(); SetConsoleCP(1251);// установка кодовой страницы win-cp 1251 в поток ввода SetConsoleOutputCP(1251); // установка кодовой страницы win-cp 1251 в поток вывода system("cls"); zastavka(); return 0; }
[ "noreply@github.com" ]
2103962345.noreply@github.com
ebd6a113e872728f9c0afa90a31c2f55f055967c
1d9df1156e49f768ed2633641075f4c307d24ad2
/third_party/WebKit/Source/modules/webgl/WebGLRenderingContext.h
ecfc3a6c504b81c48daab5105e0921d71a7a6830
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
GSIL-Monitor/platform.framework.web.chromium-efl
8056d94301c67a8524f6106482087fd683c889ce
e156100b0c5cfc84c19de612dbdb0987cddf8867
refs/heads/master
2022-10-26T00:23:44.061873
2018-10-30T03:41:51
2018-10-30T03:41:51
161,171,104
0
1
BSD-3-Clause
2022-10-20T23:50:20
2018-12-10T12:24:06
C++
UTF-8
C++
false
false
5,574
h
/* * Copyright (C) 2009 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 WebGLRenderingContext_h #define WebGLRenderingContext_h #include "core/html/canvas/CanvasRenderingContextFactory.h" #include "modules/webgl/WebGLRenderingContextBase.h" #include <memory> namespace blink { class ANGLEInstancedArrays; class CanvasContextCreationAttributes; class EXTBlendMinMax; class EXTColorBufferHalfFloat; class EXTFragDepth; class EXTShaderTextureLOD; class EXTsRGB; class EXTTextureFilterAnisotropic; class OESElementIndexUint; class OESStandardDerivatives; class OESTextureFloat; class OESTextureFloatLinear; class OESTextureHalfFloat; class OESTextureHalfFloatLinear; class WebGLColorBufferFloat; class WebGLDebugRendererInfo; class WebGLDepthTexture; class WebGLLoseContext; class WebGLRenderingContext final : public WebGLRenderingContextBase { DEFINE_WRAPPERTYPEINFO(); public: class Factory : public CanvasRenderingContextFactory { WTF_MAKE_NONCOPYABLE(Factory); public: Factory() {} ~Factory() override {} CanvasRenderingContext* Create( CanvasRenderingContextHost*, const CanvasContextCreationAttributes&) override; CanvasRenderingContext::ContextType GetContextType() const override { return CanvasRenderingContext::kContextWebgl; } void OnError(HTMLCanvasElement*, const String& error) override; }; CanvasRenderingContext::ContextType GetContextType() const override { return CanvasRenderingContext::kContextWebgl; } ImageBitmap* TransferToImageBitmap(ScriptState*) final; String ContextName() const override { return "WebGLRenderingContext"; } void RegisterContextExtensions() override; void SetCanvasGetContextResult(RenderingContext&) final; void SetOffscreenCanvasGetContextResult(OffscreenRenderingContext&) final; DECLARE_VIRTUAL_TRACE(); DECLARE_VIRTUAL_TRACE_WRAPPERS(); private: WebGLRenderingContext(CanvasRenderingContextHost*, std::unique_ptr<WebGraphicsContext3DProvider>, const CanvasContextCreationAttributes&); // Enabled extension objects. Member<ANGLEInstancedArrays> angle_instanced_arrays_; Member<EXTBlendMinMax> ext_blend_min_max_; Member<EXTColorBufferHalfFloat> ext_color_buffer_half_float_; Member<EXTDisjointTimerQuery> ext_disjoint_timer_query_; Member<EXTFragDepth> ext_frag_depth_; Member<EXTShaderTextureLOD> ext_shader_texture_lod_; Member<EXTTextureFilterAnisotropic> ext_texture_filter_anisotropic_; Member<EXTsRGB> exts_rgb_; #if defined(TIZEN_TBM_SUPPORT) && defined(OS_TIZEN_TV_PRODUCT) Member<OESEglImageExternal> oes_egl_external_; #endif Member<OESElementIndexUint> oes_element_index_uint_; Member<OESStandardDerivatives> oes_standard_derivatives_; Member<OESTextureFloat> oes_texture_float_; Member<OESTextureFloatLinear> oes_texture_float_linear_; Member<OESTextureHalfFloat> oes_texture_half_float_; Member<OESTextureHalfFloatLinear> oes_texture_half_float_linear_; Member<OESVertexArrayObject> oes_vertex_array_object_; Member<WebGLColorBufferFloat> webgl_color_buffer_float_; Member<WebGLCompressedTextureASTC> webgl_compressed_texture_astc_; Member<WebGLCompressedTextureATC> webgl_compressed_texture_atc_; Member<WebGLCompressedTextureETC> webgl_compressed_texture_etc_; Member<WebGLCompressedTextureETC1> webgl_compressed_texture_etc1_; Member<WebGLCompressedTexturePVRTC> webgl_compressed_texture_pvrtc_; Member<WebGLCompressedTextureS3TC> webgl_compressed_texture_s3tc_; Member<WebGLCompressedTextureS3TCsRGB> webgl_compressed_texture_s3tc_srgb_; Member<WebGLDebugRendererInfo> webgl_debug_renderer_info_; Member<WebGLDebugShaders> webgl_debug_shaders_; Member<WebGLDepthTexture> webgl_depth_texture_; Member<WebGLDrawBuffers> webgl_draw_buffers_; Member<WebGLLoseContext> webgl_lose_context_; }; DEFINE_TYPE_CASTS(WebGLRenderingContext, CanvasRenderingContext, context, context->Is3d() && WebGLRenderingContextBase::GetWebGLVersion(context) == 1, context.Is3d() && WebGLRenderingContextBase::GetWebGLVersion(&context) == 1); } // namespace blink #endif // WebGLRenderingContext_h
[ "RetZero@desktop" ]
RetZero@desktop
4231304aeae6bf605711ad4033a49cd729a5a46a
52a547a4e848896b88a3d466030439893d7ae69a
/ranges.hpp
259dc039e7e97b4d2ba541a32ccb6f0d4e3e10b3
[ "MIT" ]
permissive
ralphtandetzky/cpp_utils
b65ffb046332553aab0b4a601431c46cb8d360a2
3adfed125db6fccd7478385544b96ceecdf435e7
refs/heads/master
2018-12-06T06:42:47.783623
2018-10-30T18:05:31
2018-10-30T18:05:31
12,114,277
4
1
null
null
null
null
UTF-8
C++
false
false
4,856
hpp
#pragma once #include "c++17_features.hpp" #include "meta_programming.hpp" #include "rank.hpp" #include <algorithm> #include <cassert> namespace cu { /********************** * Generic put method * **********************/ namespace detail { template <typename OutputRange, typename Value> auto put_impl( OutputRange && out, Value && val, cu::Rank<1> ) -> decltype(out.put(std::forward<Value>(val))) { return out.put(std::forward<Value>(val)); } template <typename OutputRange, typename Value> auto put_impl( OutputRange && out, Value && val, cu::Rank<0> ) -> decltype(static_cast<void>(out.front()=std::forward<Value>(val)), out.pop_front()) { return static_cast<void>(out.front()=std::forward<Value>(val)), out.pop_front(); } } // namespace detail template <typename OutputRange, typename Value> decltype(auto) put( OutputRange out, Value && val ) { return detail::put_impl( std::move(out), std::forward<Value>(val), cu::Rank<1>() ); } /*************************** * Range factory functions * ***************************/ namespace detail { template <typename Iter1, typename Iter2> class IteratorRange { public: IteratorRange( Iter1 && first_, Iter2 && last_ ) : first( std::move(first_) ) , last ( std::move(last_ ) ) {} auto begin() const { return first; } auto end () const { return last; } bool empty() const { return first == last; } void pop_front() { assert( !empty() ); ++first; } decltype(auto) front() const { return *first; } private: Iter1 first; Iter2 last; }; } // namespace detail template <typename Iter1, typename Iter2> auto makeIteratorRange( Iter1 first, Iter2 last ) { return detail::IteratorRange<Iter1,Iter2>( std::move(first), std::move(last) ); } template <typename Container> auto makeRange( Container && container ) { using std::begin; using std::end; return makeIteratorRange( begin(container), end(container) ); } namespace detail { template <typename Container> class PushBackRange { public: PushBackRange( Container & container_ ) : container( container_ ) {} template <typename Value> void put( Value && val ) const { container.push_back( std::forward<Value>(val) ); } private: Container & container; }; } // namespace detail template <typename Container> auto makePushBackRange( Container && container ) { return detail::PushBackRange<Container>( container ); } /******************** * Range algorithms * ********************/ template <typename InputRange, typename F> void for_each( InputRange range, F && f ) { for ( ; !range.empty(); range.pop_front() ) f( range.front() ); } template <typename InputRange, typename OutputRange> void copy( InputRange in, OutputRange out ) { for ( ; !in.empty(); in.pop_front() ) put( out, in.front() ); } template <typename RandomAccessRange> void sort( RandomAccessRange range ) { ::std::sort( range.begin(), range.end() ); } /****************** * Range adapters * ******************/ namespace detail { template <template <typename...> class AdaptedRange, typename ...Ts> class RangeAdapter { private: std::tuple<Ts...> data; public: template <typename ...Args> RangeAdapter( Ts &&... args ) : data( std::forward<Ts>(args)... ) {} template <typename OrigRange> friend AdaptedRange<OrigRange,Ts...> operator|( OrigRange orig, RangeAdapter adapter ) { const auto f = [&orig]( auto &&...args ) { return AdaptedRange<OrigRange,Ts...>( std::move(orig), std::move(args)... ); }; return cu::apply( f, adapter.data ); } }; } // namespace detail template <template <typename...> class AdaptedRange, typename ...Ts> auto makeRangeAdapter( Ts...data ) { return detail::RangeAdapter<AdaptedRange,Ts...>( std::move(data)... ); } namespace detail { template <typename InputRange, typename F> class TransformedRange { private: InputRange in; F f; public: TransformedRange( InputRange && in_, F && f_ ) : in( std::forward<InputRange>(in_) ) , f( std::forward<F>(f_) ) {} bool empty() const { return in.empty(); } void pop_front() { in.pop_front(); } decltype(auto) front() const { return f( in.front() ); } decltype(auto) front() { return f( in.front() ); } }; } // namespace detail template <typename F> auto transformed( F && f ) { return makeRangeAdapter<detail::TransformedRange,F>( std::forward<F>(f) ); } inline auto moved() { return transformed( []( auto && x ){ return std::move(x); } ); } } // namespace cu
[ "ralph.tandetzky@optimeas.de" ]
ralph.tandetzky@optimeas.de
21f94018c7476145ef9a004c2595de40412e863f
a80e2a43286325005f47cd5751ac19f251ff8d6f
/blockdecoder/blockdecoder.cpp
01817b7182237009e1b46d78b8f6ec3a78a317ae
[]
no_license
SuperCipher/cpp_slp_graph_search
195c5a98ec80b016e9db89b1874322ee694047c2
b5972918a622743c3d498d3397f3698aa18ed467
refs/heads/master
2023-07-24T07:09:59.740857
2021-08-06T23:57:26
2021-08-06T23:57:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <gs++/block.hpp> int main(int argc, char * argv[]) { if (argc < 2) { std::cerr << "you must pass blockdata" << std::endl; return 1; } const std::vector<std::uint8_t> blockhex = gs::util::unhex(std::string(argv[1])); gs::block block; if (! block.hydrate(blockhex.begin(), blockhex.end()) ) { std::cerr << "block hydration failed" << std::endl; return 1; } std::cout << block << std::endl; return 0; }
[ "hello@blockparty.sh" ]
hello@blockparty.sh
7cc212fde6c73256761ed77a9906b4d93ef46df9
63f4fa95ea42720cd48ff462c15442311d14fe88
/minimum_distance_plugin.cpp
43c8630257bcf71b6f5a9f0ffa6cee53986886f0
[ "Apache-2.0", "MIT" ]
permissive
sloretz/minimum_distance_plugin
d5eafcafeeaf08e8370be2257a5fd3863e5874ff
288e114e2c80c638169247adc9a26b66be68760c
refs/heads/master
2020-03-17T15:14:19.697445
2018-04-18T00:10:56
2018-04-18T00:10:56
133,703,259
0
0
null
2018-05-16T17:44:28
2018-05-16T17:44:28
null
UTF-8
C++
false
false
17,796
cpp
/* * Copyright (C) 2018 Open Source Robotics Foundation * * 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 <ccd/ccd.h> #include <ccd/quat.h> #include <gazebo/common/Events.hh> #include <gazebo/common/Plugin.hh> #include <gazebo/physics/Link.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <gazebo/transport/Node.hh> #include <gazebo/msgs/contacts.pb.h> #include "CCDWrapper.hpp" using gazebo::physics::LinkPtr; using gazebo::physics::ModelPtr; namespace minimum_distance_plugin { const std::string PluginName = "minimum_distance_plugin"; const std::string PairElementName = "pair"; const std::string FromElementName = "from"; const std::string ToElementName = "to"; const std::string RangeElementName = "range"; const std::string ModelElementName = "model"; const std::string LinkElementName = "link"; const std::string CollisionElementName = "collision"; const std::string GeometryElementName = "geometry"; const std::string PoseElementName = "pose"; const std::string EmptyElementName = "empty"; const std::string BoxElementName = "box"; const std::string CylinderElementName = "cylinder"; const std::string SphereElementName = "sphere"; const std::string CapsuleElementName = "capsule"; const std::string DilationElementName = "dilation"; const std::string SizeElementName = "size"; const std::string RadiusElementName = "radius"; const std::string LengthElementName = "length"; /////////////////////////////////////////////// struct CollisionObject { std::unique_ptr<ccdw::Convex> convex; LinkPtr link; ignition::math::Pose3d offset; CollisionObject() = default; CollisionObject(CollisionObject&&) = default; mutable ccdw::TransformedConvex tf; void update_tf() const { const ignition::math::Pose3d T = (ignition::math::Matrix4d(link->GetWorldPose().Ign()) * ignition::math::Matrix4d(offset)).Pose(); const ignition::math::Quaterniond q = T.Rot(); const ignition::math::Vector3d v = T.Pos(); tf.xform = ccdw::Transform3( ccdw::quat(q.W(), q.X(), q.Y(), q.Z()), ccdw::vec3(v.X(), v.Y(), v.Z())); } }; /////////////////////////////////////////////// gazebo::msgs::Vector3d convertToMsg(const ccdw::vec3& from) { gazebo::msgs::Vector3d result; result.set_x(from.x()); result.set_y(from.y()); result.set_z(from.z()); return result; } /////////////////////////////////////////////// struct CollisionTest { std::string name; std::vector<CollisionObject> fromObjects; std::vector<CollisionObject> toObjects; double range; CollisionTest() = default; CollisionTest(CollisionTest&&) = default; mutable gazebo::transport::PublisherPtr publisher; void runTest(const gazebo::physics::WorldPtr& world, const ccdw::Checker& checker) const { if(firstRun) { firstRun = false; contact_cache.set_collision1(name + "/from"); contact_cache.set_collision2(name + "/to"); contact_cache.add_position(); contact_cache.add_position(); contact_cache.add_depth(std::numeric_limits<double>::infinity()); *contact_cache.mutable_world() = world->GetName(); } for(const CollisionObject& from : fromObjects) from.update_tf(); for(const CollisionObject& to : toObjects) to.update_tf(); ccdw::Report closestReport; // ccdw::Report::distance represents penetration distance. Negative // penetration distance is equivalent to separation distance. Therefore, // negative infinity means the objects are infinitely separated. We will // look for the Report whose cddw::Report::distance value is **highest** // because that corresponds to the most amount of penetration, i.e. the // closest distance between objects. closestReport.distance = -std::numeric_limits<ccd_real_t>::infinity(); for(const CollisionObject& from : fromObjects) { for(const CollisionObject& to : toObjects) { ccdw::Report report; checker.penetration(report, &from.tf, &to.tf, range); // As mentioned above, we want the report whose ccdw::Report::distance // value is the **highest**. if(closestReport.distance < report.distance) closestReport = report; } } *contact_cache.mutable_position(0) = convertToMsg(closestReport.pos1); *contact_cache.mutable_position(1) = convertToMsg(closestReport.pos2); *contact_cache.mutable_depth()->Mutable(0) = closestReport.distance; gazebo::msgs::Set(contact_cache.mutable_time(), gazebo::common::Time(world->GetSimTime())); publisher->Publish(contact_cache); } private: mutable gazebo::msgs::Contact contact_cache; mutable bool firstRun = true; }; /////////////////////////////////////////////// void checkDilation( std::unique_ptr<ccdw::Convex>& convex, const sdf::ElementPtr& element) { if(element->HasElement(DilationElementName)) { sdf::ElementPtr dilationElem = element->GetElement(DilationElementName); const double dilation = dilationElem->Get<double>(); if(dilation < 0.0) { gzerr << "The element <dilation> of " << PluginName << " does not " << "support negative values (" << dilation << ")!\n"; return; } convex = std::unique_ptr<ccdw::Convex>( ccdw::dilate(convex.get(), dilation)); } } /////////////////////////////////////////////// std::unique_ptr<ccdw::Convex> generateBox( const sdf::ElementPtr& boxElem) { ignition::math::Vector3d dims(1.0, 1.0, 1.0); if(boxElem->HasElement(SizeElementName)) { sdf::ElementPtr sizeElem = boxElem->GetElement(SizeElementName); dims = sizeElem->Get<ignition::math::Vector3d>(); } else { gzerr << "Missing <" << SizeElementName << "> element inside of <" << BoxElementName << "> element of " << PluginName << "\n"; } std::unique_ptr<ccdw::Convex> box( new ccdw::Box(ccdw::vec3(dims[0], dims[1], dims[2]))); checkDilation(box, boxElem); return box; } /////////////////////////////////////////////// std::unique_ptr<ccdw::Convex> generateCylinder( const sdf::ElementPtr& cylElem) { double radius = 1.0; double length = 1.0; if(cylElem->HasElement(RadiusElementName)) { sdf::ElementPtr radiusElem = cylElem->GetElement(RadiusElementName); radius = radiusElem->Get<double>(); } else { gzerr << "Missing <" << RadiusElementName << "> element inside of <" << CylinderElementName << "> element of " << PluginName << "\n"; } if(cylElem->HasElement(LengthElementName)) { sdf::ElementPtr lengthElem = cylElem->GetElement(LengthElementName); length = lengthElem->Get<double>(); } else { gzerr << "Missing <" << LengthElementName << "> element inside of <" << CylinderElementName << "> element of " << PluginName << "\n"; } std::unique_ptr<ccdw::Convex> cylinder( new ccdw::Cylinder(length, radius)); checkDilation(cylinder, cylElem); return cylinder; } /////////////////////////////////////////////// std::unique_ptr<ccdw::Convex> generateSphere( const sdf::ElementPtr& sphereElem) { double radius = 1.0; if(sphereElem->HasElement(RadiusElementName)) { sdf::ElementPtr radiusElem = sphereElem->GetElement(RadiusElementName); radius = radiusElem->Get<double>(); } else { gzerr << "Missing <" << RadiusElementName << "> element inside of <" << SphereElementName << "> element of " << PluginName << "\n"; } return std::unique_ptr<ccdw::Convex>(ccdw::sphere(radius)); } /////////////////////////////////////////////// std::unique_ptr<ccdw::Convex> generateCapsule( const sdf::ElementPtr& capElem) { double radius = 1.0; double length = 1.0; if(capElem->HasElement(RadiusElementName)) { sdf::ElementPtr radiusElem = capElem->GetElement(RadiusElementName); radius = radiusElem->Get<double>(); } else { gzerr << "Missing <" << RadiusElementName << "> element inside of <" << CapsuleElementName << "> element of " << PluginName << "\n"; } if(capElem->HasElement(LengthElementName)) { sdf::ElementPtr lengthElem = capElem->GetElement(LengthElementName); length = lengthElem->Get<double>(); } else { gzerr << "Missing <" << LengthElementName << "> element inside of <" << CapsuleElementName << "> element of " << PluginName << "\n"; } return std::unique_ptr<ccdw::Convex>(ccdw::capsule(length, radius)); } /////////////////////////////////////////////// bool checkForInvalidShape(const sdf::ElementPtr& geomElem, const std::string& shape) { if(geomElem->HasElement(shape)) { gzerr << "collision type <" << shape << "> is not supported by " << PluginName << "\n"; return true; } return false; } /////////////////////////////////////////////// void appendCollisionObject( std::vector<CollisionObject>& objects, const LinkPtr& link, const sdf::ElementPtr& collisionElem) { CollisionObject object; object.link = link; sdf::ElementPtr geomElem = collisionElem->GetElement(GeometryElementName); if(!geomElem) { gzerr << "Missing <" << GeometryElementName << "> element inside of <" << CollisionElementName << "> element of " << PluginName << "\n"; return; } // Return if the user has specified the <empty> element if(geomElem->HasElement(EmptyElementName)) return; if(geomElem->HasElement(BoxElementName)) { sdf::ElementPtr boxElem = geomElem->GetElement(BoxElementName); object.convex = generateBox(boxElem); } else if(geomElem->HasElement(CylinderElementName)) { sdf::ElementPtr cylElem = geomElem->GetElement(CylinderElementName); object.convex = generateCylinder(cylElem); } else if(geomElem->HasElement(SphereElementName)) { sdf::ElementPtr sphereElem = geomElem->GetElement(SphereElementName); object.convex = generateSphere(sphereElem); } else if(geomElem->HasElement(CapsuleElementName)) { sdf::ElementPtr capElem = geomElem->GetElement(CapsuleElementName); object.convex = generateCapsule(capElem); } else { bool hasInvalidShape = false; for(const std::string& shape : { "heightmap", "image", "mesh", "plane", "polyline" }) hasInvalidShape |= checkForInvalidShape(geomElem, shape); if(!hasInvalidShape) { gzwarn << "Could not find any shape type for <" << GeometryElementName << "> element of " << PluginName << ". Please specify a <box> or " << "<cylinder> element!\n"; } return; } object.tf.child = object.convex.get(); if(collisionElem->HasElement(PoseElementName)) { sdf::ElementPtr poseElem = collisionElem->GetElement(PoseElementName); object.offset = poseElem->Get<gazebo::math::Pose>().Ign(); } objects.emplace_back(std::move(object)); } /////////////////////////////////////////////// void traverseLink( std::vector<CollisionObject>& objects, const ModelPtr& model, const sdf::ElementPtr& linkElem) { if(!linkElem->HasAttribute("name")) { gzerr << "<" << LinkElementName << "> element of " << PluginName << " is missing a [name] attribute!\n"; return; } const std::string& linkName = linkElem->Get<std::string>("name"); const LinkPtr& link = model->GetLink(linkName); if(!link) { gzerr << "Could not find a link named [" << linkName << "] in the model [" << model->GetName() << "], requested by " << PluginName << ", in the " << "loaded world!\n"; return; } sdf::ElementPtr collisionElem = linkElem->GetFirstElement(); while(collisionElem) { if(collisionElem->GetName() == CollisionElementName) appendCollisionObject(objects, link, collisionElem); collisionElem = collisionElem->GetNextElement(); } } /////////////////////////////////////////////// void traverseModel( std::vector<CollisionObject>& objects, const gazebo::physics::WorldPtr& world, const sdf::ElementPtr& modelElem) { if(!modelElem->HasAttribute("name")) { gzerr << "<" << ModelElementName << "> element of " << PluginName << " is missing a [name] attribute!\n"; return; } const std::string& modelName = modelElem->Get<std::string>("name"); const ModelPtr& model = world->GetModel(modelName); if(!model) { gzerr << "Could not find a model named [" << modelName << "], requested by " << PluginName << ", in the loaded world!\n"; return; } const int initialCount = static_cast<int>(objects.size()); sdf::ElementPtr linkElem = modelElem->GetFirstElement(); while(linkElem) { if(linkElem->GetName() == LinkElementName) traverseLink(objects, model, linkElem); linkElem = linkElem->GetNextElement(); } const int finalCount = static_cast<int>(objects.size()); if(finalCount - initialCount == 0) { gzwarn << "No collision objects found for <model name=\"" << modelName << "\"> element\n"; } } /////////////////////////////////////////////// std::vector<CollisionObject> generateCollisionObjects( const gazebo::physics::WorldPtr& world, const sdf::ElementPtr& pairElem, const std::string& fromOrTo, const std::string& testName) { std::vector<CollisionObject> objects; sdf::ElementPtr fromOrToElem = pairElem->GetElement(fromOrTo); if(!fromOrToElem) { gzerr << "<" << PairElementName << "> element of " << PluginName << " is missing a <" << fromOrTo << "> element!\n"; return {}; } sdf::ElementPtr modelElem = fromOrToElem->GetFirstElement(); while(modelElem) { if(modelElem->GetName() == ModelElementName) traverseModel(objects, world, modelElem); modelElem = modelElem->GetNextElement(); } if(objects.empty()) { gzwarn << "<" << fromOrTo << "> element in the [" << testName << "] pair " << "of " << PluginName << " did not provide any collision " << "geometries!\n"; } return objects; } void generateCollisionTest( std::vector<CollisionTest>& collisionTests, const gazebo::physics::WorldPtr& world, const sdf::ElementPtr& pairElem, const std::size_t count) { CollisionTest test; if(pairElem->HasAttribute("name")) { sdf::ParamPtr nameParam = pairElem->GetAttribute("name"); nameParam->Get<std::string>(test.name); } else { test.name = "Test" + std::to_string(count); } test.fromObjects = generateCollisionObjects( world, pairElem, FromElementName, test.name); test.toObjects = generateCollisionObjects( world, pairElem, ToElementName, test.name); test.range = 10.0; if(pairElem->HasElement(RangeElementName)) { sdf::ElementPtr rangeElem = pairElem->GetElement(RangeElementName); test.range = rangeElem->Get<double>(); } collisionTests.emplace_back(std::move(test)); } /////////////////////////////////////////////// class Plugin : public gazebo::WorldPlugin { public: Plugin() : computeResults(true) { // Use Load() and Init() to initialize everything else } void computeMinimumDistances() { if(!computeResults) return; for(const CollisionTest& test : collisionTests) test.runTest(world, checker); } void Load(gazebo::physics::WorldPtr _world, sdf::ElementPtr _sdf) override { sdf::ElementPtr pairElem = _sdf->GetFirstElement(); std::size_t count = 0; while(pairElem) { if (pairElem->GetName() != PairElementName) { gzwarn << "Unknown element type given to " << PluginName << ":" << pairElem->GetName() << "\n -- Expected a <pair> element\n"; continue; } generateCollisionTest(collisionTests, _world, pairElem, count); pairElem = pairElem->GetNextElement(PairElementName); } updateConnection = gazebo::event::Events::ConnectWorldUpdateEnd( [this](){ computeMinimumDistances(); }); node = gazebo::transport::NodePtr(new gazebo::transport::Node); world = _world; } void toggle(const boost::shared_ptr<const gazebo::msgs::Int>& request) { if(computeResults == static_cast<bool>(request->data())) return; if(request->data() != 0) { computeResults = true; gzmsg << "Toggling " << PluginName << " on\n"; } else { computeResults = false; gzmsg << "Toggling " << PluginName << " off\n"; } } void Init() override { node->TryInit(gazebo::common::Time::Maximum()); for(CollisionTest& test : collisionTests) { test.publisher = node->Advertise<gazebo::msgs::Contact>( "/" + node->GetTopicNamespace() + "/" + PluginName + "/" + test.name); } subscription = node->Subscribe<gazebo::msgs::Int, Plugin>( "/" + node->GetTopicNamespace() + "/" + PluginName + "/toggle", &Plugin::toggle, this); } private: std::vector<CollisionTest> collisionTests; ccdw::Checker checker; gazebo::transport::NodePtr node; gazebo::transport::SubscriberPtr subscription; std::atomic_bool computeResults; gazebo::event::ConnectionPtr updateConnection; gazebo::physics::WorldPtr world; }; GZ_REGISTER_WORLD_PLUGIN(Plugin) } // namespace minimum_distance_plugin
[ "grey@osrfoundation.org" ]
grey@osrfoundation.org
f109588875226bba0b38a0e25b78c6cdff5f4aec
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/WildMagic/SDK/Include/Wm4DistTriangle3Triangle3.h
74d713c5bc67ac102f136010ebd016ad4234b343
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
2,164
h
// Wild Magic Source Code // David Eberly // http://www.geometrictools.com // Copyright (c) 1998-2009 // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // either of the locations: // http://www.gnu.org/copyleft/lgpl.html // http://www.geometrictools.com/License/WildMagicLicense.pdf // // Version: 4.0.1 (2007/05/06) #ifndef WM4DISTTRIANGLE3TRIANGLE3_H #define WM4DISTTRIANGLE3TRIANGLE3_H #include "Wm4FoundationLIB.h" #include "Wm4Distance.h" #include "Wm4Triangle3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM DistTriangle3Triangle3 : public Distance<Real,Vector3<Real> > { public: DistTriangle3Triangle3 (const Triangle3<Real>& rkTriangle0, const Triangle3<Real>& rkTriangle1); // object access const Triangle3<Real>& GetTriangle0 () const; const Triangle3<Real>& GetTriangle1 () const; // static distance queries virtual Real Get (); virtual Real GetSquared (); // function calculations for dynamic distance queries virtual Real Get (Real fT, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); virtual Real GetSquared (Real fT, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); // Information about the closest points. Real GetTriangleBary0 (int i) const; Real GetTriangleBary1 (int i) const; private: using Distance<Real,Vector3<Real> >::m_kClosestPoint0; using Distance<Real,Vector3<Real> >::m_kClosestPoint1; const Triangle3<Real>* m_pkTriangle0; const Triangle3<Real>* m_pkTriangle1; // Information about the closest points. Real m_afTriangleBary0[3]; // closest0 = sum_{i=0}^2 bary0[i]*vertex0[i] Real m_afTriangleBary1[3]; // closest1 = sum_{i=0}^2 bary1[i]*vertex1[i] }; typedef DistTriangle3Triangle3<float> DistTriangle3Triangle3f; typedef DistTriangle3Triangle3<double> DistTriangle3Triangle3d; } #endif
[ "youalexandrov@icloud.com" ]
youalexandrov@icloud.com
272732f9d6f1b6affdac5dc772fa9c0a205d64ed
683dad6ccac9b0dadcab0e4b777991d9aee283fd
/Demo/Demo/Map.h
2e7f0a57e049ff24f7cfab7e25c7c3e21c745150
[]
no_license
AStoimenovGit/Median
a3cd7a420925db376acae057fc70451785421945
b1b2ffb0eb40c43047b2611464e61b20671b9725
refs/heads/master
2020-04-05T17:26:27.043071
2018-11-13T09:55:46
2018-11-13T09:55:46
157,058,872
0
0
null
null
null
null
UTF-8
C++
false
false
2,185
h
#ifndef _Map_h_ #define _Map_h_ #include <map> #include "Median.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Map of values and number of their occurances */ template <class T, class Compare = std::less<T>> class Map : public Median<T, Compare> { using BaseClass = Median<T, Compare>; public: Map(); virtual void Clear(); virtual void Insert(const T& value); virtual bool GetMedian(T& median) const; private: std::map<T, int, Compare> m_values; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> Map<T, Compare>::Map() : m_values() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void Map<T, Compare>::Clear() { BaseClass::Clear(); m_values.clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void Map<T, Compare>::Insert(const T& value) { BaseClass::Insert(value); ++m_values[value]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ bool Map<T, Compare>::GetMedian(T& median) const { if (!BaseClass::m_size) return false; int steps = BaseClass::m_size / 2; for (const auto& val : m_values) { if (steps >= val.second) { steps -= val.second; continue; } if(BaseClass::m_size % 2) { median = val.first; } else if (steps) { median = val.first; } else { auto prev = m_values.find(val.first); assert(prev != m_values.end()); assert(prev != m_values.begin()); --prev; median = (val.first + prev->first) / static_cast<T>(2); } break; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // _Map_h_
[ "alexander.stoimenov@gmail.com" ]
alexander.stoimenov@gmail.com
d9a475ab81184ec53e822dc99737d3a06e9fa472
6cc96bf75229c8e2cd979af1cda272b5d9ad419c
/Con Nguoi/SV.cpp
7edf44183ac6855dcd6793c716e27d490d43f003
[]
no_license
vanhao051212/OOP
6ad2cbbbc95ac4b44c3613b126c2b3e0e3c9c82f
9067cd1ac0b185de5620d814277626fb1a60184e
refs/heads/master
2020-04-07T11:41:38.992462
2018-11-28T02:30:23
2018-11-28T02:30:23
158,336,798
0
0
null
null
null
null
UTF-8
C++
false
false
768
cpp
#include "SV.h" SV::SV() { } SV::SV(char HoTen[40], char DiaChi[100], char NgaySinh[20], bool GioiTinh) { Person(HoTen, DiaChi, NgaySinh, GioiTinh); } void SV::SetInfo() { std::cin.ignore(); std::cout << "Sv Truong: "; gets_s(m_Truong); std::cout << "Sv Nganh: "; gets_s(m_Nganh); std:: cout<< "Nien Khoa: "; gets_s(m_NienKhoa); std::cout << "Sv Nam: "; std::cin >> m_Nam; } void SV::SetNewInfo() { std::cout << "Nhap Vao Ten Sinh Vien: "; gets_s(m_HoTen); SetPerson(); SetInfo(); } void SV::Output() { std::cout << "Sinh Vien: " << m_HoTen; Common_Output(); std::cout << "\nLa Sinh Vien Nam " << m_Nam << "\nTruong: " << m_Truong << "\nNganh: " << m_Nganh << "\nNienKhoa: " << m_NienKhoa; } SV::~SV() { }
[ "noreply@github.com" ]
vanhao051212.noreply@github.com
df9a05e7c94ccd7632c30999ccc80d054d9ca7f2
cb0e53fdeb45451ead4fdf05cd7c2301fae22e42
/C++Appna College/tut152_Graph_06.cpp
b6a9cb5d2b5b5a66f81d07e2b18ca5aac2a303cb
[]
no_license
Ritikkumar992/DSA-Fundamental-
86909c4474abc2db873ceee15b5a4f4e3ac90bbe
2f06995efb90a1b69f11bd05e8808b59f5e652d4
refs/heads/master
2023-07-14T13:52:28.010478
2021-08-27T17:57:59
2021-08-27T17:57:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
//Graph Topological Sort. #include<bits/stdc++.h> using namespace std; int32_t main(){ int n,m; cin>>n>>m; int cnt = 0; vector<vector< int>> adj(n); vector<int> indeg(n,0); for(int i =0;i<m;i++){ int u,v; cin>>u>>v; //u---->v; adj[u].push_back(v); indeg[v]++; } queue <int> pq; for(int i=0;i<n;i++) { if(indeg[i] == 0){ pq.push(i); } } while(!pq.empty()){ cnt++; int x = pq.front(); pq.pop(); cout<<x<<" "; for(auto it: adj[x]){ indeg[it]--; if(indeg[it] == 0) pq.push(it); } } return 0; }
[ "ritik151112@gmail.com" ]
ritik151112@gmail.com
d62c110c7778ca9f99ac4e139a2d7ed10c52a6bf
6388460fad6cc9236993cb34c77a08d677145b6a
/Loops/simpleForLoop.cpp
ec2f169a0a454f6603ae84e9bcdc893055c13b1c
[]
no_license
AlexHahnPublic/CPP_Practice
fe55b5600ea68a612ed8f006268fa35e57b0e6b5
47116984680cc54330d66bf55dc4efe9933316df
refs/heads/master
2021-05-03T22:31:50.916435
2016-10-22T04:57:47
2016-10-22T04:57:47
71,617,557
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include <iostream> using namespace std; // program needs to see cout and endl int main() { // The loop goes while x<10, and x increases by 1 every loop for ( int x=0; x <10; x++ ) { cout<< x <<endl; } cin.get(); }
[ "afh53@physics.cornell.edu" ]
afh53@physics.cornell.edu
699e18e7b27713b1e76f54f0db84ad3bb0c34b41
fc559e7f7b1e1d0aaf65407d14bd59b67ad1930f
/DAY06/ex04/koaladoctor.cpp
8b9bd15695f5d45acbed8a9f5560c02ebdf60095
[]
no_license
SarraDIF/CPP_POOL
6d02d5c8dc66d5ced5f89d7408a9d379f2a8fed1
fbdec8d5b70fa6212599345de82aaad96ab14610
refs/heads/master
2021-01-22T17:38:48.578691
2017-08-18T17:08:34
2017-08-18T17:08:34
100,729,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,212
cpp
// // Created by BlueSocket on 17/08/2017. // #include "koaladoctor.h" KoalaDoctor::KoalaDoctor(std::string name) { this->name = name; this->work = false; this->speak(std::string("Je suis le Dr.") + this->name + " ! Comment Kreoggez-vous ?"); } KoalaDoctor::~KoalaDoctor() { } std::string KoalaDoctor::getName() { return (this->name); } void KoalaDoctor::speak(std::string message) { std::cout << "Dr." << this->name << ": " << message << std::endl; } void KoalaDoctor::diagnose(SickKoala* koala) { std::string filename = koala->getName() + ".report"; std::fstream report(filename.data(), std::fstream::out | std::fstream::trunc); this->speak(std::string("Alors, qu'est-ce qui vous goerk, Mr.") + koala->getName() + " ?"); koala->poke(); if (report) { std::string drugs[5] = { "mars", "Buronzand", "Viagra", "Extasy", "Feuille d'eucalyptus" }; std::string drug = drugs[random() % 5].data(); report.write(drug.data(), drug.length()); report.close(); } } void KoalaDoctor::timeCheck() { if (this->work) { this->speak("Je rentre dans ma foret d'eucalyptus !"); } else { this->speak("Je commence le travail !"); } this->work = !this->work; }
[ "sarra.dif@epitech.eu" ]
sarra.dif@epitech.eu
436cd0194a3bcb76227724fbd10ebb2792ff4ab6
333e04b95bf1439153a579adcbd9a52e066fb23e
/Cylinder detection/voxelgrid.cpp
3ebea1ec3286434a4368b7ab81722662213baccc
[]
no_license
mtodosovska/RobotOfTheRings
5a91fa0c21d695fdf2967605872b92d7b52f59c2
5c480b6604f8106601908ab730827e51956803b1
refs/heads/master
2023-01-23T18:03:28.180202
2020-11-21T21:09:29
2020-11-21T21:09:29
85,943,265
0
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
#include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/voxel_grid.h> ros::Publisher pub; void callback(const pcl::PCLPointCloud2ConstPtr& cloud_blob) { pcl::PCLPointCloud2 cloud_filtered; pcl::VoxelGrid<pcl::PCLPointCloud2> sor; sor.setInputCloud (cloud_blob); sor.setLeafSize (0.05, 0.05, 0.05); sor.filter (cloud_filtered); pub.publish(cloud_filtered); } int main(int argc, char** argv) { ros::init (argc, argv, "voxelgrid"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe ("input", 1, callback); ros::Subscriber sub1 = nh.subscribe ("/camera/depth_registered/points", 1, callback); pub = nh.advertise<pcl::PCLPointCloud2>("output", 1); ros::spin (); }
[ "Marija.Todosovska@netcetera.com" ]
Marija.Todosovska@netcetera.com
5e3ed1a8cf759e26bb0a6ed9d532e262c712b9a9
3e6a239b08f498e9118a3dbe58531cdb92c3562c
/src/errors.hpp
45e854edc1afa311040316a76bbacbbe55b5178f
[ "MIT" ]
permissive
Lythenas/json-query
eade66f0890565976e136e75bfb7df5c73551ec9
3614deade41d66dd0e99442e53ac5a76dd5ef5fc
refs/heads/master
2022-12-03T09:12:31.847008
2020-08-14T08:56:27
2020-08-14T08:56:27
275,400,195
1
0
null
null
null
null
UTF-8
C++
false
false
1,657
hpp
#pragma once #include <boost/spirit/home/support/info.hpp> #include <exception> #include <string> namespace errors { class AppException : public std::exception {}; class InputFileException : public AppException { public: const char* what() const noexcept override { return "error reading input file"; } }; class ParseError : public std::exception { protected: std::string what_; }; class SyntaxError : public ParseError { public: std::size_t error_pos; std::string expected; template <typename Iterator> SyntaxError(Iterator first, Iterator last, Iterator error_pos, const boost::spirit::info& what) : error_pos(std::distance(first, error_pos)) { std::stringstream ss; ss << what; expected = ss.str(); what_ = "Expected " + expected + " but got \"" + std::string(error_pos, last) + "\""; } // to make this a proper std::exception // but not used by me (except maybe in tests) virtual const char* what() const noexcept override { return what_.c_str(); } template <typename Out> void pretty_print(Out& o, const std::string& input) const { assert(input.size() > error_pos); o << "Error in selector:\n" << "\033[32m" << input.substr(0, error_pos) << "\033[31m"; if (error_pos == input.size()) { o << "\033[7m" << " "; } else { o << input.substr(error_pos); } o << "\033[0m\n" << std::string(error_pos, ' ') << "^ expected \033[32m" << expected << "\033[0m\n"; } }; } // namespace errors
[ "matthias-seiffert@hotmail.de" ]
matthias-seiffert@hotmail.de
65e032085ef2bff7b7e7d5bdb80442fd9fd6ecaf
04b1803adb6653ecb7cb827c4f4aa616afacf629
/media/gpu/decode_surface_handler.h
4952ee5ab62711542b2611510ad2ef9f40be3b9f
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,682
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_GPU_DECODE_SURFACE_HANDLER_H_ #define MEDIA_GPU_DECODE_SURFACE_HANDLER_H_ #include "base/memory/scoped_refptr.h" namespace gfx { class Rect; } namespace media { class VideoColorSpace; // Interface representing {V4L2,Vaapi}DecodeSurface operations, i.e. a client // gets a T to work with by calling CreateSurface() and returns it when finished // by calling SurfaceReady(). Class T has to be ref-counted. No assumptions are // made about threading. template <class T> class DecodeSurfaceHandler { public: DecodeSurfaceHandler() = default; virtual ~DecodeSurfaceHandler() = default; // Returns a T for decoding into, if available, or nullptr. virtual scoped_refptr<T> CreateSurface() = 0; // Called by the client to indicate that |dec_surface| is ready to be // outputted. This can actually be called before decode is finished in // hardware; this method must guarantee that |dec_surface|s are processed in // the same order as SurfaceReady is called. (On Intel, this order doesn't // need to be explicitly maintained since the driver will enforce it, together // with any necessary dependencies). virtual void SurfaceReady(const scoped_refptr<T>& dec_surface, int32_t bitstream_id, const gfx::Rect& visible_rect, const VideoColorSpace& color_space) = 0; private: DISALLOW_COPY_AND_ASSIGN(DecodeSurfaceHandler); }; } // namespace media #endif // MEDIA_GPU_DECODE_SURFACE_HANDLER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
99a52ad8dc7d402b04b3f201472da940178b6ff9
e0229448c5c919578e4846a241ba35a0713fe3e8
/Filters/Filters/Mask.h
e36fccf811e3cdd7faebdbf0451005fcb4963891
[]
no_license
AlibekovMurad5202/cg-practice
0ea1c8049e775815bc6544d06c6f6fc244eea39c
e78f62d81443f28194c38bb62c958e0ecc47ad90
refs/heads/master
2022-08-01T18:26:08.258309
2020-05-29T13:08:44
2020-05-29T13:08:44
241,704,647
0
1
null
2020-05-29T13:08:45
2020-02-19T19:19:21
C++
UTF-8
C++
false
false
307
h
#pragma once #include "fstream" class TMask { private: int width; int height; int* weights; public: TMask(const std::string& _filename); TMask(const TMask& _mask); ~TMask(); int getHeight(); int getWidth(); int operator[] (int _index); const int operator[] (int _index) const; };
[ "muradalibekov2000@gmail.com" ]
muradalibekov2000@gmail.com
6da4efb11a5975d3f8ce256f3b99f974f89e4c77
cc5730e4bc12df0e35e9bcbf208ef27f8b149238
/programs/multilevel inhertiance.cpp
3897a955a01fb16fcb753f199d5d24de9eddbc19
[]
no_license
RAzaALy/Cpp_Programming
4ff601f018c135b801a30dc5601e3f13ab6924d5
a55bbb3e8681e57e07a33cf7cf183241b06fae70
refs/heads/main
2023-06-14T20:30:30.671126
2021-06-23T07:08:35
2021-06-23T07:08:35
378,995,882
0
0
null
null
null
null
UTF-8
C++
false
false
868
cpp
#include<iostream> #include<conio.h> using namespace std; class A { private: int a; public: void input() { cout<<"ENTER VLAUE OF a:"; cin>>a; } void output() { cout<<"VALUE OF a="<<a<<endl; } }; class B:public A { private: int b; public: void input() { A::input(); cout<<"ENTER VALUE OF b:"; cin>>b; } void output() { A::output(); cout<<"VALUE OF b:"<<b<<endl; } }; class C:public B { private: int c; public: void input() { B::input(); cout<<"ENTER VALUE OF c:"; cin>>c; } void output() { B::output(); cout<<"VALUE OF c:"<<c; } }; int main() { C obj; obj.input(); obj.output(); getch(); return 0; }
[ "007razajutt@gmail.com" ]
007razajutt@gmail.com
d672c3f2fa3877f61e657c41889b38ea653ac40d
7042a230c730c4fae3e336cbf7c2a58a2dc6027e
/src/Scale.h
6461193e008ba64f8d59647008fe312d5d5dc890
[]
no_license
yuferovalex/MDM500M
0d47a3212a89f84e3988ca3512a3c93b0d81ae47
8f3b57cd4d1f6edef8f5215a7ca49ed8615793a8
refs/heads/master
2020-03-26T01:30:52.462091
2018-09-17T08:07:15
2018-09-17T08:07:15
113,840,520
0
0
null
null
null
null
UTF-8
C++
false
false
409
h
#pragma once #include <QWidget> class Scale : public QWidget { Q_OBJECT public: Scale(QWidget *parent = nullptr); public slots: void setEmpty(bool value); void setSignalLevel(int value); protected: void paintEvent(QPaintEvent *) override; private: static const int kUnitsCount = 10; static const QBrush kUnitsColors[]; int m_signalLevel = 0; bool m_empty = true; };
[ "yuferov.alex@gmail.com" ]
yuferov.alex@gmail.com
433b69461a186ad6a01a99c13514567fab93e0bf
734e9e9c93cb4d3c2cd212e38f8105a81fd5e5fd
/higan/sfc/cartridge/cartridge.cpp
0e4c6826625cd99614232ee9d4739282ead895e2
[]
no_license
joncampbell123/higan-x
570747fe7f6a6b54ac9b07b3e6c993da61369129
6e8406291c91f914f3cd1f2030e453ace3fb2607
refs/heads/master
2020-06-19T05:13:57.784225
2017-06-13T01:42:31
2017-06-13T01:42:31
94,178,549
0
0
null
null
null
null
UTF-8
C++
false
false
4,936
cpp
#include <sfc/sfc.hpp> namespace SuperFamicom { #include "load.cpp" #include "save.cpp" #include "serialization.cpp" Cartridge cartridge; auto Cartridge::manifest() const -> string { string manifest = information.manifest.cartridge; if(information.manifest.gameBoy) manifest.append("\n[[Game Boy]]\n\n", information.manifest.gameBoy); if(information.manifest.bsMemory) manifest.append("\n[[BS Memory]]\n\n", information.manifest.bsMemory); if(information.manifest.sufamiTurboA) manifest.append("\n[[Sufami Turbo - Slot A]]\n\n", information.manifest.sufamiTurboA); if(information.manifest.sufamiTurboB) manifest.append("\n[[Sufami Turbo - Slot B]]\n\n", information.manifest.sufamiTurboB); return manifest; } auto Cartridge::title() const -> string { string title = information.title.cartridge; if(information.title.gameBoy) title.append(" + ", information.title.gameBoy); if(information.title.bsMemory) title.append(" + ", information.title.bsMemory); if(information.title.sufamiTurboA) title.append(" + ", information.title.sufamiTurboA); if(information.title.sufamiTurboB) title.append(" + ", information.title.sufamiTurboB); return title; } auto Cartridge::load() -> bool { information = {}; has = {}; if(auto pathID = platform->load(ID::SuperFamicom, "Super Famicom", "sfc")) { information.pathID = pathID(); } else return false; if(auto fp = platform->open(ID::SuperFamicom, "manifest.bml", File::Read, File::Required)) { information.manifest.cartridge = fp->reads(); } else return false; auto document = BML::unserialize(information.manifest.cartridge); loadCartridge(document); //Game Boy if(cartridge.has.ICD2) { information.sha256 = ""; //Game Boy cartridge not loaded yet: set later via loadGameBoy() } //BS Memory else if(cartridge.has.MCC && cartridge.has.BSMemorySlot) { information.sha256 = Hash::SHA256(bsmemory.memory.data(), bsmemory.memory.size()).digest(); } //Sufami Turbo else if(cartridge.has.SufamiTurboSlots) { Hash::SHA256 sha; sha.input(sufamiturboA.rom.data(), sufamiturboA.rom.size()); sha.input(sufamiturboB.rom.data(), sufamiturboB.rom.size()); information.sha256 = sha.digest(); } //Super Famicom else { Hash::SHA256 sha; //hash each ROM image that exists; any with size() == 0 is ignored by sha256_chunk() sha.input(rom.data(), rom.size()); sha.input(mcc.rom.data(), mcc.rom.size()); sha.input(sa1.rom.data(), sa1.rom.size()); sha.input(superfx.rom.data(), superfx.rom.size()); sha.input(hitachidsp.rom.data(), hitachidsp.rom.size()); sha.input(spc7110.prom.data(), spc7110.prom.size()); sha.input(spc7110.drom.data(), spc7110.drom.size()); sha.input(sdd1.rom.data(), sdd1.rom.size()); //hash all firmware that exists vector<uint8> buffer; buffer = armdsp.firmware(); sha.input(buffer.data(), buffer.size()); buffer = hitachidsp.firmware(); sha.input(buffer.data(), buffer.size()); buffer = necdsp.firmware(); sha.input(buffer.data(), buffer.size()); //finalize hash information.sha256 = sha.digest(); } rom.writeProtect(true); ram.writeProtect(false); return true; } auto Cartridge::loadGameBoy() -> bool { #if defined(SFC_SUPERGAMEBOY) //invoked from ICD2::load() information.sha256 = GameBoy::cartridge.sha256(); information.manifest.gameBoy = GameBoy::cartridge.manifest(); information.title.gameBoy = GameBoy::cartridge.title(); loadGameBoy(BML::unserialize(information.manifest.gameBoy)); return true; #endif return false; } auto Cartridge::loadBSMemory() -> bool { if(auto fp = platform->open(bsmemory.pathID, "manifest.bml", File::Read, File::Required)) { information.manifest.bsMemory = fp->reads(); } else return false; loadBSMemory(BML::unserialize(information.manifest.bsMemory)); return true; } auto Cartridge::loadSufamiTurboA() -> bool { if(auto fp = platform->open(sufamiturboA.pathID, "manifest.bml", File::Read, File::Required)) { information.manifest.sufamiTurboA = fp->reads(); } else return false; loadSufamiTurboA(BML::unserialize(information.manifest.sufamiTurboA)); return true; } auto Cartridge::loadSufamiTurboB() -> bool { if(auto fp = platform->open(sufamiturboB.pathID, "manifest.bml", File::Read, File::Required)) { information.manifest.sufamiTurboB = fp->reads(); } else return false; loadSufamiTurboB(BML::unserialize(information.manifest.sufamiTurboB)); return true; } auto Cartridge::save() -> void { saveCartridge(BML::unserialize(information.manifest.cartridge)); saveGameBoy(BML::unserialize(information.manifest.gameBoy)); saveBSMemory(BML::unserialize(information.manifest.bsMemory)); saveSufamiTurboA(BML::unserialize(information.manifest.sufamiTurboA)); saveSufamiTurboB(BML::unserialize(information.manifest.sufamiTurboB)); } auto Cartridge::unload() -> void { rom.reset(); ram.reset(); } }
[ "screwtape@froup.com" ]
screwtape@froup.com
c2afbb8ce97274cf1aca116454550f1150375975
af1159b123597de9c5ff2b6f5417de439b76a370
/drv/global.cpp
ffd14914d59a9431f129d9b0a70fd29275cb235f
[]
no_license
felixqin/pfw
d86306def7e07cf779d706b888f535afa5477f95
b48bb7a643bc83914940d50012314da84c911e31
refs/heads/master
2021-01-12T07:26:29.548066
2016-12-20T14:19:07
2016-12-20T14:19:07
76,961,718
0
0
null
null
null
null
GB18030
C++
false
false
1,047
cpp
#include "precomp.h" #include "global.h" //=========================================================================== //有关设备的全局变量 PDRIVER_OBJECT g_DriverObject = NULL; //驱动对象 PDEVICE_OBJECT g_ControlDevice = NULL; //控制对象 PDEVICE_OBJECT g_TcpDevice = NULL; //TCP 设备对象 PDEVICE_OBJECT g_UdpDevice = NULL; //UDP 设备对象 PDEVICE_OBJECT g_IpDevice = NULL; //IP 设备对象 CObjectTbl g_Objects; //文件对象表 //=========================================================================== PVOID g_EventHandlers[MAX_EVENT] = { 0 }; //驱动的事件函数 //=========================================================================== // 有关过滤规则全局变量 ULONG g_PfwEnabled = 0; //是否允许使用过滤规则 CFilterRules g_FilterRules; //安全规则 CAppRules g_AppRules; //应用程序安全规则 //CFilter g_Filter; ///////////////////////////////////////////////////////////////////////////// // 有关日志记录的全局变量 CTdiNotify g_Notify;
[ "qfl2000@gmail.com" ]
qfl2000@gmail.com
3472f04efc39d2632c1021b2ea9dbcc16d5028c9
3a05fdc30f3966ffc87f015322d0b69191c691ca
/b143-matrix4.cpp
2feb7fed13a350084a88063f83fece3d43253acd
[]
no_license
GibOreh/CPP
1c9cecc1776560de4b2bdf30641ed94cb214877f
d81ca1288331f19ef316ee13c8c1589d20622e0d
refs/heads/master
2023-06-15T00:11:41.793119
2021-07-11T21:04:58
2021-07-11T21:04:58
385,046,608
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
cpp
#include<bits/stdc++.h> using namespace std; int n; int m; int a[101][101]; int visit[101][101]; bool check(int x,int y){ if(x>=1 && x<=n && y>=1 && y<=m){ return true; } return false; } void bfs(pair<int,int> x){ queue<pair<int,int>> q; q.push(x); visit[x.first][x.second]= 1; int X[]= {-1,-1,-1,0,0,1,1,1}; int Y[]= {-1,0,1,-1,1,-1,0,1}; while(!q.empty()){ pair<int,int> temp= q.front(); q.pop(); for(int i=0; i<8; i++){ int u= temp.first +X[i]; int v= temp.second +Y[i]; if(check(u,v) && !visit[u][v] && a[u][v]==1){ visit[u][v]= 1; q.push({u,v}); } } } } int main(){ int t; cin>>t; while(t--){ memset(visit,0,sizeof(visit)); cin>>n>>m; for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ cin>>a[i][j]; } } int count= 0; for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ if(a[i][j]==1 && visit[i][j]==0){ count++; bfs({i,j}); } } } cout<<count<<endl; } }
[ "tr2hung99@gmail.com" ]
tr2hung99@gmail.com
9f2cf64925a6557cf90ad188610433f247e59a8f
adc0a33f20e8c09a09a2492f8c3f210c94b05ec7
/src/server/ObjectHandle.cpp
6c640e0a3f58bd208332749c3daae9b67d8fc4e3
[ "MIT" ]
permissive
farmanp/terminal
01a4fee63d4103a4d031b3f48ce71795ffea0d7f
d766c9bfebbbae9c5a9c3d4a2bd046c829dc8ed0
refs/heads/master
2020-05-24T02:07:13.854359
2019-09-15T15:15:07
2019-09-15T15:15:07
187,047,668
1
0
MIT
2019-05-16T14:48:40
2019-05-16T14:48:40
null
UTF-8
C++
false
false
8,564
cpp
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "ObjectHandle.h" #include "..\host\globals.h" #include "..\host\inputReadHandleData.h" #include "..\host\input.h" #include "..\host\screenInfo.hpp" #include "..\interactivity\inc\ServiceLocator.hpp" ConsoleHandleData::ConsoleHandleData(const ULONG ulHandleType, const ACCESS_MASK amAccess, const ULONG ulShareAccess, _In_ PVOID const pvClientPointer) : _ulHandleType(ulHandleType), _amAccess(amAccess), _ulShareAccess(ulShareAccess), _pvClientPointer(pvClientPointer), _pClientInput(nullptr) { if (_IsInput()) { _pClientInput = std::make_unique<INPUT_READ_HANDLE_DATA>(); } } // Routine Description: // - Closes this handle destroying memory as appropriate and freeing ref counts. // Do not use this handle after closing. ConsoleHandleData::~ConsoleHandleData() { if (_IsInput()) { THROW_IF_FAILED(_CloseInputHandle()); } else if (_IsOutput()) { THROW_IF_FAILED(_CloseOutputHandle()); } else { FAIL_FAST_HR(E_UNEXPECTED); } } // Routine Description: // - Checks if this handle represents an input type object. // Arguments: // - <none> // Return Value: // - True if this handle is for an input object. False otherwise. bool ConsoleHandleData::_IsInput() const { return WI_IsFlagSet(_ulHandleType, HandleType::Input); } // Routine Description: // - Checks if this handle represents an output type object. // Arguments: // - <none> // Return Value: // - True if this handle is for an output object. False otherwise. bool ConsoleHandleData::_IsOutput() const { return WI_IsFlagSet(_ulHandleType, HandleType::Output); } // Routine Description: // - Indicates whether this handle is allowed to be used for reading the underlying object data. // Arguments: // - <none> // Return Value: // - True if read is permitted. False otherwise. bool ConsoleHandleData::IsReadAllowed() const { return WI_IsFlagSet(_amAccess, GENERIC_READ); } // Routine Description: // - Indicates whether this handle allows multiple customers to share reading of the underlying object data. // Arguments: // - <none> // Return Value: // - True if sharing read access is permitted. False otherwise. bool ConsoleHandleData::IsReadShared() const { return WI_IsFlagSet(_ulShareAccess, FILE_SHARE_READ); } // Routine Description: // - Indicates whether this handle is allowed to be used for writing the underlying object data. // Arguments: // - <none> // Return Value: // - True if write is permitted. False otherwise. bool ConsoleHandleData::IsWriteAllowed() const { return WI_IsFlagSet(_amAccess, GENERIC_WRITE); } // Routine Description: // - Indicates whether this handle allows multiple customers to share writing of the underlying object data. // Arguments: // - <none> // Return Value: // - True if sharing write access is permitted. False otherwise. bool ConsoleHandleData::IsWriteShared() const { return WI_IsFlagSet(_ulShareAccess, FILE_SHARE_WRITE); } // Routine Description: // - Retieves the properly typed Input Buffer from the Handle. // Arguments: // - amRequested - Access that the client would like for manipulating the buffer // - ppInputBuffer - On success, filled with the referenced Input Buffer object // Return Value: // - HRESULT S_OK or suitable error. [[nodiscard]] HRESULT ConsoleHandleData::GetInputBuffer(const ACCESS_MASK amRequested, _Outptr_ InputBuffer** const ppInputBuffer) const { *ppInputBuffer = nullptr; RETURN_HR_IF(E_ACCESSDENIED, WI_IsAnyFlagClear(_amAccess, amRequested)); RETURN_HR_IF(E_HANDLE, WI_IsAnyFlagClear(_ulHandleType, HandleType::Input)); *ppInputBuffer = static_cast<InputBuffer*>(_pvClientPointer); return S_OK; } // Routine Description: // - Retieves the properly typed Screen Buffer from the Handle. // Arguments: // - amRequested - Access that the client would like for manipulating the buffer // - ppInputBuffer - On success, filled with the referenced Screen Buffer object // Return Value: // - HRESULT S_OK or suitable error. [[nodiscard]] HRESULT ConsoleHandleData::GetScreenBuffer(const ACCESS_MASK amRequested, _Outptr_ SCREEN_INFORMATION** const ppScreenInfo) const { *ppScreenInfo = nullptr; RETURN_HR_IF(E_ACCESSDENIED, WI_IsAnyFlagClear(_amAccess, amRequested)); RETURN_HR_IF(E_HANDLE, WI_IsAnyFlagClear(_ulHandleType, HandleType::Output)); *ppScreenInfo = static_cast<SCREEN_INFORMATION*>(_pvClientPointer); return S_OK; } // Routine Description: // - Retrieves the wait queue associated with the given object held by this handle. // Arguments: // - ppWaitQueue - On success, filled with a pointer to the desired queue // Return Value: // - HRESULT S_OK or E_UNEXPECTED if the handle data structure is in an invalid state. [[nodiscard]] HRESULT ConsoleHandleData::GetWaitQueue(_Outptr_ ConsoleWaitQueue** const ppWaitQueue) const { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); if (_IsInput()) { InputBuffer* const pObj = static_cast<InputBuffer*>(_pvClientPointer); *ppWaitQueue = &pObj->WaitQueue; return S_OK; } else if (_IsOutput()) { // TODO MSFT 9405322: shouldn't the output queue be per output object target, not global? https://osgvsowi/9405322 *ppWaitQueue = &gci.OutputQueue; return S_OK; } else { return E_UNEXPECTED; } } // Routine Description: // - For input buffers only, retrieves an extra handle data structure used to save some information // across multiple reads from the same handle. // Arguments: // - <none> // Return Value: // - Pointer to the input read handle data structure with the aforementioned extra info. INPUT_READ_HANDLE_DATA* ConsoleHandleData::GetClientInput() const { return _pClientInput.get(); } // Routine Description: // - This routine closes an input handle. It decrements the input buffer's // reference count. If it goes to zero, the buffer is reinitialized. // Otherwise, the handle is removed from sharing. // Arguments: // - <none> // Return Value: // - HRESULT S_OK or suitable error code. // Note: // - The console lock must be held when calling this routine. [[nodiscard]] HRESULT ConsoleHandleData::_CloseInputHandle() { FAIL_FAST_IF(!(_IsInput())); InputBuffer* pInputBuffer = static_cast<InputBuffer*>(_pvClientPointer); INPUT_READ_HANDLE_DATA* pReadHandleData = GetClientInput(); pReadHandleData->CompletePending(); // see if there are any reads waiting for data via this handle. if // there are, wake them up. there aren't any other outstanding i/o // operations via this handle because the console lock is held. if (pReadHandleData->GetReadCount() != 0) { pInputBuffer->WaitQueue.NotifyWaiters(true, WaitTerminationReason::HandleClosing); } FAIL_FAST_IF(pReadHandleData->GetReadCount() > 0); // TODO: MSFT: 9115192 - THIS IS BAD. It should use a destructor. LOG_IF_FAILED(pInputBuffer->FreeIoHandle(this)); if (!pInputBuffer->HasAnyOpenHandles()) { pInputBuffer->ReinitializeInputBuffer(); } return S_OK; } // Routine Description: // - This routine closes an output handle. It decrements the screen buffer's // reference count. If it goes to zero, the buffer is freed. Otherwise, // the handle is removed from sharing. // Arguments: // - <none> // Return Value: // - HRESULT S_OK or suitable error code. // Note: // - The console lock must be held when calling this routine. [[nodiscard]] HRESULT ConsoleHandleData::_CloseOutputHandle() { FAIL_FAST_IF(!(_IsOutput())); SCREEN_INFORMATION* pScreenInfo = static_cast<SCREEN_INFORMATION*>(_pvClientPointer); pScreenInfo = &pScreenInfo->GetMainBuffer(); // TODO: MSFT: 9115192 - THIS IS BAD. It should use a destructor. LOG_IF_FAILED(pScreenInfo->FreeIoHandle(this)); if (!pScreenInfo->HasAnyOpenHandles()) { SCREEN_INFORMATION::s_RemoveScreenBuffer(pScreenInfo); } return S_OK; }
[ "duhowett@microsoft.com" ]
duhowett@microsoft.com
95fa10bc1b4c9bf204b2f4a6aa8ade493c77d692
fa40a93ca9d851909aeea182c49c07eb9a0e88d1
/tests/vector.cpp
794ff4ed09513ca05273d57d80206811543b2672
[ "Apache-2.0" ]
permissive
pniekamp/leap
43d5f0e7e4498e2ceaff7f081b397732bae713ad
fe66c5aae1f4a676718806198677731a0f0d19e2
refs/heads/master
2021-06-15T19:58:59.067329
2021-03-14T12:00:49
2021-03-14T12:00:49
53,132,631
0
0
null
null
null
null
UTF-8
C++
false
false
4,997
cpp
// // vector.cpp // // Copyright (C) Peter Niekamp // // This code remains the property of the copyright holder. // The code contained herein is licensed for use without limitation // #include <iostream> #include <sstream> #include <leap/lml/vector.h> #include <leap/lml/io.h> #include <leap/util.h> using namespace std; using namespace leap; using namespace leap::lml; void VectorTest(); constexpr Vector2f gVector1{ 1.0f, 2.0f }; constexpr Vector2f gVector2 = Vector2(3.0f, 4.0f); constexpr float gElement = gVector1(0) * gVector2(1); //constexpr float gVecNorm = norm(gVector1); //|//////////////////// VectorBasicTest ///////////////////////////////////// static void VectorBasicTest() { cout << "Simple Vector Test Set\n"; Vector3f P; if (P.size() != 3) cout << "** Size Error!\n"; cout << " Size : " << P.size() << "\n"; P(0) = 1; P(1) = 2; P(2) = 3; if (P(0) != 1 || P(1) != 2 || P(2) != 3) cout << "** Set Error!\n"; cout << " Data P() : "; for(size_t i = 0; i < P.size(); ++i) cout << P(i) << " "; cout << "\n"; Vector3f Q = P; if (Q(0) != 1 || Q(1) != 2 || Q(2) != 3) cout << "** Copy Constructor Error!\n"; Q(0) = 4; if (Q(0) != 4 || P(0) != 1) cout << "** Copy Constructor Set Error!\n"; Q = P; if (Q(0) != 1 || Q(1) != 2 || Q(2) != 3) cout << "** Copy Operator Error!\n"; Q(0) = 4; Q(1) = 5; Q(2) = 6; if (Q(0) != 4 || Q(1) != 5 || Q(2) != 6 || P(0) != 1 || P(1) != 2 || P(2) != 3) cout << "** Copy Operator Set Error!\n"; Q = Q; if (Q(0) != 4 || Q(1) != 5 || Q(2) != 6) cout << "** Self Copy Error!\n"; // Vector3d R = P; // if (R(0) != 1 || R(1) != 2 || R(2) != 3) // cout << "** Cross Copy Constructor Error!\n"; // R = Q; // if (R(0) != 4 || R(1) != 5 || R(2) != 6) // cout << "** Cross Copy Operator Error!\n"; // if (Q != R) // cout << "** Equality Test Error!\n"; swap(P, Q); if (P(0) != 4 || P(1) != 5 || P(2) != 6 || Q(0) != 1 || Q(1) != 2 || Q(2) != 3) cout << "** Swap Error!\n"; swap(P, P); if (P(0) != 4 || P(1) != 5 || P(2) != 6) cout << "** Self Swap Error!\n"; if (gElement != 4) cout << "** Error in Vector Constants\n"; cout << endl; } class Vec3 : public Vector3f { public: Vec3(float x, float y, float z) : Vector3f({ x, y, z }) { } }; //|//////////////////// VectorMathTest ////////////////////////////////////// static void VectorMathTest() { cout << "Vector Math Test Set\n"; Vector3d A, B, C; for(int i = 0; i < 3; ++i) { A(i) = i; B(i) = i+1; C(i) = (i==0) ? 0.5 : i*2; } cout << " " << A << " + " << B << " = " << A+B << "\n"; if (A+B != Vector3(1.0, 3.0, 5.0)) cout << "** Error in Vector addition\n"; cout << " " << C << " - " << B << " = " << C-B << "\n"; if (C-B != Vector3(-0.5, 0.0, 1.0)) cout << "** Error in Vector subtraction\n"; cout << " 5 * " << C << " = " << 5*C << "\n"; if (5*C != 5.0*C || 5*C != C*5 || 5*C != Vector3(2.5, 10.0, 20.0)) cout << "** Error in Vector scaler multiplication\n"; cout << " " << C << " / 5 = " << C/5 << "\n"; if (C/5 != C/5.0 || C/5 != Vector3(0.1, 0.4, 0.8)) cout << "** Error in Vector scaler multiplication\n"; // This test gives a warning about conversion to int // Vector<3, int> G = Vector3(1, 2, 3); // cout << " 1.5 * " << G << " = " << 1.5f*G << "\n"; // if (1.5f*G != Vector3(1, 3, 4)) // cout << "** Error in integer Vector scaler multiplication\n"; cout << " norm(" << C << ") = " << norm(C) << "\n"; if (norm(C) != 4.5) cout << "** Error in Vector norm\n"; cout << " dot(" << A << ", " << C << ") = " << dot(A, C) << "\n"; if (dot(A, C) != 10) cout << "** Error in Vector dot product\n"; cout << " clamp(" << A << ", 0, 1) = " << clamp(A, 0.0, 1.0) << "\n"; cout << " swizzle<2,0,1>(" << A << ") = " << swizzle<2,0,1>(A) << "\n"; Vec3 pt(1, 2, 3); cout << " Point (Vector derivative) : " << pt + pt << " (" << sizeof(pt) << " bytes)" << " [" << get<0>(pt) << "," << get<1>(pt) << "," << get<2>(pt) << "]\n"; cout << endl; } //|//////////////////// lmlioTest /////////////////////////////////////////// static void lmlioTest() { cout << "lml IO Test Set\n"; istringstream is; Vector<double, 5> P; for(int i = 0; i < 5; ++i) P(i) = i / 10.0; cout << " Output : " << P << "\n"; is.str("(1,2.3,-3.12,9e-1,10)"); if (!(is >> P) || P(0) != 1.0 || P(1) != 2.3 || P(2) != -3.12 || P(3) != 0.9 || P(4) != 10) cout << "** Read without spaces Error!\n"; is.str(" ( 1 , -2 , +3.911 , 8e-2, 11 ) "); if (!(is >> P) || P(0) != 1.0 || P(1) != -2.0 || P(2) != 3.911 || P(3) != 0.08 || P(4) != 11) cout << "** Read with spaces Error!\n"; cout << " Input : " << P << "\n"; cout << endl; } //|//////////////////// VectorTest ////////////////////////////////////////// void VectorTest() { VectorBasicTest(); VectorMathTest(); lmlioTest(); cout << endl; }
[ "pniekamp@gmail.com" ]
pniekamp@gmail.com
6b2a80a0e397b87780ca9c51e0e402f50fa05cad
374b802c9287391ccf515220ecab074c4b847960
/First-Dlg-Project/stdafx.cpp
a03eb9033a8b5297bf2d6b2e9b68e55a1659af20
[]
no_license
walleri18/Programming-under-Windows-OS
f4e815c35a6976108f65d9b88efa8ae0e5551665
3f37d151e4478bdcf12237d4e028251c50d6585b
refs/heads/master
2021-01-10T01:33:53.945166
2016-03-22T17:06:20
2016-03-22T17:06:20
51,696,190
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
384
cpp
// stdafx.cpp: исходный файл, содержащий стандарт, включающий // First-Dlg-Project.pch будет предварительно откомпилированным заголовком // stdafx.obj будет содержать предварительно откомпилированные сведения о типе #include "stdafx.h"
[ "walleri18@yandex.ru" ]
walleri18@yandex.ru
0ebefcd43c08391a1a4105d777027be834752584
7e6503c5b354bc20593022278e459a8e62047879
/PicoloWindowsImageServer/PicoloRead/PicoloImageServer.h
7a43013d6cc7ac5c81cde5c7621e67bdccb4e6d8
[]
no_license
jaejunlee0538/ImageSending
0d343cb450625dfc493548e66af497f8e0ffc0f2
7da636384d2bc3925f65e2b4e0a0c476a4bbb0a8
refs/heads/master
2020-09-17T02:53:41.577967
2016-08-31T19:42:55
2016-08-31T19:42:55
66,149,935
1
0
null
null
null
null
UHC
C++
false
false
1,430
h
#ifndef PICOLO_IMAGE_SERVER_H_ #define PICOLO_IMAGE_SERVER_H_ #include "PicoloImageRead.h" #include <opencv2/opencv.hpp> #include "ImageServer.h" #include "ImagePacket.h" #include "PreciseClock.h" namespace MC = Euresys::MultiCam; /* setServer와 init 메서드는 setActive 메서드를 호출하여 이미지를 수집하기 전에 반드시 호출하여야 한다. */ class PicoloImageSender :public PicoloImageReader{ public: PicoloImageSender() :m_serverPtr(NULL), m_id(-1){ } /* 이미지 서버의 포인터를 설정함. 새로운 영상 정보가 갱신 될 때마다 이미지 서버에 영상 데이터를 넘겨줌. 서버는 넘겨 받은 영상 정보를 네트워크로 전송함. */ void setServer(ImageServer* server){ m_serverPtr = server; } /* 사용자 지정 카메라 ID를 설정함. 영상을 네트워크로 전송 시에 수신 측에서 각 영상의 소스(각각의 카메라)를 구별하기 위해서 사용함. */ void setID(const uint32_t& id){ m_id = id; } /* Picolo board와 카메라를 초기화함. */ virtual bool init(const size_t& boardIdx, const char* connectorName, const char* camType, const int& pixelType); protected: virtual void userCallback(std::shared_ptr<cv::Mat>& img, MC::Channel & ch, MC::SignalInfo & sig); std::string windowName; FrequencyEstimator freq; ImageServer * m_serverPtr; uint32_t m_id;//카메라 ID(User-Defined) }; #endif
[ "jaejun0201@gmail.com" ]
jaejun0201@gmail.com
35875c8121b19d3e043ddd608ba938b614a731b6
2d7085400926aa37e400fd00716df7305987e8d5
/src/uiobjects/Traza.cpp
fe597961d8f4909acf5bd9b574e447be140bc076
[]
no_license
damarbo33/crosslib
3fdd3c20e7516c6529bd4c393131ea58cb46fc01
5daca258df974c1c10e3fa338700072bb385f317
refs/heads/master
2022-11-04T09:35:15.144396
2022-10-27T08:55:08
2022-10-27T08:55:08
82,192,728
0
0
null
null
null
null
UTF-8
C++
false
false
2,224
cpp
// Class automatically generated by Dev-C++ New Class wizard #include "Traza.h" // class's header file ofstream *Traza::fout; bool Traza::pintarTrazas; /** * Constructor */ Traza::Traza(const char *ruta){ strcpy(this->ruta,ruta); iniFile(); } /** * Constructor */ Traza::Traza(){ strcpy(this->ruta,RUTA_TRAZA); iniFile(); } /** * Destructor */ Traza::~Traza(){ closeFile(); } /** * */ void Traza::iniFile(){ setTraza(TRAZA_ENABLED); this->fout = NULL; this->fout = new ofstream(ruta, ios::out | ios::app | ios::binary); } /** * closeFile */ void Traza::closeFile(){ if (this->fout != NULL){ this->fout->close(); this->fout = NULL; } } /** * print */ void Traza::print(string msg,int msg2, int logLevel){ if (pintarTrazas && logLevel <= Constant::getTrazaLevel()){ string myMsg = string(msg) + string(":") + Constant::TipoToStr(msg2); print(myMsg.c_str(), logLevel); } } /** * print */ void Traza::print(string msg, int logLevel){ #ifdef RELEASE if (pintarTrazas && logLevel <= W_ERROR){ #else if (pintarTrazas && logLevel <= Constant::getTrazaLevel()){ #endif if ( fout != NULL){ if (!msg.empty()){ string type = "-DEBUG"; switch(logLevel){ case 0 : type = "-FATAL"; break; case 1 : type = "-ERROR"; break; case 2 : type = "-WARN"; break; case 3 : type = "-INFO"; break; case 4 : type = "-DEBUG"; break; case 5: type = "-PARANOIC"; break; default : type = "-DDEBUG"; break; } *fout << Constant::fecha() << "-" << type << ": " << msg << endl; } } } } /** * setTraza */ void Traza::setTraza(bool estado){ pintarTrazas = estado; }
[ "damarbo33@gmail.com" ]
damarbo33@gmail.com
dd0f90a10aa4195ed5dce623a14d53fad447271c
70ad0a06c54b68b7d817131f4b139b76739e2e20
/GUI/BScope/PlayerWindow.h
58aeb525bd699f7f49d79ee784747c74698f42c7
[ "MIT" ]
permissive
SherlockThang/sidecar
391b08ffb8a91644cbc86cdcb976993386aca70c
2d09dfaebee3c9b030db4d8503b765862e634068
refs/heads/master
2022-12-09T14:57:08.727181
2020-09-01T10:31:12
2020-09-01T10:31:12
313,326,062
1
0
MIT
2020-11-16T14:21:59
2020-11-16T14:21:58
null
UTF-8
C++
false
false
2,390
h
#ifndef SIDECAR_GUI_BSCOPE_PLAYERWINDOW_H // -*- C++ -*- #define SIDECAR_GUI_BSCOPE_PLAYERWINDOW_H #include "QtCore/QBasicTimer" #include "QtCore/QList" #include "QtGui/QImage" #include "QtWidgets/QWidget" #include "GUI/MainWindowBase.h" class QScrollArea; namespace Logger { class Log; } namespace SideCar { namespace GUI { namespace BScope { class FrameWidget; class ImageScaler; class PlayerPositioner; class PlayerSettings; class PlayerWindow : public MainWindowBase { Q_OBJECT using Super = MainWindowBase; public: static Logger::Log& Log(); PlayerWindow(const QList<QImage>& past, const QImage& blank, int shortcut); void saveToSettings(QSettings&); void restoreFromSettings(QSettings& settings); public slots: void setNormalSize(const QSize& size); void setScale(double scale); void setFrameCount(int frameCount); void frameAdded(int activeFrames); private slots: void on_actionViewZoomIn__triggered(); void on_actionViewZoomOut__triggered(); void on_actionShowMainWindow__triggered(); void on_actionShowFramesWindow__triggered(); void on_actionPresetRevert__triggered(); void on_actionPresetSave__triggered(); void playbackRateChanged(int msecs); void updateMaxSize(); void start(); void stop(); void positionerValueChanged(int value); void imageScalerDone(const QImage& image, int index); private: void updateButtons(); void updateInfo(); void keyReleaseEvent(QKeyEvent* event); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void timerEvent(QTimerEvent* event); void showEvent(QShowEvent* event); void hideEvent(QHideEvent* event); void rescaleImage(int index, bool all); const QList<QImage>& past_; QList<QImage> scaled_; PlayerSettings* playerSettings_; QScrollArea* scrollArea_; FrameWidget* frame_; PlayerPositioner* positioner_; QAction* actionViewTogglePhantomCursor_; ImageScaler* imageScaler_; QBasicTimer playTimer_; QPoint panFrom_; double scale_; QSize normalSize_; QSize scaledSize_; int rescalingIndex_; bool panning_; bool needUpdateMaxSize_; bool rescalingAll_; }; } // end namespace BScope } // end namespace GUI } // end namespace SideCar #endif
[ "bradhowes@mac.com" ]
bradhowes@mac.com
b7b31a0bc338b2d3e7173c859320c64131414217
1d3a99aef7a8683dee5f834923ca831861311f78
/library/include/memory.hh
7a9b9597ad2ec79db7e5f7f96ab9d513fc9ab0d3
[]
no_license
daanhenke/scareware
35f732757fbbddbccc3229f3a8572cba18304643
a2e05fdede71f4572ff085b5a74b09714a6810eb
refs/heads/master
2023-04-01T20:44:23.291249
2021-04-12T22:08:05
2021-04-12T22:08:05
324,032,755
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
hh
#pragma once #include <Windows.h> #include <string> #include "iface/IViewRenderBeams.hh" #include "iface/IMoveHelper.hh" #include "iface/CMoveData.hh" #include <d3d9.h> namespace sw::iface { class KeyValues; } namespace sw::memory { template<typename T> constexpr T ToAbsolute(uintptr_t address) { return (T)(address + 4 + *reinterpret_cast<std::int32_t*>(address)); } DWORD WaitForModule(const char* module_name); DWORD FindTextInModule(const char* module_name, const char* text); DWORD FindPattern(const char* module_name, std::string pattern); void FindRandomPtrs(); extern uintptr_t CameraThinkPtr; extern std::add_pointer_t<void __fastcall(const char*)> LoadSky; extern uintptr_t KeyValuesFromString; extern iface::KeyValues* (__thiscall* KeyValuesFindKey)(iface::KeyValues* keyValues, const char* keyName, bool create); extern void (__thiscall* KeyValuesSetString)(iface::KeyValues* keyValues, const char* value); extern iface::IViewRenderBeams* IViewRenderBeams; extern iface::IMoveHelper* IMoveHelper; extern int* predictSeed; extern iface::CMoveData* CMoveData; extern IDirect3DDevice9* D3DDevice; }
[ "daan@daan.vodka" ]
daan@daan.vodka
71f34842bef03e11b4fcc68e8963f5cb62377275
7550795ab145607efaaf562a7f25be86b39cb9e9
/0583.cpp
04204b9ec751a9ad1f60e724a0a35d0efefb15b3
[]
no_license
shiba090/aoj
8dd97e678076a71848ad3dc4b2ecb6aa7728e9af
20e4f5418fffc2065494c6e589a6aac49d331055
refs/heads/master
2016-09-06T07:49:40.458614
2015-06-28T13:38:11
2015-06-28T13:38:11
38,198,357
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
#include <functional> #include <algorithm> #include <iostream> #include <numeric> #include <iomanip> #include <utility> #include <cstdlib> #include <sstream> #include <bitset> #include <vector> #include <cstdio> #include <ctime> #include <queue> #include <deque> #include <cmath> #include <stack> #include <list> #include <map> #include <set> using namespace std; typedef vector<int> vi; typedef pair<int,int> pii; typedef long long ll; #define dump(x) cerr << #x << " = " << (x) << endl #define rep(i,n) for(int i=0;i<(n);i++) #define all(a) (a).begin(),(a).end() #define pb push_back int n; bool solve(int in[3],int a){ rep(i,n){ if(in[i]%a!=0)return false; } return true; } int main() { cin>>n; int in[3]={}; int ma=-1; rep(i,n){ cin>>in[i]; ma=max(ma,in[i]); } for(int i=1;i<=ma;i++){ if( solve(in,i) ){ cout<<i<<endl; } } return 0; }
[ "m2914711979@deapink.pink" ]
m2914711979@deapink.pink
39aa9a7f2613711c56922907bd54c055bcf49143
a19e7a3c448588e3be7fd789c48f8d0c9521e945
/Source/S05__TestingGrounds/NPC/ChooseNextWaypoint.h
efbbf42cd8a69e66d0a55bc8943980f12be9a243
[]
no_license
AlbertMontagutCasero/TestingGrounds
e0234e3f221ffef07e65d2dea338438946085c81
74a2fa43914cbe7da4126b805b592906459bd5c2
refs/heads/master
2021-09-06T22:57:46.135955
2018-02-13T01:24:44
2018-02-13T01:24:44
112,645,453
0
0
null
null
null
null
UTF-8
C++
false
false
623
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "BehaviorTree/BTTaskNode.h" #include "ChooseNextWaypoint.generated.h" /** * */ UCLASS() class S05__TESTINGGROUNDS_API UChooseNextWaypoint : public UBTTaskNode { GENERATED_BODY() virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override; protected: UPROPERTY(EditAnywhere, Category = "Blackboard") struct FBlackboardKeySelector IndexKey; UPROPERTY(EditAnywhere, Category = "Blackboard") struct FBlackboardKeySelector WaypointKey; };
[ "albert.montagut.casero@gmail.com" ]
albert.montagut.casero@gmail.com
349d0395c61ad6c3b0c1ecf9a5b4a0fbcea38f54
a5e5aff33259dfbb637cf000874f2c16d747503c
/src/gdgem/tests/HitGenerator.cpp
a9ad8e7f67c46ed253206be975b78ba027f60f84
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
moneytech/event-formation-unit
c85365183f3446421eedac3a919e552738149b71
4ef64fb72a199e408209a6c19cc4ca69811be538
refs/heads/master
2022-04-17T17:35:38.807249
2020-04-02T14:09:45
2020-04-02T14:09:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,697
cpp
/** Copyright (C) 2019 European Spallation Source ERIC */ #include <gdgem/tests/HitGenerator.h> #include <fmt/format.h> #include <algorithm> #include <cmath> #include <cstdio> #include <vector> #include <cassert> /// \todo Should not belong to gdgem but to common, reduction? namespace Gem { // void HitGenerator::printHits() { for (auto & Hit : Hits) { fmt::print("t {}, p {}, c {}, w {}\n", Hit.time, Hit.plane, Hit.coordinate, Hit.weight); } } // void HitGenerator::printEvents() { fmt::print("t (x, y)\n"); for (auto & Event : Events) { fmt::print("{} ({}, {})\n", Event.TimeNs, Event.XPos, Event.YPos); } } // std::vector<NeutronEvent> & HitGenerator::randomEvents(int NumEvents, int MinCoord, int MaxCoord) { auto TimeNs = T0; std::uniform_int_distribution<int> coords(MinCoord, MaxCoord); for (int i = 0; i < NumEvents; i++) { auto XPos = coords(RandGen); auto YPos = coords(RandGen); //fmt::print("Event: ({}, {}), t={}\n", XPos, YPos, Time); Events.push_back({XPos, YPos, TimeNs}); TimeNs += TGap; } return Events; } // std::vector<Hit> & HitGenerator::randomHits(int MaxHits, int Gaps, int DeadTimeNs, bool Shuffle) { std::uniform_int_distribution<int> angle(0, 360); for (auto & Event : Events) { auto Degrees = angle(RandGen); //fmt::print("({},{}) @ {}\n", Event.XPos, Event.YPos, Degrees); makeHitsForSinglePlane(0, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle); makeHitsForSinglePlane(1, MaxHits, Event.XPos, Event.YPos, Degrees, Gaps, DeadTimeNs, Shuffle); advanceTime(TGap); } return Hits; } // std::vector<Hit> & HitGenerator::makeHitsForSinglePlane(int Plane, int MaxHits, float X0, float Y0, float Angle, int Gaps, int DeadTimeNs, bool Shuffle) { int64_t TimeNs = T0; int32_t OldTime = TimeNs; float TmpCoord{0}; int Coord{32767}, OldCoord{32767}; uint16_t ADC{2345}; std::vector<Hit> TmpHits; if ((Plane != PlaneX) and (Plane != PlaneY)) { return Hits; } for (int hit = 0; hit < MaxHits; hit++) { if (Plane == PlaneX) { TmpCoord = X0 + hit * 1.0 * cos(D2R(Angle)); //fmt::print("X0 {}, RO {}, Angle {}, cos(angle) {}, TmpCoord {}\n", X0, hit, Angle, cosa, TmpCoord); } else { TmpCoord = Y0 + hit * 1.0 * sin(D2R(Angle)); } Coord = (int)TmpCoord; if ((Coord > CoordMax) or (Coord < CoordMin)) { continue; } // Same coordinate - time gap is critical if (Coord == OldCoord) { //fmt::print("Same coordinate, OldTime {}, Time {}\n", OldTime, Time); if ((OldTime != TimeNs) and (TimeNs - OldTime < DeadTimeNs) ) { // Not the first Hit but within deadtime //fmt::print(" dT {} shorter than deadtime - skipping\n", Time - OldTime); TimeNs += DeltaT; continue; } } Hit CurrHit{(uint64_t)TimeNs, (uint16_t)Coord, ADC, (uint8_t)Plane}; TmpHits.push_back(CurrHit); OldTime = TimeNs; TimeNs += DeltaT; OldCoord = Coord; } // Handle gaps TmpHits = makeGaps(TmpHits, Gaps); if (Shuffle) { std::shuffle(TmpHits.begin(), TmpHits.end(), RandGen); } for (auto & Hit : TmpHits) { Hits.push_back(Hit); } return Hits; } // std::vector<Hit> & HitGenerator::makeGaps(std::vector<Hit> & Hits, uint8_t Gaps) { if (Gaps == 0) { return Hits; } std::vector<Hit> GapHits; if (Gaps > Hits.size() - 2) { //fmt::print("Gaps requestes {}, available {}\n", Gaps, TmpHits.size() - 2); Hits.clear(); } for (unsigned int i = 0; i < Hits.size(); i ++) { if ((i == 0) or (i > Gaps)) { GapHits.push_back(Hits[i]); } } Hits = GapHits; return Hits; } } // namespace
[ "morten.christensen@esss.se" ]
morten.christensen@esss.se
e96995444a80bcc923838f7f0f340b4efb2456a6
4e38faaa2dc1d03375010fd90ad1d24322ed60a7
/include/RED4ext/Scripting/Natives/Generated/game/data/RoachRaceLevelList_Record.hpp
08d06f3defe22e7b7656ae5fbcde59161370740a
[ "MIT" ]
permissive
WopsS/RED4ext.SDK
0a1caef8a4f957417ce8fb2fdbd821d24b3b9255
3a41c61f6d6f050545ab62681fb72f1efd276536
refs/heads/master
2023-08-31T08:21:07.310498
2023-08-18T20:51:18
2023-08-18T20:51:18
324,193,986
68
25
MIT
2023-08-18T20:51:20
2020-12-24T16:17:20
C++
UTF-8
C++
false
false
791
hpp
#pragma once // clang-format off // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/game/data/TweakDBRecord.hpp> namespace RED4ext { namespace game::data { struct RoachRaceLevelList_Record : game::data::TweakDBRecord { static constexpr const char* NAME = "gamedataRoachRaceLevelList_Record"; static constexpr const char* ALIAS = "RoachRaceLevelList_Record"; uint8_t unk48[0x50 - 0x48]; // 48 }; RED4EXT_ASSERT_SIZE(RoachRaceLevelList_Record, 0x50); } // namespace game::data using gamedataRoachRaceLevelList_Record = game::data::RoachRaceLevelList_Record; using RoachRaceLevelList_Record = game::data::RoachRaceLevelList_Record; } // namespace RED4ext // clang-format on
[ "3403191+WopsS@users.noreply.github.com" ]
3403191+WopsS@users.noreply.github.com
853ac31cd498f6e766ef72fce7c0451a53cb43a7
d778525e7823854ee35d92164d1e2f8c8a689f07
/LOOP/11_FIR&L.CPP
120219ea0289486d6544898ba9af55a81084b4a2
[]
no_license
manojmansukh/C
b695afeb55b56839cb2ea30a056dae4dcd4f5ce1
bfce00c64df084557f4dad864928116d2c69ed69
refs/heads/master
2020-09-04T16:25:22.817196
2019-11-05T17:17:51
2019-11-05T17:17:51
219,801,176
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
#include<stdio.h> #include<conio.h> int main() { long long no,first,last,sum=0; clrscr(); printf("enter the no :"); scanf("%lld",&no); last=no%10; // first=no; while(no>=10) { no=no/10; } first=no; printf("first no: %lld\n",first); printf("last no: %lld\n",last); getch(); }
[ "manojmansukh7@gmail.com" ]
manojmansukh7@gmail.com
2f81aa9754548816298c41a1f6be736cb554802d
ef2e6bfd2f9c1a7e246c5a2251e0c3c72bf2f5fb
/BullCowGame/FBullCowGame.cpp
3611de7ef7426a0cbf50e097d369ba382a46eda2
[]
no_license
timdhoffmann/Section_02
4f4ca6d98adca9efd824b6465b5ac0a11b5aa0ce
c9b09cdea9c4c356a805511eb2580a5f6f5c047a
refs/heads/master
2021-09-06T21:22:13.730742
2018-02-11T17:03:38
2018-02-11T17:03:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,457
cpp
#pragma once #include "FBullCowGame.h" #include <map> // To make syntax Unreal friendly. #define TMap std::map FBullCowGame::FBullCowGame() { Reset(); } int32 FBullCowGame::GetMaxTries() const { TMap <int32, int32> WordLengthToMaxTries { { 3,4 },{ 4,7 },{ 5,10 },{ 6,15 },{ 7,20 } }; return WordLengthToMaxTries[GetHiddenWordLength()]; } int32 FBullCowGame::GetCurrentTry() const { return MyCurrentTry; } int32 FBullCowGame::GetHiddenWordLength() const { return MyHiddenWord.length(); } bool FBullCowGame::IsGameWon() const { return bGameIsWon; } bool FBullCowGame::IsIsogram(FString Word) const { if (Word.length() <= 1) { return true; } TMap <char, bool> LetterSeen; for (auto Letter : Word) // "For each Letter in Word." { Letter = tolower(Letter); if (LetterSeen[Letter]) { return false; } else { LetterSeen[Letter] = true; } } // For special cases, e.g. when \0 in entered. return true; } bool FBullCowGame::IsLowerCase(FString Word) const { for (auto Letter : Word) { if (!islower(Letter)) { return false; } } // If only lowercase letters found. return true; } EGuessStatus FBullCowGame::CheckGuessIsValid(FString Guess) const { if (!IsIsogram(Guess)) { return EGuessStatus::Not_Isogram; } else if (!IsLowerCase(Guess)) { return EGuessStatus::Not_Lowercase; } else if (Guess.length() != GetHiddenWordLength()) { return EGuessStatus::Wrong_Length; } else { return EGuessStatus::Ok; } } void FBullCowGame::Reset() { // This must be an isogram. const FString HIDDEN_WORD = "plane"; MyHiddenWord = HIDDEN_WORD; MyCurrentTry = 1; bGameIsWon = false; return; } // Receives a valid guess, increments turn and returns count. FBullsCowsCount FBullCowGame::SubmitValidGuess(FString Guess) { MyCurrentTry++; FBullsCowsCount BullsCowsCount; // Loop through all letters in the hidden word. for (int32 HiddenWordChar = 0; HiddenWordChar < GetHiddenWordLength(); HiddenWordChar++) { // Compare letters against the guess. for (int32 GuessChar = 0; GuessChar < GetHiddenWordLength(); GuessChar++) { if (Guess[GuessChar] == MyHiddenWord[HiddenWordChar]) { // if they're in the same place if (HiddenWordChar == GuessChar) { BullsCowsCount.Bulls++; } else { BullsCowsCount.Cows++; } } } } if (BullsCowsCount.Bulls == GetHiddenWordLength()) { bGameIsWon = true; } return BullsCowsCount; }
[ "tim@hoffmannprojects.com" ]
tim@hoffmannprojects.com
6112a1e4255070ab18addfb391e569000c25b8ca
793c8848753f530aab28076a4077deac815af5ac
/src/dskphone/ui/t48/wifiui/src/modwifiui.cpp
d41de977e08d05bb6031d74a989b7eb5f7ecb10e
[]
no_license
Parantido/sipphone
4c1b9b18a7a6e478514fe0aadb79335e734bc016
f402efb088bb42900867608cc9ccf15d9b946d7d
refs/heads/master
2021-09-10T20:12:36.553640
2018-03-30T12:44:13
2018-03-30T12:44:13
263,628,242
1
0
null
2020-05-13T12:49:19
2020-05-13T12:49:18
null
UTF-8
C++
false
false
587
cpp
#include "wifi_inc.h" /************************************************************************/ /* 接口 : WifiUI_EnterBaseView() */ /* 功能 : 进入wifi列表界面 */ /* 参数说明 :无 */ /* 返回值 : 无 */ /************************************************************************/ void WifiUI_EnterBaseView() { SettingUI_OpenPage(SubMenuData("OpenSubPage(wifi)")); }
[ "rongxx@yealink.com" ]
rongxx@yealink.com
b91860ebf407535481d68d8e624715eba966f1a4
0d0e78c6262417fb1dff53901c6087b29fe260a0
/gaap/include/tencentcloud/gaap/v20180529/model/CreateDomainResponse.h
c2592f0391e428c47335632c7bbe978f541d6ace
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
1,538
h
/* * 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. */ #ifndef TENCENTCLOUD_GAAP_V20180529_MODEL_CREATEDOMAINRESPONSE_H_ #define TENCENTCLOUD_GAAP_V20180529_MODEL_CREATEDOMAINRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Gaap { namespace V20180529 { namespace Model { /** * CreateDomain返回参数结构体 */ class CreateDomainResponse : public AbstractModel { public: CreateDomainResponse(); ~CreateDomainResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); private: }; } } } } #endif // !TENCENTCLOUD_GAAP_V20180529_MODEL_CREATEDOMAINRESPONSE_H_
[ "zhiqiangfan@tencent.com" ]
zhiqiangfan@tencent.com
f5d5475fc021c542b0456416a648bb0480fcbb9b
54320ef64dd0548a5b5016feed14c606a5fd1e76
/Araksya_Hambaryan/Homework/C++/Homework_30_10_2015/Covapnya_Tner.cpp
96fa4543aeb5454b9b92e2134d156e61f4fce341
[]
no_license
ITC-Vanadzor/ITC-7
9859ebbd0d824d3a480ea281bbdb14edbb6a374e
d2bfcdc3a1faea4cdc1d7e555404445ac8768c66
refs/heads/master
2021-01-17T15:43:29.646485
2019-02-17T19:07:36
2019-02-17T19:07:36
44,699,731
0
4
null
2017-04-13T18:45:36
2015-10-21T19:38:34
JavaScript
UTF-8
C++
false
false
648
cpp
#include <iostream> #include <string> #include <cmath> // Voroshel te qani tun e gtnvum Armeni ev Ashoti tneri mijev, ete Ashoti tnic aj gtnvum e N tun, dzax M tun, isk Armeni tnic aj ev dzax gtnvum en havasar qanakutyamb tner int Nermucum (std::string Koxm) { int M=-1; while ((M < 0) || (M > 100)) { std::cout << "Ashoti tnic " << Koxm << " gtnvum e ( < 100) "; std::cin >> M; } return M; } int main () { int N = Nermucum ("dzax"); int M = Nermucum ("aj"); int MijankyalTner = fabs (N - M) /2 -1; std::cout << "Ashoti ev Armeni tneri mijev gtnvum e " << MijankyalTner << " tun" << std::endl; return 0; }
[ "araksyahambaryan@mail.ru" ]
araksyahambaryan@mail.ru
61ee5d90851bd65348143b768f217fc39d6587e2
d558f0774efbaefb198c4dc8287634f4550a1ae4
/Other test/Working_sensor_ping_with_LED_light_which_doesnt_timeout/Working_sensor_ping_with_LED_light_which_doesnt_timeout.ino
570eddfa1f8d62f6ab8340146bba9e66d8087e84
[]
no_license
grantstewart/Drawbot4000
7736add183167e6035c6b645255c0052886dadae
72b67a69421359c94a9f0accf085776758604a25
refs/heads/master
2021-01-10T10:57:21.863945
2016-01-11T09:37:59
2016-01-11T09:37:59
49,197,104
0
1
null
2016-01-11T09:37:59
2016-01-07T10:09:01
Arduino
UTF-8
C++
false
false
1,259
ino
// --------------------------------------------------------------------------- // Example NewPing library sketch that does a ping about 20 times per second. // --------------------------------------------------------------------------- #include <NewPing.h> #define TRIGGER_PIN A4 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN A5 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. int ledPin = 14; //define the pin that the LED is on void setup() { Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results. pinMode(ledPin, OUTPUT); } void loop() { delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. Serial.print("Ping: "); Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range) Serial.println("cm"); if(sonar.ping_cm()<10){ digitalWrite(ledPin, LOW); }else{ digitalWrite(ledPin, HIGH); } }
[ "grant.c.stewart@gmail.com" ]
grant.c.stewart@gmail.com
2dddedaede40c7d5c0af0d1f68ef0ea3449c6889
d52c9def5290aecb8b3eb20d0d7a71fc9df57cdc
/lintcode/LRU Cache.cpp
e9d77e94b5d4abaae57941af8f40319c4c9866bc
[]
no_license
glc12125/Algo
26091b8af6cd25029958fa794280ac15fb9e06e2
8b1649893ef4aefadcc1c312f38359464d3b7a18
refs/heads/master
2022-11-19T06:02:05.851206
2022-11-04T12:34:43
2022-11-04T12:34:43
73,620,928
2
1
null
null
null
null
UTF-8
C++
false
false
2,409
cpp
class LRUCache { private: struct Node { int m_key; int m_value; Node * m_prev; Node * m_next; Node(int key, int value) : m_key(key), m_value(value), m_prev(nullptr), m_next(nullptr) { } }; Node * m_recent; Node * m_stale; int m_totalSize; std::unordered_map<int, Node*> m_cache; void removeNode(Node* node) { Node * prev = node->m_prev; Node * next = node->m_next; if(prev != nullptr) { prev->m_next = next; } else { m_recent = next; } if(next != nullptr) { next->m_prev = prev; } else { m_stale = prev; } } void makeRecent(Node* node) { if(m_recent == nullptr) { m_stale = node; m_recent = node; //std::cout << "current recent: " << m_recent->m_key << "\n"; return; } node->m_next = m_recent; m_recent->m_prev = node; node->m_prev = nullptr; m_recent = node; if(m_stale == nullptr) m_stale = m_recent; //std::cout << "current recent: " << m_recent->m_key << "\n"; } public: /* * @param capacity: An integer */LRUCache(int capacity) { m_recent = nullptr; m_stale = nullptr; m_totalSize = capacity; } /* * @param key: An integer * @return: An integer */ int get(int key) { if(m_cache.count(key) > 0) { removeNode(m_cache[key]); makeRecent(m_cache[key]); return m_cache[key]->m_value; } return -1; } /* * @param key: An integer * @param value: An integer * @return: nothing */ void set(int key, int value) { //std::cout << "calling set: key " << key << ", value " << value << "\n"; if(m_cache.count(key) > 0) { removeNode(m_cache[key]); makeRecent(m_cache[key]); m_cache[key]->m_value = value; } else { if(m_cache.size() == m_totalSize) { //std::cout << "trying to set: " << key << "\n"; m_cache.erase(m_stale->m_key); removeNode(m_stale); } Node * newNode = new Node(key, value); m_cache[key] = newNode; makeRecent(newNode); } } };
[ "Liangchuan Gu" ]
Liangchuan Gu
0105152918275b0bb801ac492da589f300649220
8a093bd321895877ffcb8aedc4ac13488bb4962e
/and_operator.cpp
f9a906d1b5edc0f4cbc67ff1ef04154aae5cd1d2
[]
no_license
FreemanKCST/CS101-Week1
22c861cb8fc5ef856bb55f6f6c034114afcbb12c
7965193da44f21de572abcdd8697e9e75114359b
refs/heads/master
2020-06-04T15:47:56.101934
2019-06-16T10:13:49
2019-06-16T10:13:49
192,089,466
1
0
null
null
null
null
UTF-8
C++
false
false
837
cpp
// This program demonstrates the && logical operator. #include <iostream> using namespace std; int main() { char employed, // Currently employed, Y or N recentGrad; // Recent graduate, Y or N // Is the user employed and a recent graduate? cout << "Answer the following questions\n"; cout << "with either Y for Yes or N for No.\n"; cout << "Are you employed? "; cin >> employed; cout << "Have you graduated from college " << "in the past two years? "; cin >> recentGrad; // Determine the user's loan qualifications. if (employed == 'Y' && recentGrad == 'Y') { cout << "You qualify for the special " << "interest rate.\n"; } else { cout << "You must be employed and have\n" << "graduated from college in the\n" << "past two years to qualify.\n"; } return 0; }
[ "noreply@github.com" ]
FreemanKCST.noreply@github.com
00bfeb64e8a5ee94fbbd3d6e7ef316cc08576a60
f59dbe7f59c9090f347306f34c8c013d4efa0ba9
/WhateverGreen/kern_con.hpp
1de136f4f7cc2f42bf1a9d54f114b7a197127263
[ "BSD-3-Clause" ]
permissive
acidanthera/WhateverGreen
3657ac8ddc3c287dca119394b011a9a2a88f803b
1541f13a5f8c0e80b1f0869ef7e687319d092fa6
refs/heads/master
2023-08-16T12:10:57.253062
2023-08-13T10:08:45
2023-08-13T10:08:45
98,471,367
3,357
837
BSD-3-Clause
2023-07-15T12:29:28
2017-07-26T22:40:14
C++
UTF-8
C++
false
false
4,932
hpp
// // kern_con.hpp // WhateverGreen // // Copyright © 2017 vit9696. All rights reserved. // #ifndef kern_con_hpp #define kern_con_hpp #include <Headers/kern_util.hpp> #include <libkern/libkern.h> namespace RADConnectors { /** * Connectors from AMDSupport before 10.12 */ struct LegacyConnector { uint32_t type; uint32_t flags; uint16_t features; uint16_t priority; uint8_t transmitter; uint8_t encoder; uint8_t hotplug; uint8_t sense; }; /** * Connectors from AMDSupport since 10.12 */ struct ModernConnector { uint32_t type; uint32_t flags; uint16_t features; uint16_t priority; uint32_t reserved1; uint8_t transmitter; uint8_t encoder; uint8_t hotplug; uint8_t sense; uint32_t reserved2; }; /** * Internal atom connector struct since 10.13 */ struct AtomConnectorInfo { uint16_t *atomObject; uint16_t usConnObjectId; uint16_t usGraphicObjIds; uint8_t *hpdRecord; uint8_t *i2cRecord; }; /** * Opaque connector type for simplicity */ union Connector { LegacyConnector legacy; ModernConnector modern; static_assert(sizeof(LegacyConnector) == 16, "LegacyConnector has wrong size"); static_assert(sizeof(ModernConnector) == 24, "ModernConnector has wrong size"); /** * Assigns connector from one to another * * @param out destination connector * @param in source connector */ template <typename T, typename Y> static inline void assign(T &out, const Y &in) { memset(&out, 0, sizeof(T)); out.type = in.type; out.flags = in.flags; out.features = in.features; out.priority = in.priority; out.transmitter = in.transmitter; out.encoder = in.encoder; out.hotplug = in.hotplug; out.sense = in.sense; } }; /** * Connector types available in the drivers */ enum ConnectorType { ConnectorLVDS = 0x2, ConnectorDigitalDVI = 0x4, ConnectorSVID = 0x8, ConnectorVGA = 0x10, ConnectorDP = 0x400, ConnectorHDMI = 0x800, ConnectorAnalogDVI = 0x2000 }; /** * Prints connector type * * @param type connector type */ inline const char *printType(uint32_t type) { switch (type) { case ConnectorLVDS: return "LVDS"; case ConnectorDigitalDVI: return "DVI "; case ConnectorSVID: return "SVID"; case ConnectorVGA: return "VGA "; case ConnectorDP: return "DP "; case ConnectorHDMI: return "HDMI"; case ConnectorAnalogDVI: return "ADVI"; default: return "UNKN"; } } /** * Prints connector * * @param out out buffer * @param connector typed connector * * @return out */ template <typename T, size_t N> inline char *printConnector(char (&out)[N], T &connector) { snprintf(out, N, "type %08X (%s) flags %08X feat %04X pri %04X txmit %02X enc %02X hotplug %02X sense %02X", connector.type, printType(connector.type), connector.flags, connector.features, connector.priority, connector.transmitter, connector.encoder, connector.hotplug, connector.sense); return out; } /** * Is modern system * * @return true if modern connectors are used */ inline bool modern() { return getKernelVersion() >= KernelVersion::Sierra; } /** * Prints connectors * * @param con pointer to an array of legacy or modern connectors (depends on the kernel version) * @param num number of connectors in con */ inline void print(Connector *con, uint8_t num) { #ifdef DEBUG for (uint8_t i = 0; con && i < num; i++) { char tmp[192]; DBGLOG("con", "%u is %s", i, modern() ? printConnector(tmp, (&con->modern)[i]) : printConnector(tmp, (&con->legacy)[i])); } #endif } /** * Sanity check connector size * * @param size buffer size in bytes * @param num number of connectors * * @return true if connectors are in either legacy or modern format */ inline bool valid(uint32_t size, uint8_t num) { return (size % sizeof(ModernConnector) == 0 && size / sizeof(ModernConnector) == num) || (size % sizeof(LegacyConnector) == 0 && size / sizeof(LegacyConnector) == num); } /** * Copy new connectors * * @param out destination connectors * @param num number of copied connectors * @param in source connectors * @param size size of source connectors */ inline void copy(RADConnectors::Connector *out, uint8_t num, const RADConnectors::Connector *in, uint32_t size) { bool outModern = modern(); bool inModern = size % sizeof(ModernConnector) == 0 && size / sizeof(ModernConnector) == num; for (uint8_t i = 0; i < num; i++) { if (outModern) { if (inModern) Connector::assign((&out->modern)[i], (&in->modern)[i]); else Connector::assign((&out->modern)[i], (&in->legacy)[i]); } else { if (inModern) Connector::assign((&out->legacy)[i], (&in->modern)[i]); else Connector::assign((&out->legacy)[i], (&in->legacy)[i]); } } } }; #endif /* kern_con_hpp */
[ "vit9696@users.noreply.github.com" ]
vit9696@users.noreply.github.com
a8cc91d35b262e32eab3f7ad34e9e7ca9cde3822
898ea9483d57867eaeaed098e8c4788fd58bdb8f
/src/Parser.hpp
6a0051c3a9b7657bb034866dcd650d0a75a33344
[]
no_license
pavlovandy/Abstract_VM
0e0412cc49278c889116888396171cfcb7bc9303
d9085b6d63dbee9764b79e666804301ba79af016
refs/heads/master
2020-08-20T19:25:20.771197
2019-11-03T13:20:14
2019-11-03T13:20:14
216,058,125
0
0
null
null
null
null
UTF-8
C++
false
false
1,288
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Parser.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anri <anri@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/23 21:15:28 by anri #+# #+# */ /* Updated: 2019/10/28 16:38:08 by anri ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef ABSTRACT_VM_PARSER_HPP # define ABSTRACT_VM_PARSER_HPP # include <regex> # include <string> # include <vector> # include <ios> # include <iostream> # include "IOperand.hpp" # include <cstring> class Parser { public: void getMatches( const std::string & str, std::string & command, eOperandType & type, std::string &value ); eOperandType strToEnum( const std::string m ); }; #endif
[ "andrij0pawlov@gmail.com" ]
andrij0pawlov@gmail.com
ceee816ce1d9a6dedcdac4432b95a0c7e3cb3f8b
3fa5ce936093f7e1afabbb5c1bfce98385ca1206
/main/lsp/LSPPreprocessor.cc
099e6213e474133422408530092e3cec7bcfd7fa
[ "Apache-2.0" ]
permissive
landovsky/sorbet
ed67d501d9219dee49013b2910b9b1b6d3a4ec37
29a967a22cc8cfcccb3d6a502b9ccb99cace0f5c
refs/heads/master
2021-01-15T01:53:36.611535
2020-02-22T01:55:07
2020-02-22T01:55:07
242,838,884
0
0
Apache-2.0
2020-02-24T20:42:00
2020-02-24T20:41:59
null
UTF-8
C++
false
false
16,763
cc
#include "main/lsp/LSPPreprocessor.h" #include "absl/strings/match.h" #include "absl/strings/str_replace.h" #include "main/lsp/LSPOutput.h" #include "main/lsp/lsp.h" #include "main/lsp/notifications/notifications.h" #include "main/lsp/requests/requests.h" using namespace std; namespace sorbet::realmain::lsp { namespace { string readFile(string_view path, const FileSystem &fs) { try { return fs.readFile(path); } catch (FileNotFoundException e) { // Act as if file is completely empty. // NOTE: It is not appropriate to throw an error here. Sorbet does not differentiate between Watchman // updates that specify if a file has changed or has been deleted, so this is the 'golden path' for deleted // files. // TODO(jvilk): Use Tombstone files instead. return ""; } } } // namespace LSPPreprocessor::LSPPreprocessor(shared_ptr<LSPConfiguration> config, shared_ptr<absl::Mutex> taskQueueMutex, shared_ptr<TaskQueueState> taskQueue, u4 initialVersion) : config(move(config)), taskQueueMutex(std::move(taskQueueMutex)), taskQueue(move(taskQueue)), owner(this_thread::get_id()), nextVersion(initialVersion + 1) {} string_view LSPPreprocessor::getFileContents(string_view path) const { auto it = openFiles.find(path); if (it == openFiles.end()) { ENFORCE(false, "Editor sent a change request without a matching open request."); return string_view(); } return it->second->source(); } void LSPPreprocessor::mergeFileChanges() { taskQueueMutex->AssertHeld(); auto &logger = config->logger; // mergeFileChanges is the most expensive operation this thread performs while holding the mutex lock. Timer timeit(logger, "lsp.mergeFileChanges"); auto &pendingRequests = taskQueue->pendingTasks; const int originalSize = pendingRequests.size(); int requestsMergedCounter = 0; for (auto it = pendingRequests.begin(); it != pendingRequests.end();) { auto *olderEdit = dynamic_cast<SorbetWorkspaceEditTask *>(it->get()); it++; if (olderEdit == nullptr) { // Is not an edit. continue; } // See which newer requests we can merge. We want to merge them *backwards* into olderEdit so we can complete // merging (and erase merged edits) in a single loop over the queue. while (it != pendingRequests.end()) { auto &task = *it; auto *newerEdit = dynamic_cast<SorbetWorkspaceEditTask *>(task.get()); if (newerEdit == nullptr) { if (task->isDelayable()) { ++it; continue; } else { // Stop merging edits into olderEdit if the pointed-to message is neither an edit nor delayable break; } } olderEdit->mergeNewer(*newerEdit); // Delete the update we just merged and move on to next item. it = pendingRequests.erase(it); requestsMergedCounter++; } } ENFORCE(pendingRequests.size() + requestsMergedCounter == originalSize); } bool LSPPreprocessor::ensureInitialized(LSPMethod method, const LSPMessage &msg) const { // The following whitelisted methods are OK to run prior to LSP server initialization. // TODO(jvilk): Could encode this in each LSPTask. if (config->isInitialized() || method == LSPMethod::Initialize || method == LSPMethod::Initialized || method == LSPMethod::Exit || method == LSPMethod::Shutdown || method == LSPMethod::SorbetError || method == LSPMethod::SorbetFence) { return true; } config->logger->error("Serving request before got an Initialize & Initialized handshake from IDE"); if (!msg.isNotification()) { auto id = msg.id().value_or(0); auto response = make_unique<ResponseMessage>("2.0", id, msg.method()); response->error = make_unique<ResponseError>((int)LSPErrorCodes::ServerNotInitialized, "IDE did not initialize Sorbet correctly. No requests should " "be made before Initialize & Initialized have been completed"); config->output->write(move(response)); } return false; } unique_ptr<LSPTask> LSPPreprocessor::getTaskForMessage(LSPMessage &msg) { if (msg.isResponse()) { // We currently send no requests to the client, so we don't expect any response messages. return make_unique<SorbetErrorTask>( *config, make_unique<SorbetErrorParams>((int)LSPErrorCodes::MethodNotFound, "Unexpected response message")); } const LSPMethod method = msg.method(); if (msg.isNotification()) { auto &rawParams = msg.asNotification().params; switch (method) { case LSPMethod::TextDocumentDidOpen: { auto &params = get<unique_ptr<DidOpenTextDocumentParams>>(rawParams); auto newParams = canonicalizeEdits(nextVersion++, move(params)); return make_unique<SorbetWorkspaceEditTask>(*config, move(newParams)); } case LSPMethod::TextDocumentDidClose: { auto &params = get<unique_ptr<DidCloseTextDocumentParams>>(rawParams); auto newParams = canonicalizeEdits(nextVersion++, move(params)); return make_unique<SorbetWorkspaceEditTask>(*config, move(newParams)); } case LSPMethod::TextDocumentDidChange: { auto &params = get<unique_ptr<DidChangeTextDocumentParams>>(rawParams); auto newParams = canonicalizeEdits(nextVersion++, move(params)); return make_unique<SorbetWorkspaceEditTask>(*config, move(newParams)); } case LSPMethod::SorbetWatchmanFileChange: { auto &params = get<unique_ptr<WatchmanQueryResponse>>(rawParams); auto newParams = canonicalizeEdits(nextVersion++, move(params)); return make_unique<SorbetWorkspaceEditTask>(*config, move(newParams)); } case LSPMethod::SorbetWorkspaceEdit: return make_unique<SorbetWorkspaceEditTask>( *config, move(get<unique_ptr<SorbetWorkspaceEditParams>>(rawParams))); case LSPMethod::$CancelRequest: return make_unique<CancelRequestTask>(*config, move(get<unique_ptr<CancelParams>>(rawParams))); case LSPMethod::Initialized: return make_unique<InitializedTask>(*config); case LSPMethod::Exit: return make_unique<ExitTask>(*config, 0); case LSPMethod::SorbetFence: return make_unique<SorbetFenceTask>(*config, get<int>(rawParams)); case LSPMethod::PAUSE: return make_unique<SorbetPauseTask>(*config); case LSPMethod::RESUME: return make_unique<SorbetResumeTask>(*config); case LSPMethod::SorbetError: return make_unique<SorbetErrorTask>(*config, move(get<unique_ptr<SorbetErrorParams>>(rawParams))); default: return make_unique<SorbetErrorTask>( *config, make_unique<SorbetErrorParams>( (int)LSPErrorCodes::MethodNotFound, fmt::format("Unknown notification method: {}", convertLSPMethodToString(method)))); } } else if (msg.isRequest()) { auto &requestMessage = msg.asRequest(); // asRequest() should guarantee the presence of an ID. ENFORCE(msg.id()); auto id = *msg.id(); auto &rawParams = requestMessage.params; switch (method) { case LSPMethod::TextDocumentDefinition: return make_unique<DefinitionTask>(*config, id, move(get<unique_ptr<TextDocumentPositionParams>>(rawParams))); case LSPMethod::Initialize: return make_unique<InitializeTask>(*config, id, move(get<unique_ptr<InitializeParams>>(rawParams))); case LSPMethod::TextDocumentDocumentHighlight: return make_unique<DocumentHighlightTask>(*config, id, move(get<unique_ptr<TextDocumentPositionParams>>(rawParams))); case LSPMethod::TextDocumentDocumentSymbol: return make_unique<DocumentSymbolTask>(*config, id, move(get<unique_ptr<DocumentSymbolParams>>(rawParams))); case LSPMethod::TextDocumentHover: return make_unique<HoverTask>(*config, id, move(get<unique_ptr<TextDocumentPositionParams>>(rawParams))); case LSPMethod::TextDocumentTypeDefinition: return make_unique<TypeDefinitionTask>(*config, id, move(get<unique_ptr<TextDocumentPositionParams>>(rawParams))); case LSPMethod::WorkspaceSymbol: return make_unique<WorkspaceSymbolsTask>(*config, id, move(get<unique_ptr<WorkspaceSymbolParams>>(rawParams))); case LSPMethod::TextDocumentCompletion: return make_unique<CompletionTask>(*config, id, move(get<unique_ptr<CompletionParams>>(rawParams))); case LSPMethod::TextDocumentCodeAction: return make_unique<CodeActionTask>(*config, id, move(get<unique_ptr<CodeActionParams>>(rawParams))); case LSPMethod::TextDocumentSignatureHelp: return make_unique<SignatureHelpTask>(*config, id, move(get<unique_ptr<TextDocumentPositionParams>>(rawParams))); case LSPMethod::TextDocumentReferences: return make_unique<ReferencesTask>(*config, id, move(get<unique_ptr<ReferenceParams>>(rawParams))); case LSPMethod::SorbetReadFile: return make_unique<SorbetReadFileTask>(*config, id, move(get<unique_ptr<TextDocumentIdentifier>>(rawParams))); case LSPMethod::Shutdown: return make_unique<ShutdownTask>(*config, id); case LSPMethod::SorbetError: return make_unique<SorbetErrorTask>(*config, move(get<unique_ptr<SorbetErrorParams>>(rawParams)), id); default: return make_unique<SorbetErrorTask>( *config, make_unique<SorbetErrorParams>( (int)LSPErrorCodes::MethodNotFound, fmt::format("Unknown request method: {}", convertLSPMethodToString(method))), id); } } else { // This should be impossible. Exception::raise("Message isn't a request, notification, or response."); } } bool LSPPreprocessor::cancelRequest(const CancelParams &params) { absl::MutexLock lock(taskQueueMutex.get()); auto &pendingTasks = taskQueue->pendingTasks; for (auto it = pendingTasks.begin(); it != pendingTasks.end(); ++it) { auto &current = **it; if (current.cancel(params.id)) { pendingTasks.erase(it); // Now that we've removed this request, we may be able to merge more edits together. mergeFileChanges(); return true; } } // It's too late; we have either already processed the request or are currently processing it. Swallow cancellation // and ignore. return false; } void LSPPreprocessor::pause() { absl::MutexLock lock(taskQueueMutex.get()); ENFORCE(!taskQueue->paused); config->logger->error("Pausing"); taskQueue->paused = true; } void LSPPreprocessor::resume() { absl::MutexLock lock(taskQueueMutex.get()); ENFORCE(taskQueue->paused); config->logger->error("Resuming"); taskQueue->paused = false; } void LSPPreprocessor::exit(int exitCode) { absl::MutexLock lock(taskQueueMutex.get()); if (!taskQueue->terminate) { taskQueue->terminate = true; taskQueue->errorCode = exitCode; } } void LSPPreprocessor::preprocessAndEnqueue(unique_ptr<LSPMessage> msg) { ENFORCE(owner == this_thread::get_id()); if (msg->isResponse()) { // We ignore responses. return; } const LSPMethod method = msg->method(); if (!ensureInitialized(method, *msg)) { // msg is invalid. Error sent to client. return; } auto task = getTaskForMessage(*msg); task->latencyTimer = move(msg->latencyTimer); { Timer timeit(config->logger, "LSPTask::Preprocess"); timeit.setTag("method", task->methodString()); task->preprocess(*this); } if (task->finalPhase() != LSPTask::Phase::PREPROCESS) { // Enqueue task to be processed on processing thread. absl::MutexLock lock(taskQueueMutex.get()); const bool isEdit = task->method == LSPMethod::SorbetWorkspaceEdit; taskQueue->pendingTasks.push_back(move(task)); if (isEdit) { // Only edits can be merged; avoid looping over the queue on every request. mergeFileChanges(); } } else { prodCategoryCounterInc("lsp.messages.processed", task->methodString()); } } unique_ptr<SorbetWorkspaceEditParams> LSPPreprocessor::canonicalizeEdits(u4 v, unique_ptr<DidChangeTextDocumentParams> changeParams) { auto edit = make_unique<SorbetWorkspaceEditParams>(); edit->epoch = v; edit->sorbetCancellationExpected = changeParams->sorbetCancellationExpected.value_or(false); edit->sorbetPreemptionsExpected = changeParams->sorbetPreemptionsExpected.value_or(0); string_view uri = changeParams->textDocument->uri; if (config->isUriInWorkspace(uri)) { string localPath = config->remoteName2Local(uri); if (!config->isFileIgnored(localPath)) { string fileContents = changeParams->getSource(getFileContents(localPath)); auto file = make_shared<core::File>(move(localPath), move(fileContents), core::File::Type::Normal, v); edit->updates.push_back(file); openFiles[localPath] = move(file); } } return edit; } unique_ptr<SorbetWorkspaceEditParams> LSPPreprocessor::canonicalizeEdits(u4 v, unique_ptr<DidOpenTextDocumentParams> openParams) { auto edit = make_unique<SorbetWorkspaceEditParams>(); edit->epoch = v; string_view uri = openParams->textDocument->uri; if (config->isUriInWorkspace(uri)) { string localPath = config->remoteName2Local(uri); if (!config->isFileIgnored(localPath)) { auto file = make_shared<core::File>(move(localPath), move(openParams->textDocument->text), core::File::Type::Normal, v); edit->updates.push_back(file); openFiles[localPath] = move(file); } } return edit; } unique_ptr<SorbetWorkspaceEditParams> LSPPreprocessor::canonicalizeEdits(u4 v, unique_ptr<DidCloseTextDocumentParams> closeParams) { auto edit = make_unique<SorbetWorkspaceEditParams>(); edit->epoch = v; string_view uri = closeParams->textDocument->uri; if (config->isUriInWorkspace(uri)) { string localPath = config->remoteName2Local(uri); if (!config->isFileIgnored(localPath)) { openFiles.erase(localPath); // Use contents of file on disk. edit->updates.push_back(make_shared<core::File>(move(localPath), readFile(localPath, *config->opts.fs), core::File::Type::Normal, v)); } } return edit; } unique_ptr<SorbetWorkspaceEditParams> LSPPreprocessor::canonicalizeEdits(u4 v, unique_ptr<WatchmanQueryResponse> queryResponse) const { auto edit = make_unique<SorbetWorkspaceEditParams>(); edit->epoch = v; for (auto file : queryResponse->files) { // Don't append rootPath if it is empty. string localPath = !config->rootPath.empty() ? absl::StrCat(config->rootPath, "/", file) : file; // Editor contents supercede file system updates. if (!config->isFileIgnored(localPath) && !openFiles.contains(localPath)) { edit->updates.push_back(make_shared<core::File>(move(localPath), readFile(localPath, *config->opts.fs), core::File::Type::Normal, v)); } } return edit; } } // namespace sorbet::realmain::lsp
[ "noreply@github.com" ]
landovsky.noreply@github.com
b7d35281d44166be0e2f1d51f7fd9abb5c0e285c
c56a7c342ef0ddd318104201acd5f4ed2a3f9c58
/src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_digest.cpp
54354b21fe331a4609c16f4f5a2616c4adea6988
[ "MIT" ]
permissive
ivandrofly/corefx
4ce40dc55add785e3e7b3c29b3c94ae2f5ad40d8
2f6d756400385df488132f2cb99d83c553baf2ab
refs/heads/master
2021-01-13T10:29:26.571458
2016-10-28T12:43:46
2016-10-28T12:43:46
72,207,236
0
0
NOASSERTION
2019-08-30T10:09:14
2016-10-28T12:55:06
C#
UTF-8
C++
false
false
4,132
cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal_digest.h" #include <CommonCrypto/CommonCrypto.h> #include <CommonCrypto/CommonDigest.h> #include <assert.h> struct digest_ctx_st { PAL_HashAlgorithm algorithm; // This 32-bit field is required for alignment, // but it's also handy for remembering how big the final buffer is. int32_t cbDigest; union { CC_MD5_CTX md5; CC_SHA1_CTX sha1; CC_SHA256_CTX sha256; CC_SHA512_CTX sha384; CC_SHA512_CTX sha512; } d; }; extern "C" void AppleCryptoNative_DigestFree(DigestCtx* pDigest) { if (pDigest != nullptr) { free(pDigest); } } extern "C" DigestCtx* AppleCryptoNative_DigestCreate(PAL_HashAlgorithm algorithm, int32_t* pcbDigest) { if (pcbDigest == nullptr) return nullptr; DigestCtx* digestCtx = reinterpret_cast<DigestCtx*>(malloc(sizeof(DigestCtx))); digestCtx->algorithm = algorithm; switch (algorithm) { case PAL_MD5: *pcbDigest = CC_MD5_DIGEST_LENGTH; CC_MD5_Init(&digestCtx->d.md5); break; case PAL_SHA1: *pcbDigest = CC_SHA1_DIGEST_LENGTH; CC_SHA1_Init(&digestCtx->d.sha1); break; case PAL_SHA256: *pcbDigest = CC_SHA256_DIGEST_LENGTH; CC_SHA256_Init(&digestCtx->d.sha256); break; case PAL_SHA384: *pcbDigest = CC_SHA384_DIGEST_LENGTH; CC_SHA384_Init(&digestCtx->d.sha384); break; case PAL_SHA512: *pcbDigest = CC_SHA512_DIGEST_LENGTH; CC_SHA512_Init(&digestCtx->d.sha512); break; default: *pcbDigest = -1; free(digestCtx); return nullptr; } digestCtx->cbDigest = *pcbDigest; return digestCtx; } extern "C" int AppleCryptoNative_DigestUpdate(DigestCtx* ctx, uint8_t* pBuf, int32_t cbBuf) { if (cbBuf == 0) return 1; if (ctx == nullptr || pBuf == nullptr) return -1; CC_LONG bufSize = static_cast<CC_LONG>(cbBuf); switch (ctx->algorithm) { case PAL_MD5: return CC_MD5_Update(&ctx->d.md5, pBuf, bufSize); case PAL_SHA1: return CC_SHA1_Update(&ctx->d.sha1, pBuf, bufSize); case PAL_SHA256: return CC_SHA256_Update(&ctx->d.sha256, pBuf, bufSize); case PAL_SHA384: return CC_SHA384_Update(&ctx->d.sha384, pBuf, bufSize); case PAL_SHA512: return CC_SHA512_Update(&ctx->d.sha512, pBuf, bufSize); default: return -1; } } extern "C" int AppleCryptoNative_DigestFinal(DigestCtx* ctx, uint8_t* pOutput, int32_t cbOutput) { if (ctx == nullptr || pOutput == nullptr || cbOutput < ctx->cbDigest) return -1; int ret = 0; switch (ctx->algorithm) { case PAL_MD5: ret = CC_MD5_Final(pOutput, &ctx->d.md5); break; case PAL_SHA1: ret = CC_SHA1_Final(pOutput, &ctx->d.sha1); break; case PAL_SHA256: ret = CC_SHA256_Final(pOutput, &ctx->d.sha256); break; case PAL_SHA384: ret = CC_SHA384_Final(pOutput, &ctx->d.sha384); break; case PAL_SHA512: ret = CC_SHA512_Final(pOutput, &ctx->d.sha512); break; default: ret = -1; break; } if (ret != 1) { return ret; } switch (ctx->algorithm) { case PAL_MD5: return CC_MD5_Init(&ctx->d.md5); case PAL_SHA1: return CC_SHA1_Init(&ctx->d.sha1); case PAL_SHA256: return CC_SHA256_Init(&ctx->d.sha256); case PAL_SHA384: return CC_SHA384_Init(&ctx->d.sha384); case PAL_SHA512: return CC_SHA512_Init(&ctx->d.sha512); default: assert(false); return -2; } }
[ "jbarton@microsoft.com" ]
jbarton@microsoft.com
c0e86139145da8b3239b31d372922d4c38894187
2c81b2159d5b6d1c3234df031b8055eb7f5f30a2
/src/application/app_yolo.cpp
6857d8ce324972de1faaa17188733802c50133f4
[]
no_license
zsffuture/tensorRT_Pro
f0fa73052e83974f0555f06fd7163eac0a8bd1ec
806ec11b7065dc3e3d8f33dd56016c65e32a74c1
refs/heads/main
2023-09-05T19:01:34.413991
2021-11-22T03:16:21
2021-11-22T03:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,901
cpp
#include <builder/trt_builder.hpp> #include <infer/trt_infer.hpp> #include <common/ilogger.hpp> #include "app_yolo/yolo.hpp" #include "app_yolo/multi_gpu.hpp" using namespace std; static const char* cocolabels[] = { "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" }; bool requires(const char* name); static void append_to_file(const string& file, const string& data){ FILE* f = fopen(file.c_str(), "a+"); if(f == nullptr){ INFOE("Open %s failed.", file.c_str()); return; } fprintf(f, "%s\n", data.c_str()); fclose(f); } static void inference_and_performance(int deviceid, const string& engine_file, TRT::Mode mode, Yolo::Type type, const string& model_name){ auto engine = Yolo::create_infer( engine_file, // engine file type, // yolo type, Yolo::Type::V5 / Yolo::Type::X deviceid, // gpu id 0.25f, // confidence threshold 0.45f, // nms threshold Yolo::NMSMethod::FastGPU, // NMS method, fast GPU / CPU 1024, // max objects false // preprocess use multi stream ); if(engine == nullptr){ INFOE("Engine is nullptr"); return; } auto files = iLogger::find_files("inference", "*.jpg;*.jpeg;*.png;*.gif;*.tif"); vector<cv::Mat> images; for(int i = 0; i < files.size(); ++i){ auto image = cv::imread(files[i]); images.emplace_back(image); } // warmup vector<shared_future<Yolo::BoxArray>> boxes_array; for(int i = 0; i < 10; ++i) boxes_array = engine->commits(images); boxes_array.back().get(); boxes_array.clear(); ///////////////////////////////////////////////////////// const int ntest = 100; auto begin_timer = iLogger::timestamp_now_float(); for(int i = 0; i < ntest; ++i) boxes_array = engine->commits(images); // wait all result boxes_array.back().get(); float inference_average_time = (iLogger::timestamp_now_float() - begin_timer) / ntest / images.size(); auto type_name = Yolo::type_name(type); auto mode_name = TRT::mode_string(mode); INFO("%s[%s] average: %.2f ms / image, FPS: %.2f", engine_file.c_str(), type_name, inference_average_time, 1000 / inference_average_time); append_to_file("perf.result.log", iLogger::format("%s,%s,%s,%f", model_name.c_str(), type_name, mode_name, inference_average_time)); string root = iLogger::format("%s_%s_%s_result", model_name.c_str(), type_name, mode_name); iLogger::rmtree(root); iLogger::mkdir(root); for(int i = 0; i < boxes_array.size(); ++i){ auto& image = images[i]; auto boxes = boxes_array[i].get(); for(auto& obj : boxes){ uint8_t b, g, r; tie(b, g, r) = iLogger::random_color(obj.class_label); cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(b, g, r), 5); auto name = cocolabels[obj.class_label]; auto caption = iLogger::format("%s %.2f", name, obj.confidence); int width = cv::getTextSize(caption, 0, 1, 2, nullptr).width + 10; cv::rectangle(image, cv::Point(obj.left-3, obj.top-33), cv::Point(obj.left + width, obj.top), cv::Scalar(b, g, r), -1); cv::putText(image, caption, cv::Point(obj.left, obj.top-5), 0, 1, cv::Scalar::all(0), 2, 16); } string file_name = iLogger::file_name(files[i], false); string save_path = iLogger::format("%s/%s.jpg", root.c_str(), file_name.c_str()); INFO("Save to %s, %d object, average time %.2f ms", save_path.c_str(), boxes.size(), inference_average_time); cv::imwrite(save_path, image); } engine.reset(); } static void test(Yolo::Type type, TRT::Mode mode, const string& model){ int deviceid = 0; auto mode_name = TRT::mode_string(mode); TRT::set_device(deviceid); auto int8process = [=](int current, int count, const vector<string>& files, shared_ptr<TRT::Tensor>& tensor){ INFO("Int8 %d / %d", current, count); for(int i = 0; i < files.size(); ++i){ auto image = cv::imread(files[i]); Yolo::image_to_tensor(image, tensor, type, i); } }; const char* name = model.c_str(); INFO("===================== test %s %s %s ==================================", Yolo::type_name(type), mode_name, name); if(not requires(name)) return; string onnx_file = iLogger::format("%s.onnx", name); string model_file = iLogger::format("%s.%s.trtmodel", name, mode_name); int test_batch_size = 16; if(not iLogger::exists(model_file)){ TRT::compile( mode, // FP32、FP16、INT8 test_batch_size, // max batch size onnx_file, // source model_file, // save to {}, int8process, "inference" ); } inference_and_performance(deviceid, model_file, mode, type, name); } void multi_gpu_test(){ vector<int> devices{0, 1, 2}; auto multi_gpu_infer = Yolo::create_multi_gpu_infer( "yolov5s-6.0.FP32.trtmodel", Yolo::Type::V5, devices ); auto files = iLogger::find_files("inference", "*.jpg"); #pragma omp parallel for num_threads(devices.size()) for(int i = 0; i < devices.size(); ++i){ auto image = cv::imread(files[i]); for(int j = 0; j < 1000; ++j){ multi_gpu_infer->commit(image).get(); } } INFO("Done"); } int app_yolo(){ //test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5s"); test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5m"); // multi_gpu_test(); //iLogger::set_log_level(iLogger::LogLevel::Debug); //test(Yolo::Type::X, TRT::Mode::FP32, "yolox_s"); //iLogger::set_log_level(iLogger::LogLevel::Info); // test(Yolo::Type::X, TRT::Mode::FP32, "yolox_x"); // test(Yolo::Type::X, TRT::Mode::FP32, "yolox_l"); // test(Yolo::Type::X, TRT::Mode::FP32, "yolox_m"); // test(Yolo::Type::X, TRT::Mode::FP32, "yolox_s"); // test(Yolo::Type::X, TRT::Mode::FP16, "yolox_x"); // test(Yolo::Type::X, TRT::Mode::FP16, "yolox_l"); // test(Yolo::Type::X, TRT::Mode::FP16, "yolox_m"); // test(Yolo::Type::X, TRT::Mode::FP16, "yolox_s"); // test(Yolo::Type::X, TRT::Mode::INT8, "yolox_x"); // test(Yolo::Type::X, TRT::Mode::INT8, "yolox_l"); // test(Yolo::Type::X, TRT::Mode::INT8, "yolox_m"); // test(Yolo::Type::X, TRT::Mode::INT8, "yolox_s"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5x6"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5l6"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5m6"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5s6"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5x"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5l"); // test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5m"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5x6"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5l6"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5m6"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5s6"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5x"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5l"); // test(Yolo::Type::V5, TRT::Mode::FP16, "yolov5m"); //test(Yolo::Type::V5, TRT::Mode::FP32, "yolov5s"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5x6"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5l6"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5m6"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5s6"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5x"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5l"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5m"); // test(Yolo::Type::V5, TRT::Mode::INT8, "yolov5s"); return 0; }
[ "dujw@deepblueai.com" ]
dujw@deepblueai.com
3950d4abb5f57c315055439a26ab9a2519190049
a679dba6ef0364962b94ed65d0caad1a88da6c43
/OrginalServerCode/OrginalCode/labixiaoxin/ACE_wrappers/examples/Service_Configurator/IPC-tests/server/Handle_L_FIFO.inl
c07f7f2ef35e04b444f95334f314280d3e285ed4
[]
no_license
w5762847/Learn
7f84933fe664e6cf52089a9f4b9140fca8b9a783
a5494181ea791fd712283fa8e78ca0287bf05318
refs/heads/master
2020-08-27T05:43:35.496579
2016-12-02T12:16:12
2016-12-02T12:16:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,543
inl
/* -*- C++ -*- */ // $Id: Handle_L_FIFO.inl 91813 2010-09-17 07:52:52Z johnnyw $ #include "ace/Get_Opt.h" #include "ace/Truncate.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_string.h" #include "ace/OS_NS_stropts.h" #include "ace/OS_NS_unistd.h" ACE_INLINE Handle_L_FIFO::Handle_L_FIFO (void) { } ACE_INLINE int Handle_L_FIFO::open (const ACE_TCHAR *rendezvous_fifo) { if (this->ACE_FIFO_Recv_Msg::open (rendezvous_fifo) == -1) return -1; else return 0; } ACE_INLINE int Handle_L_FIFO::info (ACE_TCHAR **strp, size_t length) const { ACE_TCHAR buf[BUFSIZ]; const ACE_TCHAR *rendezvous_fifo; this->get_local_addr (rendezvous_fifo); ACE_OS::strcpy (buf, rendezvous_fifo); ACE_OS::strcat (buf, ACE_TEXT(" # tests local ACE_FIFO\n")); if (*strp == 0 && (*strp = ACE_OS::strdup (buf)) == 0) { return -1; } else { ACE_OS::strncpy (*strp, buf, length); } return ACE_Utils::truncate_cast<int> (ACE_OS::strlen (buf)); } ACE_INLINE int Handle_L_FIFO::init (int argc, ACE_TCHAR *argv[]) { const ACE_TCHAR *rendezvous_fifo = Handle_L_FIFO::DEFAULT_RENDEZVOUS; ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("r:"), 0); for (int c; (c = get_opt ()) != -1; ) switch (c) { case 'r': rendezvous_fifo = get_opt.opt_arg (); break; default: break; } ACE_OS::unlink (rendezvous_fifo); if (this->open (rendezvous_fifo) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("open")), -1); else if (ACE_Reactor::instance ()->register_handler (this, ACE_Event_Handler::READ_MASK) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("registering service with ACE_Reactor")), -1); return 0; } ACE_INLINE int Handle_L_FIFO::fini (void) { return ACE_Reactor::instance ()->remove_handler (this, ACE_Event_Handler::ACCEPT_MASK); } ACE_INLINE ACE_HANDLE Handle_L_FIFO::get_handle (void) const { return this->ACE_FIFO::get_handle (); } ACE_INLINE int Handle_L_FIFO::handle_input (ACE_HANDLE) { char buf[PIPE_BUF]; ACE_Str_Buf msg (buf, 0, sizeof buf); /* Accept communication requests */ if (this->recv (msg) == -1) return -1; else ACE_OS::write (ACE_STDOUT, (const char *) msg.buf, (int) msg.len); return 0; } ACE_INLINE int Handle_L_FIFO::handle_close (ACE_HANDLE, ACE_Reactor_Mask) { return this->ACE_FIFO::remove (); }
[ "flyer_son@126.com" ]
flyer_son@126.com
666e9e3dbf1023a0a2bd322b9c6a9897c4f7341c
e8f97f496935d90f841f40a6292a0a24f0877aa5
/include/shader.h
24780db3e1eedf27d0be2ad8c11ae037212c4b94
[ "MIT" ]
permissive
johnfredcee/meistravimas
65d81609bc798c732748f6f6e9db38341063d5ec
4ee3168518525db0d3eddde5008115fc874dc249
refs/heads/master
2021-05-25T09:44:38.453184
2020-08-02T13:42:27
2020-08-02T13:42:27
31,008,802
0
0
null
null
null
null
UTF-8
C++
false
false
289
h
#ifndef SHADER_H #define SHADER_H namespace venk { class Program; class Shader { friend class Program; private: Sint32 shaderOk; Uint32 shader; public: Shader(GLenum type, const std::string& filename); ~Shader(); bool isValid() const; }; } #endif
[ "johnc@yagc.ndo.co.uk" ]
johnc@yagc.ndo.co.uk
de97ff7eb8216606acceb135203a53b9690b8764
ad54adee9a3300a34d8704c1f5d21f92260e2b9a
/src/IntelligentMaze/comparelabel.cpp
f1708f489480e067b63b731f44d686d03a052f01
[]
no_license
bigchestnut/IntelligentMaze
04bb8846ce7289414f3a177560799694759a8c0f
30c1ab1271efd23afb26f8574688ddc98baa1748
refs/heads/master
2021-01-11T20:19:23.734073
2017-06-04T15:00:03
2017-06-04T15:00:03
79,089,904
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
#include "comparelabel.h" CompareLabel::CompareLabel(QWidget *parent) : QWidget(parent) ,mainLayout(new QVBoxLayout()) ,m_sliderLayout(new QHBoxLayout()) ,m_sliderLabel(new QLabel(tr("单步速度:"))) ,m_slowLabel(new QLabel(tr("慢"))) ,m_fastLabel(new QLabel(tr("快"))) ,m_slider(new QSlider(Qt::Horizontal)) { mazeWindow = MazeWindow::getInstance(); m_slider->setRange(10,2000); m_slider->setValue(50); m_sliderLayout->addWidget(m_fastLabel); m_sliderLayout->addWidget(m_slider); m_sliderLayout->addWidget(m_slowLabel); mainLayout->addWidget(m_sliderLabel,1); mainLayout->addLayout(m_sliderLayout, 1); this->setLayout(mainLayout); connect(m_slider, SIGNAL(valueChanged(int)),mazeWindow, SLOT(setStepTime(int))); }
[ "lqq604350132@outlook.com" ]
lqq604350132@outlook.com
6c2d660584303c5a88aaeadbed805da451d94b1f
ce3f8464ef9eca19f27b9548b74f710b1b5ec0ca
/src/shaders/shadow_shader.cc
a812c3a518dcbc8efa427984a726d4ea855c7fcb
[]
no_license
marla396/CubeExplorer
e1ac69df657dd64569ee371f4052104297b47ccd
4279b3fa9d6b38848617893fa62fce98a88558bf
refs/heads/master
2020-04-04T11:00:03.110169
2018-12-13T16:07:22
2018-12-13T16:07:22
155,875,154
1
0
null
null
null
null
UTF-8
C++
false
false
1,738
cc
#include <string> #include "shaders/shadow_shader.h" ShadowShader::ShadowShader(Shader* parent) : ExtensionShader(parent){ } ShadowShader::~ShadowShader() { } void ShadowShader::upload_shadow_maps(int first) const { for (int i = 0; i < SHADOW_CASCADES; i++) { m_parent->upload_uniform(m_shadow_map_locations[i], first + i); } } void ShadowShader::upload_shadow_transforms(const std::shared_ptr<Light>& light) const { for (int i = 0; i < SHADOW_CASCADES; i++) { m_parent->upload_uniform(m_shadow_transform_locations[i], light->get_transform_matrix(i)); } } void ShadowShader::upload_shadow_cascade_end(const Camera& camera, const std::shared_ptr<Light>& light) const { for (int i = 0; i < SHADOW_CASCADES; i++) { m_parent->upload_uniform(m_shadow_cascade_end_locations[i], light->get_shadow_cascade_end(i) / camera.get_far()); } } void ShadowShader::upload_view_matrix(const glm::mat4& matrix) const { m_parent->upload_uniform(m_view_matrix_location, matrix); } void ShadowShader::upload_projection_depth(const glm::vec2& projection_depth) const { m_parent->upload_uniform(m_projection_depth_location, projection_depth); } void ShadowShader::get_uniform_locations() { for (int i = 0; i < SHADOW_CASCADES; i++) { m_shadow_transform_locations[i] = m_parent->get_uniform_location("shadow_transforms[" + std::to_string(i) + "]"); m_shadow_map_locations[i] = m_parent->get_uniform_location("shadow_maps[" + std::to_string(i) + "]"); m_shadow_cascade_end_locations[i] = m_parent->get_uniform_location("shadow_cascade_end[" + std::to_string(i) + "]"); } m_view_matrix_location = m_parent->get_uniform_location("view_matrix"); m_projection_depth_location = m_parent->get_uniform_location("projection_depth"); }
[ "martino_7878@hotmail.com" ]
martino_7878@hotmail.com
878c3a94e927ac9e9e7fa4568b80ab71bcef213b
d59dc968b8eebea1fb13e87f04aec569f8761aaa
/src/slVector.cpp
c3dc77ed70fb2c83038660687d46bb8e7982a0b7
[]
no_license
haimasree/particleskinner
ab27074d262a862ca98cd09a662231518dc0a946
4e0451814e3d9c81017303e644129c7baad8176e
refs/heads/master
2021-01-24T08:49:32.765783
2018-04-11T12:53:28
2018-04-11T12:53:28
122,997,192
3
0
null
null
null
null
UTF-8
C++
false
false
2,818
cpp
// Copyright (c) 2011, Regents of the University of Utah // Copyright (c) 2003-2005, Regents of the University of California. // 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 "slVector.H" #include "slUtil.H" using std::istream; using std::ostream; using std::ios; //------------------------------------------------------------------- istream &operator>>(istream &strm,SlVector3 &v) { ios::fmtflags orgFlags = strm.setf(ios::skipws); eatChar('[',strm); strm >> v[0]; eatChar(',',strm); strm >> v[1]; eatChar(',',strm); strm >> v[2]; eatChar(']',strm); strm.flags(orgFlags); return strm; } ostream &operator<<(ostream &strm,const SlVector3 &v) { strm << "["; strm << v[0]; strm << ","; strm << v[1]; strm << ","; strm << v[2]; strm << "]"; return strm; } //------------------------------------------------------------------- istream &operator>>(istream &strm,SlVector2 &v) { ios::fmtflags orgFlags = strm.setf(ios::skipws); eatChar('[',strm); strm >> v[0]; eatChar(',',strm); strm >> v[1]; eatChar(']',strm); strm.flags(orgFlags); return strm; } ostream &operator<<(ostream &strm,const SlVector2 &v) { strm << "["; strm << v[0]; strm << ","; strm << v[1]; strm << "]"; return strm; } //-------------------------------------------------------------------
[ "noreply@github.com" ]
haimasree.noreply@github.com
cd28c1eb1ce0d5344c2ad432876d8979b88cb71e
60eb36f75ba90e10563d55b734f5e5a820ac8e9b
/include/ugdk/action/animationframe.h
635c8674e63363d49f596e9bd434bc87a143d44e
[]
no_license
uspgamedev/roguelike
4a72775c1751b02051b0b9d9510fc354506371af
592d6c65442497c197528d4491b56d271d66e6e4
refs/heads/master
2021-01-17T16:52:48.464947
2014-11-15T22:01:22
2014-11-15T22:01:22
6,002,318
1
0
null
null
null
null
UTF-8
C++
false
false
1,701
h
#ifndef UGDK_ACTION_ANIMATIONFRAME_H_ #define UGDK_ACTION_ANIMATIONFRAME_H_ #include <vector> #include <string> #include <ugdk/graphic/modifier.h> #define DEFAULT_PERIOD 0.1 namespace ugdk { namespace action { class Observer; class AnimationSet; /* * Represents the visual behavior information of a sprite in a single game frame. */ class AnimationFrame { /* * frame_: the index of the spritesheet frame that should be rendered. * modifier_: a pointer to the Modifier object describing the visual modifiers that * should be applied to the rendered sprite. */ public: AnimationFrame(int frame, graphic::Modifier *modifier = NULL) : frame_(frame), modifier_(modifier) {} int frame() const { return frame_; } graphic::Modifier *modifier() const { return modifier_; } void set_frame(const int frame) { frame_ = frame; } private: int frame_; graphic::Modifier *modifier_; }; /* * Is a complex of a vector with a sequence of frame indexes, and a fixed period/fps. */ class Animation : public std::vector<AnimationFrame*> { /* * period_: the inverse of the animation's fps. */ public: Animation() : std::vector<AnimationFrame*>(), period_(DEFAULT_PERIOD) {} /* try to use period() instead whenever you can */ double fps() const { return 1.0/period_; } double period() const { return period_; } /* try to use set_period() instead whenever you can */ void set_fps(const double fps) { period_ = 1.0/fps; } void set_period(const double period) { period_ = period; } private: double period_; }; } /* namespace action */ } /* namespace ugdk */ #endif /* UGDK_ACTION_ANIMATIONFRAME_H_ */
[ "julio.angelini@gmail.com" ]
julio.angelini@gmail.com
df269833ec6bc803190ed1766134763e2b81b0ab
696f9da2cf71d81063408f9b78b3d43cb772c2f2
/UserFaceSignUp/pch.h
a7621b95ca5a902a64ae367c24c98e04f3b2807c
[]
no_license
0xliko/faceLoginCredential
43a08d7c5960e78c851e58872254e2e15bb94937
2ac7e318e7ec019573433dd4856cd47a031a1afb
refs/heads/master
2023-04-21T19:04:34.449042
2021-04-19T14:42:18
2021-04-19T14:42:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,649
h
// pch.h: This is a precompiled header file. // Files listed below are compiled only once, improving build performance for future builds. // This also affects IntelliSense performance, including code completion and many code browsing features. // However, files listed here are ALL re-compiled if any one of them is updated between builds. // Do not add files here that you will be updating frequently as this negates the performance advantage. #ifndef PCH_H #define PCH_H // add headers that you want to pre-compile here #include "framework.h" #include <iostream> #include <string> #include <vector> #include <stdlib.h> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/dnn.hpp> #include <opencv2/face.hpp> using namespace cv; using namespace std; using namespace cv::dnn; using namespace cv::face; const size_t inWidth = 320; const size_t inHeight = 320; const double inScaleFactor = 1.0; const float confidenceThreshold = 0.7; const cv::Scalar meanVal(104.0, 177.0, 123.0); #define CAFFE const std::string caffeConfigFile = "./model/deploy.prototxt"; const std::string caffeWeightFile = "./model/res10_300x300_ssd_iter_140000_fp16.caffemodel"; const std::string tensorflowConfigFile = "./model/opencv_face_detector.pbtxt"; const std::string tensorflowWeightFile = "./model/opencv_face_detector_uint8.pb"; static const PWSTR s_RegistryKey_face = L"SOFTWARE\\FaceLogin\\FaceCredentialProvider"; static const LPWSTR description_string = L"fivestarsmobi"; HBITMAP ConvertCVMatToBMP(cv::Mat frame); int detectFaceOpenCVDNN(Net net, Mat& frameOpenCVDNN,Rect& facerect); #endif //PCH_H
[ "moonshot191@gmail.com" ]
moonshot191@gmail.com
458e7a2e5c994dd79cbb0e813048f99e07592eba
dbcad4cb68a0777d3b74d821e467b1399b041d8c
/optbinstr.cpp
399204aecce5e1ea1002543cb0b242546ccf5696
[]
no_license
jatin196/CP
ec5724708b8b1a27abd6104d43f7ddb5d20549a4
35db7443b512d04e825ed445e301ef9eeea0b3a4
refs/heads/master
2023-04-19T02:48:11.828578
2021-05-07T18:47:58
2021-05-07T18:47:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
#include <bits/stdc++.h> using namespace std; int ct(int n) { if (n == 0) return 1; if (n == 1) return 2; else { int a = ct(n - 1); int b = ct(n - 2); cout<<a<<" "<<b<<endl; return a+b; } } int main() { int n; cin >> n; cout << ct(n); }
[ "jatinpopli196@gmail.com" ]
jatinpopli196@gmail.com
21d1b9dbd47c8af24f940a8b7cfe39a04997a89e
1460d98ad578dde9fb39d7a6605589743b3997ed
/chrome/browser/flag_descriptions.h
0b52151760a4689aaa44037eea3a228c7e94708a
[ "BSD-3-Clause" ]
permissive
ShaheedLegion/chromium
101016488b9027ade8bb47b0d9ca829da920bfa0
efa942217548a45b1f6a5120dd66b9e8ba9ea24e
refs/heads/master
2023-03-17T02:48:57.403495
2019-01-24T20:12:15
2019-01-24T20:12:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
83,632
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_FLAG_DESCRIPTIONS_H_ #define CHROME_BROWSER_FLAG_DESCRIPTIONS_H_ // Includes needed for macros allowing conditional compilation of some strings. #include "base/logging.h" #include "build/build_config.h" #include "build/buildflag.h" #include "chrome/common/buildflags.h" #include "components/feature_engagement/buildflags.h" #include "components/nacl/common/buildflags.h" #include "device/vr/buildflags/buildflags.h" #include "media/media_buildflags.h" #include "ppapi/buildflags/buildflags.h" #if defined(OS_ANDROID) #include "ui/android/buildflags.h" #endif // defined(OS_ANDROID) // This file declares strings used in chrome://flags. These messages are not // translated, because instead of end-users they target Chromium developers and // testers. See https://crbug.com/587272 and https://crbug.com/703134 for more // details. // // Comments are not necessary. The contents of the strings (which appear in the // UI) should be good enough documentation for what flags do and when they // apply. If they aren't, fix them. // // Sort flags in each section alphabetically by the k...Name constant. Follow // that by the k...Description constant and any special values associated with // that. // // Put #ifdefed flags in the appropriate section toward the bottom, don't // intersperse the file with ifdefs. namespace flag_descriptions { // Cross-platform ------------------------------------------------------------- extern const char kAccelerated2dCanvasName[]; extern const char kAccelerated2dCanvasDescription[]; extern const char kAcceleratedVideoDecodeName[]; extern const char kAcceleratedVideoDecodeDescription[]; extern const char kAffiliationBasedMatchingName[]; extern const char kAffiliationBasedMatchingDescription[]; extern const char kAllowInsecureLocalhostName[]; extern const char kAllowInsecureLocalhostDescription[]; extern const char kAllowNaclSocketApiName[]; extern const char kAllowNaclSocketApiDescription[]; extern const char kAllowSignedHTTPExchangeCertsWithoutExtensionName[]; extern const char kAllowSignedHTTPExchangeCertsWithoutExtensionDescription[]; extern const char kAllowStartingServiceManagerOnlyName[]; extern const char kAllowStartingServiceManagerOnlyDescription[]; extern const char kAndroidMessagesIntegrationName[]; extern const char kAndroidMessagesIntegrationDescription[]; extern const char kUseMessagesGoogleComDomainName[]; extern const char kUseMessagesGoogleComDomainDescription[]; extern const char kEnableMessagesWebPushName[]; extern const char kEnableMessagesWebPushDescription[]; extern const char kAndroidSiteSettingsUIRefreshName[]; extern const char kAndroidSiteSettingsUIRefreshDescription[]; extern const char kAppBannersName[]; extern const char kAppBannersDescription[]; extern const char kAutomaticPasswordGenerationName[]; extern const char kAutomaticPasswordGenerationDescription[]; extern const char kEnableBlinkHeapUnifiedGarbageCollectionName[]; extern const char kEnableBlinkHeapUnifiedGarbageCollectionDescription[]; extern const char kEnableBloatedRendererDetectionName[]; extern const char kEnableBloatedRendererDetectionDescription[]; extern const char kAsyncImageDecodingName[]; extern const char kAsyncImageDecodingDescription[]; extern const char kAutofillAlwaysShowServerCardsInSyncTransportName[]; extern const char kAutofillAlwaysShowServerCardsInSyncTransportDescription[]; extern const char kAutofillCacheQueryResponsesName[]; extern const char kAutofillCacheQueryResponsesDescription[]; extern const char kAutofillEnableCompanyNameName[]; extern const char kAutofillEnableCompanyNameDescription[]; extern const char kAutofillDynamicFormsName[]; extern const char kAutofillDynamicFormsDescription[]; // Enforcing restrictions to enable/disable autofill small form support. extern const char kAutofillEnforceMinRequiredFieldsForHeuristicsName[]; extern const char kAutofillEnforceMinRequiredFieldsForHeuristicsDescription[]; extern const char kAutofillEnforceMinRequiredFieldsForQueryName[]; extern const char kAutofillEnforceMinRequiredFieldsForQueryDescription[]; extern const char kAutofillEnforceMinRequiredFieldsForUploadName[]; extern const char kAutofillEnforceMinRequiredFieldsForUploadDescription[]; extern const char kAutofillNoLocalSaveOnUploadSuccessName[]; extern const char kAutofillNoLocalSaveOnUploadSuccessDescription[]; extern const char kAutofillPrefilledFieldsName[]; extern const char kAutofillPrefilledFieldsDescription[]; extern const char kAutofillProfileClientValidationName[]; extern const char kAutofillProfileClientValidationDescription[]; extern const char kAutofillPreviewStyleExperimentName[]; extern const char kAutofillPreviewStyleExperimentDescription[]; extern const char kAutofillRestrictUnownedFieldsToFormlessCheckoutName[]; extern const char kAutofillRestrictUnownedFieldsToFormlessCheckoutDescription[]; extern const char kAutofillRichMetadataQueriesName[]; extern const char kAutofillRichMetadataQueriesDescription[]; extern const char kAutofillSettingsSplitByCardTypeName[]; extern const char kAutofillSettingsSplitByCardTypeDescription[]; extern const char kAutoplayPolicyName[]; extern const char kAutoplayPolicyDescription[]; extern const char kAutoplayPolicyUserGestureRequiredForCrossOrigin[]; extern const char kAutoplayPolicyNoUserGestureRequired[]; extern const char kAutoplayPolicyUserGestureRequired[]; extern const char kAutoplayPolicyDocumentUserActivation[]; extern const char kAwaitOptimizationName[]; extern const char kAwaitOptimizationDescription[]; extern const char kBleAdvertisingInExtensionsName[]; extern const char kBleAdvertisingInExtensionsDescription[]; extern const char kBlockTabUndersName[]; extern const char kBlockTabUndersDescription[]; extern const char kBrowserTaskSchedulerName[]; extern const char kBrowserTaskSchedulerDescription[]; extern const char kBundledConnectionHelpName[]; extern const char kBundledConnectionHelpDescription[]; extern const char kBypassAppBannerEngagementChecksName[]; extern const char kBypassAppBannerEngagementChecksDescription[]; extern const char kCanvas2DImageChromiumName[]; extern const char kCanvas2DImageChromiumDescription[]; extern const char kCastStreamingHwEncodingName[]; extern const char kCastStreamingHwEncodingDescription[]; extern const char kClickToOpenPDFName[]; extern const char kClickToOpenPDFDescription[]; extern const char kClipboardContentSettingName[]; extern const char kClipboardContentSettingDescription[]; extern const char kCloudImportName[]; extern const char kCloudImportDescription[]; extern const char kCloudPrinterHandlerName[]; extern const char kCloudPrinterHandlerDescription[]; extern const char kExperimentalAccessibilityFeaturesName[]; extern const char kExperimentalAccessibilityFeaturesDescription[]; extern const char kExperimentalAccessibilityAutoclickName[]; extern const char kExperimentalAccessibilityAutoclickDescription[]; extern const char kExperimentalAccessibilityLabelsName[]; extern const char kExperimentalAccessibilityLabelsDescription[]; extern const char kExperimentalAccessibilityLanguageDetectionName[]; extern const char kExperimentalAccessibilityLanguageDetectionDescription[]; extern const char kExperimentalAccessibilitySwitchAccessName[]; extern const char kExperimentalAccessibilitySwitchAccessDescription[]; extern const char kFCMInvalidationsName[]; extern const char kFCMInvalidationsDescription[]; extern const char kForceColorProfileSRGB[]; extern const char kForceColorProfileP3[]; extern const char kForceColorProfileColorSpin[]; extern const char kForceColorProfileHdr[]; extern const char kForceColorProfileName[]; extern const char kForceColorProfileDescription[]; extern const char kCompositedLayerBordersName[]; extern const char kCompositedLayerBordersDescription[]; extern const char kContextualSuggestionsButtonName[]; extern const char kContextualSuggestionsButtonDescription[]; extern const char kContextualSuggestionsIPHReverseScrollName[]; extern const char kContextualSuggestionsIPHReverseScrollDescription[]; extern const char kContextualSuggestionsOptOutName[]; extern const char kContextualSuggestionsOptOutDescription[]; extern const char kCreditCardAssistName[]; extern const char kCreditCardAssistDescription[]; extern const char kDataSaverServerPreviewsName[]; extern const char kDataSaverServerPreviewsDescription[]; extern const char kDebugPackedAppName[]; extern const char kDebugPackedAppDescription[]; extern const char kDebugShortcutsName[]; extern const char kDebugShortcutsDescription[]; extern const char kDeviceDiscoveryNotificationsName[]; extern const char kDeviceDiscoveryNotificationsDescription[]; extern const char kDevtoolsExperimentsName[]; extern const char kDevtoolsExperimentsDescription[]; extern const char kDisableAudioForDesktopShareName[]; extern const char kDisableAudioForDesktopShareDescription[]; extern const char kDisableIpcFloodingProtectionName[]; extern const char kDisableIpcFloodingProtectionDescription[]; extern const char kDisablePushStateThrottleName[]; extern const char kDisablePushStateThrottleDescription[]; extern const char kDisableTabForDesktopShareName[]; extern const char kDisableTabForDesktopShareDescription[]; extern const char kDisallowDocWrittenScriptsUiName[]; extern const char kDisallowDocWrittenScriptsUiDescription[]; extern const char kDisallowUnsafeHttpDownloadsName[]; extern const char kDisallowUnsafeHttpDownloadsNameDescription[]; extern const char kDisplayList2dCanvasName[]; extern const char kDisplayList2dCanvasDescription[]; extern const char kDriveSearchInChromeLauncherName[]; extern const char kDriveSearchInChromeLauncherDescription[]; extern const char kEmbeddedExtensionOptionsName[]; extern const char kEmbeddedExtensionOptionsDescription[]; extern const char kEnableAccessibilityObjectModelName[]; extern const char kEnableAccessibilityObjectModelDescription[]; extern const char kEnableAudioFocusEnforcementName[]; extern const char kEnableAudioFocusEnforcementDescription[]; extern const char kEnableAutocompleteDataRetentionPolicyName[]; extern const char kEnableAutocompleteDataRetentionPolicyDescription[]; extern const char kEnableAutofillAccountWalletStorageName[]; extern const char kEnableAutofillAccountWalletStorageDescription[]; extern const char kEnableAutofillCreditCardAblationExperimentDisplayName[]; extern const char kEnableAutofillCreditCardAblationExperimentDescription[]; extern const char kEnableAutofillCreditCardLastUsedDateDisplayName[]; extern const char kEnableAutofillCreditCardLastUsedDateDisplayDescription[]; extern const char kEnableAutofillCreditCardLocalCardMigrationName[]; extern const char kEnableAutofillCreditCardLocalCardMigrationDescription[]; extern const char kEnableAutofillCreditCardUploadEditableCardholderNameName[]; extern const char kEnableAutofillCreditCardUploadEditableCardholderNameDescription[]; extern const char kEnableAutofillCreditCardUploadEditableExpirationDateName[]; extern const char kEnableAutofillCreditCardUploadEditableExpirationDateDescription[]; extern const char kEnableAutofillLocalCardMigrationShowFeedbackName[]; extern const char kEnableAutofillLocalCardMigrationShowFeedbackDescription[]; extern const char kEnableAutofillSaveCardImprovedUserConsentName[]; extern const char kEnableAutofillSaveCardImprovedUserConsentDescription[]; extern const char kEnableAutofillSaveCreditCardUsesStrikeSystemName[]; extern const char kEnableAutofillSaveCreditCardUsesStrikeSystemDescription[]; extern const char kEnableAutofillSaveCreditCardUsesStrikeSystemV2Name[]; extern const char kEnableAutofillSaveCreditCardUsesStrikeSystemV2Description[]; extern const char kEnableAutofillToolkitViewsCreditCardDialogsMac[]; extern const char kEnableAutofillToolkitViewsCreditCardDialogsMacDescription[]; extern const char kEnableAutofillNativeDropdownViewsName[]; extern const char kEnableAutofillNativeDropdownViewsDescription[]; extern const char kEnableAutofillSaveCardDialogUnlabeledExpirationDateName[]; extern const char kEnableAutofillSaveCardDialogUnlabeledExpirationDateDescription[]; extern const char kEnableAutofillSaveCardSignInAfterLocalSaveName[]; extern const char kEnableAutofillSaveCardSignInAfterLocalSaveDescription[]; extern const char kEnableAutofillSendExperimentIdsInPaymentsRPCsName[]; extern const char kEnableAutofillSendExperimentIdsInPaymentsRPCsDescription[]; extern const char kEnableAutoplayIgnoreWebAudioName[]; extern const char kEnableAutoplayIgnoreWebAudioDescription[]; extern const char kEnableAutoplayUnifiedSoundSettingsName[]; extern const char kEnableAutoplayUnifiedSoundSettingsDescription[]; extern const char kEnableBrotliName[]; extern const char kEnableBrotliDescription[]; extern const char kEnableCaptivePortalRandomUrl[]; extern const char kEnableCaptivePortalRandomUrlDescription[]; extern const char kEnableChromevoxDeveloperOptionName[]; extern const char kEnableChromevoxDeveloperOptionDescription[]; extern const char kEnableClientLoFiName[]; extern const char kEnableClientLoFiDescription[]; extern const char kEnableCSSFragmentIdentifiersName[]; extern const char kEnableCSSFragmentIdentifiersDescription[]; extern const char kEnableNoScriptPreviewsName[]; extern const char kEnableNoScriptPreviewsDescription[]; extern const char kDataReductionProxyServerAlternative1[]; extern const char kDataReductionProxyServerAlternative2[]; extern const char kDataReductionProxyServerAlternative3[]; extern const char kDataReductionProxyServerAlternative4[]; extern const char kDataReductionProxyServerAlternative5[]; extern const char kDataReductionProxyServerAlternative6[]; extern const char kDataReductionProxyServerAlternative7[]; extern const char kDataReductionProxyServerAlternative8[]; extern const char kDataReductionProxyServerAlternative9[]; extern const char kDataReductionProxyServerAlternative10[]; extern const char kEnableDataReductionProxyNetworkServiceName[]; extern const char kEnableDataReductionProxyNetworkServiceDescription[]; extern const char kEnableDataReductionProxyServerExperimentName[]; extern const char kEnableDataReductionProxyServerExperimentDescription[]; extern const char kEnableDataReductionProxySavingsPromoName[]; extern const char kEnableDataReductionProxySavingsPromoDescription[]; extern const char kEnableDesktopPWAsName[]; extern const char kEnableDesktopPWAsDescription[]; extern const char kEnableDesktopPWAsLinkCapturingName[]; extern const char kEnableDesktopPWAsLinkCapturingDescription[]; extern const char kDesktopPWAsCustomTabUIName[]; extern const char kDesktopPWAsCustomTabUIDescription[]; extern const char kDesktopPWAsStayInWindowName[]; extern const char kDesktopPWAsStayInWindowDescription[]; extern const char kEnableSystemWebAppsName[]; extern const char kEnableSystemWebAppsDescription[]; extern const char kEnableDockedMagnifierName[]; extern const char kEnableDockedMagnifierDescription[]; extern const char kEnforceTLS13DowngradeName[]; extern const char kEnforceTLS13DowngradeDescription[]; extern const char kEnableEnumeratingAudioDevicesName[]; extern const char kEnableEnumeratingAudioDevicesDescription[]; extern const char kEnableGenericSensorName[]; extern const char kEnableGenericSensorDescription[]; extern const char kEnableGenericSensorExtraClassesName[]; extern const char kEnableGenericSensorExtraClassesDescription[]; extern const char kEnableGpuServiceLoggingName[]; extern const char kEnableGpuServiceLoggingDescription[]; extern const char kEnableHDRName[]; extern const char kEnableHDRDescription[]; extern const char kEnableHeavyPageCappingName[]; extern const char kEnableHeavyPageCappingDescription[]; extern const char kEnableImplicitRootScrollerName[]; extern const char kEnableImplicitRootScrollerDescription[]; extern const char kEnablePreviewsAndroidOmniboxUIName[]; extern const char kEnablePreviewsAndroidOmniboxUIDescription[]; extern const char kEnableLitePageServerPreviewsName[]; extern const char kEnableLitePageServerPreviewsDescription[]; extern const char kLayeredAPIName[]; extern const char kLayeredAPIDescription[]; extern const char kEnableBlinkGenPropertyTreesName[]; extern const char kEnableBlinkGenPropertyTreesDescription[]; extern const char kEnableLayoutNGName[]; extern const char kEnableLayoutNGDescription[]; extern const char kEnableLazyFrameLoadingName[]; extern const char kEnableLazyFrameLoadingDescription[]; extern const char kEnableLazyImageLoadingName[]; extern const char kEnableLazyImageLoadingDescription[]; extern const char kEnableMacMaterialDesignDownloadShelfName[]; extern const char kEnableMacMaterialDesignDownloadShelfDescription[]; extern const char kEnableMaterialDesignBookmarksName[]; extern const char kEnableMaterialDesignBookmarksDescription[]; extern const char kEnableMediaSessionServiceName[]; extern const char kEnableMediaSessionServiceDescription[]; extern const char kEnablePolicyToolName[]; extern const char kEnablePolicyToolDescription[]; extern const char kDisableMultiMirroringName[]; extern const char kDisableMultiMirroringDescription[]; extern const char kEnableNavigationTracingName[]; extern const char kEnableNavigationTracingDescription[]; extern const char kEnableNetworkLoggingToFileName[]; extern const char kEnableNetworkLoggingToFileDescription[]; extern const char kEnableNetworkServiceName[]; extern const char kEnableNetworkServiceDescription[]; extern const char kEnableNetworkServiceInProcessName[]; extern const char kEnableNetworkServiceInProcessDescription[]; extern const char kEnableNightLightName[]; extern const char kEnableNightLightDescription[]; extern const char kEnableNotificationScrollBarName[]; extern const char kEnableNotificationScrollBarDescription[]; extern const char kEnableNotificationExpansionAnimationName[]; extern const char kEnableNotificationExpansionAnimationDescription[]; extern const char kEnableNupPrintingName[]; extern const char kEnableNupPrintingDescription[]; extern const char kEnableOptimizationHintsName[]; extern const char kEnableOptimizationHintsDescription[]; extern const char kEnableOutOfBlinkCorsName[]; extern const char kEnableOutOfBlinkCorsDescription[]; extern const char kVizDisplayCompositorName[]; extern const char kVizDisplayCompositorDescription[]; extern const char kVizHitTestDrawQuadName[]; extern const char kVizHitTestDrawQuadDescription[]; extern const char kEnableOutOfProcessHeapProfilingName[]; extern const char kEnableOutOfProcessHeapProfilingDescription[]; extern const char kEnableOutOfProcessHeapProfilingModeMinimal[]; extern const char kEnableOutOfProcessHeapProfilingModeAll[]; extern const char kEnableOutOfProcessHeapProfilingModeAllRenderers[]; extern const char kEnableOutOfProcessHeapProfilingModeBrowser[]; extern const char kEnableOutOfProcessHeapProfilingModeGpu[]; extern const char kEnableOutOfProcessHeapProfilingModeManual[]; extern const char kEnableOutOfProcessHeapProfilingModeRendererSampling[]; extern const char kOutOfProcessHeapProfilingKeepSmallAllocations[]; extern const char kOutOfProcessHeapProfilingKeepSmallAllocationsDescription[]; extern const char kOutOfProcessHeapProfilingSampling[]; extern const char kOutOfProcessHeapProfilingSamplingDescription[]; extern const char kOOPHPStackModeName[]; extern const char kOOPHPStackModeDescription[]; extern const char kOOPHPStackModeMixed[]; extern const char kOOPHPStackModeNative[]; extern const char kOOPHPStackModeNativeWithThreadNames[]; extern const char kOOPHPStackModePseudo[]; extern const char kEnablePictureInPictureName[]; extern const char kEnablePictureInPictureDescription[]; extern const char kEnablePixelCanvasRecordingName[]; extern const char kEnablePixelCanvasRecordingDescription[]; extern const char kEnableResamplingInputEventsName[]; extern const char kEnableResamplingInputEventsDescription[]; extern const char kEnableResamplingScrollEventsName[]; extern const char kEnableResamplingScrollEventsDescription[]; extern const char kEnableResourceLoadingHintsName[]; extern const char kEnableResourceLoadingHintsDescription[]; extern const char kEnableSyncPseudoUSSAppListName[]; extern const char kEnableSyncPseudoUSSAppListDescription[]; extern const char kEnableSyncPseudoUSSAppsName[]; extern const char kEnableSyncPseudoUSSAppsDescription[]; extern const char kEnableSyncPseudoUSSDictionaryName[]; extern const char kEnableSyncPseudoUSSDictionaryDescription[]; extern const char kEnableSyncPseudoUSSExtensionSettingsName[]; extern const char kEnableSyncPseudoUSSExtensionSettingsDescription[]; extern const char kEnableSyncPseudoUSSExtensionsName[]; extern const char kEnableSyncPseudoUSSExtensionsDescription[]; extern const char kEnableSyncPseudoUSSFaviconsName[]; extern const char kEnableSyncPseudoUSSFaviconsDescription[]; extern const char kEnableSyncPseudoUSSHistoryDeleteDirectivesName[]; extern const char kEnableSyncPseudoUSSHistoryDeleteDirectivesDescription[]; extern const char kEnableSyncPseudoUSSPasswordsName[]; extern const char kEnableSyncPseudoUSSPasswordsDescription[]; extern const char kEnableSyncPseudoUSSPreferencesName[]; extern const char kEnableSyncPseudoUSSPreferencesDescription[]; extern const char kEnableSyncPseudoUSSPriorityPreferencesName[]; extern const char kEnableSyncPseudoUSSPriorityPreferencesDescription[]; extern const char kEnableSyncPseudoUSSSearchEnginesName[]; extern const char kEnableSyncPseudoUSSSearchEnginesDescription[]; extern const char kEnableSyncPseudoUSSSupervisedUsersName[]; extern const char kEnableSyncPseudoUSSSupervisedUsersDescription[]; extern const char kEnableSyncPseudoUSSThemesName[]; extern const char kEnableSyncPseudoUSSThemesDescription[]; extern const char kEnableSyncUSSBookmarksName[]; extern const char kEnableSyncUSSBookmarksDescription[]; extern const char kEnableSyncUSSSessionsName[]; extern const char kEnableSyncUSSSessionsDescription[]; extern const char kEnableUseZoomForDsfName[]; extern const char kEnableUseZoomForDsfDescription[]; extern const char kEnableUseZoomForDsfChoiceDefault[]; extern const char kEnableUseZoomForDsfChoiceEnabled[]; extern const char kEnableUseZoomForDsfChoiceDisabled[]; extern const char kEnableScrollAnchorSerializationName[]; extern const char kEnableScrollAnchorSerializationDescription[]; extern const char kEnableSharedArrayBufferName[]; extern const char kEnableSharedArrayBufferDescription[]; extern const char kEnableWasmName[]; extern const char kEnableWasmDescription[]; extern const char kEnableWebAuthenticationCableSupportName[]; extern const char kEnableWebAuthenticationCableSupportDescription[]; extern const char kEnableWebPaymentsSingleAppUiSkipName[]; extern const char kEnableWebPaymentsSingleAppUiSkipDescription[]; extern const char kEnableWebUsbName[]; extern const char kEnableWebUsbDescription[]; extern const char kEnableImageCaptureAPIName[]; extern const char kEnableImageCaptureAPIDescription[]; extern const char kEnableIncognitoWindowCounterName[]; extern const char kEnableIncognitoWindowCounterDescription[]; extern const char kEnableZeroSuggestRedirectToChromeName[]; extern const char kEnableZeroSuggestRedirectToChromeDescription[]; extern const char kEnableWasmBaselineName[]; extern const char kEnableWasmBaselineDescription[]; extern const char kEnableWasmThreadsName[]; extern const char kEnableWasmThreadsDescription[]; extern const char kExpensiveBackgroundTimerThrottlingName[]; extern const char kExpensiveBackgroundTimerThrottlingDescription[]; extern const char kExperimentalAppBannersName[]; extern const char kExperimentalAppBannersDescription[]; extern const char kExperimentalCanvasFeaturesName[]; extern const char kExperimentalCanvasFeaturesDescription[]; extern const char kExperimentalExtensionApisName[]; extern const char kExperimentalExtensionApisDescription[]; extern const char kExperimentalProductivityFeaturesName[]; extern const char kExperimentalProductivityFeaturesDescription[]; extern const char kExperimentalSecurityFeaturesName[]; extern const char kExperimentalSecurityFeaturesDescription[]; extern const char kExperimentalWebPlatformFeaturesName[]; extern const char kExperimentalWebPlatformFeaturesDescription[]; extern const char kExtensionContentVerificationName[]; extern const char kExtensionContentVerificationDescription[]; extern const char kExtensionContentVerificationBootstrap[]; extern const char kExtensionContentVerificationEnforce[]; extern const char kExtensionContentVerificationEnforceStrict[]; extern const char kExtensionsOnChromeUrlsName[]; extern const char kExtensionsOnChromeUrlsDescription[]; extern const char kFeaturePolicyName[]; extern const char kFeaturePolicyDescription[]; extern const char kFontCacheScalingName[]; extern const char kFontCacheScalingDescription[]; extern const char kForceEffectiveConnectionTypeName[]; extern const char kForceEffectiveConnectionTypeDescription[]; extern const char kEffectiveConnectionTypeUnknownDescription[]; extern const char kEffectiveConnectionTypeOfflineDescription[]; extern const char kEffectiveConnectionTypeSlow2GDescription[]; extern const char kEffectiveConnectionTypeSlow2GOnCellularDescription[]; extern const char kEffectiveConnectionType2GDescription[]; extern const char kEffectiveConnectionType3GDescription[]; extern const char kEffectiveConnectionType4GDescription[]; extern const char kFillOnAccountSelectName[]; extern const char kFillOnAccountSelectDescription[]; extern const char kForceTextDirectionName[]; extern const char kForceTextDirectionDescription[]; extern const char kForceDirectionLtr[]; extern const char kForceDirectionRtl[]; extern const char kForceUiDirectionName[]; extern const char kForceUiDirectionDescription[]; extern const char kFramebustingName[]; extern const char kFramebustingDescription[]; extern const char kGamepadVibrationName[]; extern const char kGamepadVibrationDescription[]; extern const char kGpuRasterizationName[]; extern const char kGpuRasterizationDescription[]; extern const char kForceGpuRasterization[]; extern const char kGooglePasswordManagerName[]; extern const char kGooglePasswordManagerDescription[]; extern const char kGoogleProfileInfoName[]; extern const char kGoogleProfileInfoDescription[]; extern const char kHandwritingGestureName[]; extern const char kHandwritingGestureDescription[]; extern const char kHardwareMediaKeyHandling[]; extern const char kHardwareMediaKeyHandlingDescription[]; extern const char kHarfbuzzRendertextName[]; extern const char kHarfbuzzRendertextDescription[]; extern const char kHorizontalTabSwitcherAndroidName[]; extern const char kHorizontalTabSwitcherAndroidDescription[]; extern const char kTabSwitcherOnReturnName[]; extern const char kTabSwitcherOnReturnDescription[]; extern const char kViewsCastDialogName[]; extern const char kViewsCastDialogDescription[]; extern const char kHideActiveAppsFromShelfName[]; extern const char kHideActiveAppsFromShelfDescription[]; extern const char kHistoryRequiresUserGestureName[]; extern const char kHistoryRequiresUserGestureDescription[]; extern const char kHyperlinkAuditingName[]; extern const char kHyperlinkAuditingDescription[]; extern const char kHostedAppQuitNotificationName[]; extern const char kHostedAppQuitNotificationDescription[]; extern const char kHostedAppShimCreationName[]; extern const char kHostedAppShimCreationDescription[]; extern const char kHtmlBasedUsernameDetectorName[]; extern const char kHtmlBasedUsernameDetectorDescription[]; extern const char kIconNtpName[]; extern const char kIconNtpDescription[]; extern const char kIgnoreGpuBlacklistName[]; extern const char kIgnoreGpuBlacklistDescription[]; extern const char kIgnorePreviewsBlacklistName[]; extern const char kIgnorePreviewsBlacklistDescription[]; extern const char kImprovedGeoLanguageDataName[]; extern const char kImprovedGeoLanguageDataDescription[]; extern const char kInProductHelpDemoModeChoiceName[]; extern const char kInProductHelpDemoModeChoiceDescription[]; extern const char kJavascriptHarmonyName[]; extern const char kJavascriptHarmonyDescription[]; extern const char kJavascriptHarmonyShippingName[]; extern const char kJavascriptHarmonyShippingDescription[]; extern const char kJustInTimeServiceWorkerPaymentAppName[]; extern const char kJustInTimeServiceWorkerPaymentAppDescription[]; extern const char kKeepAliveRendererForKeepaliveRequestsName[]; extern const char kKeepAliveRendererForKeepaliveRequestsDescription[]; extern const char kKeyboardLockApiName[]; extern const char kKeyboardLockApiDescription[]; extern const char kLcdTextName[]; extern const char kLcdTextDescription[]; extern const char kLeftToRightUrlsName[]; extern const char kLeftToRightUrlsDescription[]; extern const char kLoadMediaRouterComponentExtensionName[]; extern const char kLoadMediaRouterComponentExtensionDescription[]; extern const char kLookalikeUrlNavigationSuggestionsName[]; extern const char kLookalikeUrlNavigationSuggestionsDescription[]; extern const char kMarkHttpAsName[]; extern const char kMarkHttpAsDescription[]; extern const char kMarkHttpAsDangerous[]; extern const char kMarkHttpAsWarning[]; extern const char kMarkHttpAsWarningAndDangerousOnFormEdits[]; extern const char kMarkHttpAsWarningAndDangerousOnPasswordsAndCreditCards[]; extern const char kMaterialDesignIncognitoNTPName[]; extern const char kMaterialDesignIncognitoNTPDescription[]; extern const char kMediaRouterCastAllowAllIPsName[]; extern const char kMediaRouterCastAllowAllIPsDescription[]; extern const char kMemoryCoordinatorName[]; extern const char kMemoryCoordinatorDescription[]; extern const char kMessageCenterNewStyleNotificationName[]; extern const char kMessageCenterNewStyleNotificationDescription[]; extern const char kMhtmlGeneratorOptionName[]; extern const char kMhtmlGeneratorOptionDescription[]; extern const char kMhtmlSkipNostoreMain[]; extern const char kMhtmlSkipNostoreAll[]; extern const char kNewAudioRenderingMixingStrategyName[]; extern const char kNewAudioRenderingMixingStrategyDescription[]; extern const char kNewBookmarkAppsName[]; extern const char kNewBookmarkAppsDescription[]; extern const char kNewPasswordFormParsingName[]; extern const char kNewPasswordFormParsingDescription[]; extern const char kNewPasswordFormParsingForSavingName[]; extern const char kNewPasswordFormParsingForSavingDescription[]; extern const char kNewRemotePlaybackPipelineName[]; extern const char kNewRemotePlaybackPipelineDescription[]; extern const char kOnlyNewPasswordFormParsingName[]; extern const char kOnlyNewPasswordFormParsingDescription[]; extern const char kUseSurfaceLayerForVideoName[]; extern const char kUseSurfaceLayerForVideoDescription[]; extern const char kNewUsbBackendName[]; extern const char kNewUsbBackendDescription[]; extern const char kNewblueName[]; extern const char kNewblueDescription[]; extern const char kNewTabLoadingAnimation[]; extern const char kNewTabLoadingAnimationDescription[]; extern const char kNewTabButtonPosition[]; extern const char kNewTabButtonPositionDescription[]; extern const char kNewTabButtonPositionOppositeCaption[]; extern const char kNewTabButtonPositionLeading[]; extern const char kNewTabButtonPositionAfterTabs[]; extern const char kNewTabButtonPositionTrailing[]; extern const char kNostatePrefetchName[]; extern const char kNostatePrefetchDescription[]; extern const char kNotificationIndicatorName[]; extern const char kNotificationIndicatorDescription[]; extern const char kNotificationsNativeFlagName[]; extern const char kNotificationsNativeFlagDescription[]; extern const char kUseMultiloginEndpointName[]; extern const char kUseMultiloginEndpointDescription[]; #if defined(OS_POSIX) extern const char kNtlmV2EnabledName[]; extern const char kNtlmV2EnabledDescription[]; #endif extern const char kOfferStoreUnmaskedWalletCardsName[]; extern const char kOfferStoreUnmaskedWalletCardsDescription[]; extern const char kOfflineAutoReloadName[]; extern const char kOfflineAutoReloadDescription[]; extern const char kOfflineAutoReloadVisibleOnlyName[]; extern const char kOfflineAutoReloadVisibleOnlyDescription[]; extern const char kOmniboxDisplayTitleForCurrentUrlName[]; extern const char kOmniboxDisplayTitleForCurrentUrlDescription[]; extern const char kOmniboxNewAnswerLayoutName[]; extern const char kOmniboxNewAnswerLayoutDescription[]; extern const char kOmniboxSpareRendererName[]; extern const char kOmniboxSpareRendererDescription[]; extern const char kOmniboxUIHideSteadyStateUrlSchemeName[]; extern const char kOmniboxUIHideSteadyStateUrlSchemeDescription[]; extern const char kOmniboxUIHideSteadyStateUrlTrivialSubdomainsName[]; extern const char kOmniboxUIHideSteadyStateUrlTrivialSubdomainsDescription[]; extern const char kOmniboxUIHideSteadyStateUrlPathQueryAndRefName[]; extern const char kOmniboxUIHideSteadyStateUrlPathQueryAndRefDescription[]; extern const char kOmniboxUIOneClickUnelideName[]; extern const char kOmniboxUIOneClickUnelideDescription[]; extern const char kOmniboxUIMaxAutocompleteMatchesName[]; extern const char kOmniboxUIMaxAutocompleteMatchesDescription[]; extern const char kOmniboxUISwapTitleAndUrlName[]; extern const char kOmniboxUISwapTitleAndUrlDescription[]; extern const char kOmniboxVoiceSearchAlwaysVisibleName[]; extern const char kOmniboxVoiceSearchAlwaysVisibleDescription[]; extern const char kOnTheFlyMhtmlHashComputationName[]; extern const char kOnTheFlyMhtmlHashComputationDescription[]; extern const char kOopRasterizationName[]; extern const char kOopRasterizationDescription[]; extern const char kOverflowIconsForMediaControlsName[]; extern const char kOverflowIconsForMediaControlsDescription[]; extern const char kOriginTrialsName[]; extern const char kOriginTrialsDescription[]; extern const char kOverlayScrollbarsName[]; extern const char kOverlayScrollbarsDescription[]; extern const char kOverlayScrollbarsFlashAfterAnyScrollUpdateName[]; extern const char kOverlayScrollbarsFlashAfterAnyScrollUpdateDescription[]; extern const char kOverlayScrollbarsFlashWhenMouseEnterName[]; extern const char kOverlayScrollbarsFlashWhenMouseEnterDescription[]; extern const char kOverlayStrategiesName[]; extern const char kOverlayStrategiesDescription[]; extern const char kOverlayStrategiesDefault[]; extern const char kOverlayStrategiesNone[]; extern const char kOverlayStrategiesUnoccludedFullscreen[]; extern const char kOverlayStrategiesUnoccluded[]; extern const char kOverlayStrategiesOccludedAndUnoccluded[]; extern const char kUseNewAcceptLanguageHeaderName[]; extern const char kUseNewAcceptLanguageHeaderDescription[]; extern const char kOverscrollHistoryNavigationName[]; extern const char kOverscrollHistoryNavigationDescription[]; extern const char kOverscrollStartThresholdName[]; extern const char kOverscrollStartThresholdDescription[]; extern const char kOverscrollStartThreshold133Percent[]; extern const char kOverscrollStartThreshold166Percent[]; extern const char kOverscrollStartThreshold200Percent[]; extern const char kParallelDownloadingName[]; extern const char kParallelDownloadingDescription[]; extern const char kPassiveEventListenerDefaultName[]; extern const char kPassiveEventListenerDefaultDescription[]; extern const char kPassiveEventListenerTrue[]; extern const char kPassiveEventListenerForceAllTrue[]; extern const char kPassiveEventListenersDueToFlingName[]; extern const char kPassiveEventListenersDueToFlingDescription[]; extern const char kPassiveDocumentEventListenersName[]; extern const char kPassiveDocumentEventListenersDescription[]; extern const char kPassiveDocumentWheelEventListenersName[]; extern const char kPassiveDocumentWheelEventListenersDescription[]; extern const char kPasswordImportName[]; extern const char kPasswordImportDescription[]; extern const char kPasswordsKeyboardAccessoryName[]; extern const char kPasswordsKeyboardAccessoryDescription[]; extern const char kPasswordsMigrateLinuxToLoginDBName[]; extern const char kPasswordsMigrateLinuxToLoginDBDescription[]; extern const char kPerMethodCanMakePaymentQuotaName[]; extern const char kPerMethodCanMakePaymentQuotaDescription[]; extern const char kPinchScaleName[]; extern const char kPinchScaleDescription[]; extern const char kPreviewsAllowedName[]; extern const char kPreviewsAllowedDescription[]; extern const char kPrintPdfAsImageName[]; extern const char kPrintPdfAsImageDescription[]; extern const char kPrintPreviewRegisterPromosName[]; extern const char kPrintPreviewRegisterPromosDescription[]; extern const char kProtectSyncCredentialName[]; extern const char kProtectSyncCredentialDescription[]; extern const char kProtectSyncCredentialOnReauthName[]; extern const char kProtectSyncCredentialOnReauthDescription[]; extern const char kPullToRefreshName[]; extern const char kPullToRefreshDescription[]; extern const char kPullToRefreshEnabledTouchscreen[]; extern const char kQueryInOmniboxName[]; extern const char kQueryInOmniboxDescription[]; extern const char kQuicName[]; extern const char kQuicDescription[]; extern const char kRecurrentInterstitialName[]; extern const char kRecurrentInterstitialDescription[]; extern const char kReducedReferrerGranularityName[]; extern const char kReducedReferrerGranularityDescription[]; extern const char kRegionalLocalesAsDisplayUIName[]; extern const char kRegionalLocalesAsDisplayUIDescription[]; extern const char kRewriteLevelDBOnDeletionName[]; extern const char kRewriteLevelDBOnDeletionDescription[]; extern const char kRendererSideResourceSchedulerName[]; extern const char kRendererSideResourceSchedulerDescription[]; extern const char kRequestTabletSiteName[]; extern const char kRequestTabletSiteDescription[]; extern const char kResetAppListInstallStateName[]; extern const char kResetAppListInstallStateDescription[]; extern const char kResourceLoadSchedulerName[]; extern const char kResourceLoadSchedulerDescription[]; extern const char kSafeBrowsingUseAPDownloadVerdictsName[]; extern const char kSafeBrowsingUseAPDownloadVerdictsDescription[]; extern const char kSafeSearchUrlReportingName[]; extern const char kSafeSearchUrlReportingDescription[]; extern const char kSamplingHeapProfilerName[]; extern const char kSamplingHeapProfilerDescription[]; extern const char kSaveasMenuLabelExperimentName[]; extern const char kSaveasMenuLabelExperimentDescription[]; extern const char kSavePageAsMhtmlName[]; extern const char kSavePageAsMhtmlDescription[]; extern const char kSendTabToSelfName[]; extern const char kSendTabToSelfDescription[]; extern const char kServiceWorkerPaymentAppsName[]; extern const char kServiceWorkerPaymentAppsDescription[]; extern const char kServiceWorkerImportedScriptUpdateCheckName[]; extern const char kServiceWorkerImportedScriptUpdateCheckDescription[]; extern const char kServiceWorkerServicificationName[]; extern const char kServiceWorkerServicificationDescription[]; extern const char kServiceWorkerLongRunningMessageName[]; extern const char kServiceWorkerLongRunningMessageDescription[]; extern const char kSettingsWindowName[]; extern const char kSettingsWindowDescription[]; extern const char kShelfHoverPreviewsName[]; extern const char kShelfHoverPreviewsDescription[]; extern const char kShowAndroidFilesInFilesAppName[]; extern const char kShowAndroidFilesInFilesAppDescription[]; extern const char kShowAutofillSignaturesName[]; extern const char kShowAutofillSignaturesDescription[]; extern const char kShowAutofillTypePredictionsName[]; extern const char kShowAutofillTypePredictionsDescription[]; extern const char kShowOverdrawFeedbackName[]; extern const char kShowOverdrawFeedbackDescription[]; extern const char kHistoryManipulationIntervention[]; extern const char kHistoryManipulationInterventionDescription[]; extern const char kSupervisedUserCommittedInterstitialsName[]; extern const char kSupervisedUserCommittedInterstitialsDescription[]; extern const char kEnableDrawOcclusionName[]; extern const char kEnableDrawOcclusionDescription[]; extern const char kShowSavedCopyName[]; extern const char kShowSavedCopyDescription[]; extern const char kEnableShowSavedCopyPrimary[]; extern const char kEnableShowSavedCopySecondary[]; extern const char kDisableShowSavedCopy[]; extern const char kSilentDebuggerExtensionApiName[]; extern const char kSilentDebuggerExtensionApiDescription[]; extern const char kSignedHTTPExchangeName[]; extern const char kSignedHTTPExchangeDescription[]; extern const char kSimplifyHttpsIndicatorName[]; extern const char kSimplifyHttpsIndicatorDescription[]; extern const char kSingleTabMode[]; extern const char kSingleTabModeDescription[]; extern const char kSiteIsolationOptOutName[]; extern const char kSiteIsolationOptOutDescription[]; extern const char kSiteIsolationOptOutChoiceDefault[]; extern const char kSiteIsolationOptOutChoiceOptOut[]; extern const char kSiteSettings[]; extern const char kSiteSettingsDescription[]; extern const char kSmoothScrollingName[]; extern const char kSmoothScrollingDescription[]; extern const char kSoftwareRasterizerName[]; extern const char kSoftwareRasterizerDescription[]; extern const char kSoleIntegrationName[]; extern const char kSoleIntegrationDescription[]; extern const char kSoundContentSettingName[]; extern const char kSoundContentSettingDescription[]; extern const char kSpeculativeServiceWorkerStartOnQueryInputName[]; extern const char kSpeculativeServiceWorkerStartOnQueryInputDescription[]; extern const char kSpellingFeedbackFieldTrialName[]; extern const char kSpellingFeedbackFieldTrialDescription[]; extern const char kSSLCommittedInterstitialsName[]; extern const char kSSLCommittedInterstitialsDescription[]; extern const char kStopInBackgroundName[]; extern const char kStopInBackgroundDescription[]; extern const char kStopNonTimersInBackgroundName[]; extern const char kStopNonTimersInBackgroundDescription[]; extern const char kSystemKeyboardLockName[]; extern const char kSystemKeyboardLockDescription[]; extern const char kSuggestionsWithSubStringMatchName[]; extern const char kSuggestionsWithSubStringMatchDescription[]; extern const char kSyncSandboxName[]; extern const char kSyncSandboxDescription[]; extern const char kSyncStandaloneTransportName[]; extern const char kSyncStandaloneTransportDescription[]; extern const char kSyncSupportSecondaryAccountName[]; extern const char kSyncSupportSecondaryAccountDescription[]; extern const char kSyncUSSAutofillProfileName[]; extern const char kSyncUSSAutofillProfileDescription[]; extern const char kSyncUSSAutofillWalletDataName[]; extern const char kSyncUSSAutofillWalletDataDescription[]; extern const char kSysInternalsName[]; extern const char kSysInternalsDescription[]; extern const char kTabGroupsName[]; extern const char kTabGroupsDescription[]; extern const char kTabHoverCardsName[]; extern const char kTabHoverCardsDescription[]; extern const char kTabsInCbdName[]; extern const char kTabsInCbdDescription[]; extern const char kTintGlCompositedContentName[]; extern const char kTintGlCompositedContentDescription[]; extern const char kTopChromeTouchUiName[]; extern const char kTopChromeTouchUiDescription[]; extern const char kThreadedScrollingName[]; extern const char kThreadedScrollingDescription[]; extern const char kTopSitesFromSiteEngagementName[]; extern const char kTopSitesFromSiteEngagementDescription[]; extern const char kTouchAdjustmentName[]; extern const char kTouchAdjustmentDescription[]; extern const char kTouchDragDropName[]; extern const char kTouchDragDropDescription[]; extern const char kTouchEventsName[]; extern const char kTouchEventsDescription[]; extern const char kTouchpadOverscrollHistoryNavigationName[]; extern const char kTouchpadOverscrollHistoryNavigationDescription[]; extern const char kTouchSelectionStrategyName[]; extern const char kTouchSelectionStrategyDescription[]; extern const char kTouchSelectionStrategyCharacter[]; extern const char kTouchSelectionStrategyDirection[]; extern const char kTraceUploadUrlName[]; extern const char kTraceUploadUrlDescription[]; extern const char kTraceUploadUrlChoiceOther[]; extern const char kTraceUploadUrlChoiceEmloading[]; extern const char kTraceUploadUrlChoiceQa[]; extern const char kTraceUploadUrlChoiceTesting[]; extern const char kTranslateExplicitLanguageAskName[]; extern const char kTranslateExplicitLanguageAskDescription[]; extern const char kTranslateForceTriggerOnEnglishName[]; extern const char kTranslateForceTriggerOnEnglishDescription[]; extern const char kTranslateRankerEnforcementName[]; extern const char kTranslateRankerEnforcementDescription[]; extern const char kTranslateUIName[]; extern const char kTranslateUIDescription[]; extern const char kTreatInsecureOriginAsSecureName[]; extern const char kTreatInsecureOriginAsSecureDescription[]; extern const char kTrySupportedChannelLayoutsName[]; extern const char kTrySupportedChannelLayoutsDescription[]; extern const char kUnifiedConsentName[]; extern const char kUnifiedConsentDescription[]; extern const char kUiPartialSwapName[]; extern const char kUiPartialSwapDescription[]; extern const char kUseDdljsonApiName[]; extern const char kUseDdljsonApiDescription[]; extern const char kUseModernMediaControlsName[]; extern const char kUseModernMediaControlsDescription[]; extern const char kUsePdfCompositorServiceName[]; extern const char kUsePdfCompositorServiceDescription[]; extern const char kUserActivationV2Name[]; extern const char kUserActivationV2Description[]; extern const char kUserConsentForExtensionScriptsName[]; extern const char kUserConsentForExtensionScriptsDescription[]; extern const char kUseSuggestionsEvenIfFewFeatureName[]; extern const char kUseSuggestionsEvenIfFewFeatureDescription[]; extern const char kV8CacheOptionsName[]; extern const char kV8CacheOptionsDescription[]; extern const char kV8CacheOptionsParse[]; extern const char kV8CacheOptionsCode[]; extern const char kV8VmFutureName[]; extern const char kV8VmFutureDescription[]; extern const char kV8OrinocoName[]; extern const char kV8OrinocoDescription[]; extern const char kVideoFullscreenOrientationLockName[]; extern const char kVideoFullscreenOrientationLockDescription[]; extern const char kVideoRotateToFullscreenName[]; extern const char kVideoRotateToFullscreenDescription[]; extern const char kWalletServiceUseSandboxName[]; extern const char kWalletServiceUseSandboxDescription[]; extern const char kWebglDraftExtensionsName[]; extern const char kWebglDraftExtensionsDescription[]; extern const char kWebMidiName[]; extern const char kWebMidiDescription[]; extern const char kWebPaymentsName[]; extern const char kWebPaymentsDescription[]; extern const char kWebPaymentsModifiersName[]; extern const char kWebPaymentsModifiersDescription[]; extern const char kWebrtcEchoCanceller3Name[]; extern const char kWebrtcEchoCanceller3Description[]; extern const char kWebrtcH264WithOpenh264FfmpegName[]; extern const char kWebrtcH264WithOpenh264FfmpegDescription[]; extern const char kWebrtcHideLocalIpsWithMdnsName[]; extern const char kWebrtcHideLocalIpsWithMdnsDecription[]; extern const char kWebrtcHybridAgcName[]; extern const char kWebrtcHybridAgcDescription[]; extern const char kWebrtcHwDecodingName[]; extern const char kWebrtcHwDecodingDescription[]; extern const char kWebrtcHwEncodingName[]; extern const char kWebrtcHwEncodingDescription[]; extern const char kWebrtcHwH264EncodingName[]; extern const char kWebrtcHwH264EncodingDescription[]; extern const char kWebrtcHwVP8EncodingName[]; extern const char kWebrtcHwVP8EncodingDescription[]; extern const char kWebrtcNewEncodeCpuLoadEstimatorName[]; extern const char kWebrtcNewEncodeCpuLoadEstimatorDescription[]; extern const char kWebRtcRemoteEventLogName[]; extern const char kWebRtcRemoteEventLogDescription[]; extern const char kWebrtcSrtpAesGcmName[]; extern const char kWebrtcSrtpAesGcmDescription[]; extern const char kWebrtcSrtpEncryptedHeadersName[]; extern const char kWebrtcSrtpEncryptedHeadersDescription[]; extern const char kWebrtcStunOriginName[]; extern const char kWebrtcStunOriginDescription[]; extern const char kWebrtcUnifiedPlanByDefaultName[]; extern const char kWebrtcUnifiedPlanByDefaultDescription[]; extern const char kWebvrName[]; extern const char kWebvrDescription[]; extern const char kWebXrName[]; extern const char kWebXrDescription[]; extern const char kWebXrGamepadSupportName[]; extern const char kWebXrGamepadSupportDescription[]; extern const char kWebXrHitTestName[]; extern const char kWebXrHitTestDescription[]; extern const char kWebXrOrientationSensorDeviceName[]; extern const char kWebXrOrientationSensorDeviceDescription[]; extern const char kZeroCopyName[]; extern const char kZeroCopyDescription[]; // Android -------------------------------------------------------------------- #if defined(OS_ANDROID) extern const char kAiaFetchingName[]; extern const char kAiaFetchingDescription[]; extern const char kAccessibilityTabSwitcherName[]; extern const char kAccessibilityTabSwitcherDescription[]; extern const char kAllowRemoteContextForNotificationsName[]; extern const char kAllowRemoteContextForNotificationsDescription[]; extern const char kAndroidAutofillAccessibilityName[]; extern const char kAndroidAutofillAccessibilityDescription[]; extern const char kAndroidPaymentAppsName[]; extern const char kAndroidPaymentAppsDescription[]; extern const char kAndroidSurfaceControl[]; extern const char kAndroidSurfaceControlDescription[]; extern const char kAppNotificationStatusMessagingName[]; extern const char kAppNotificationStatusMessagingDescription[]; extern const char kAsyncDnsName[]; extern const char kAsyncDnsDescription[]; extern const char kAutoFetchOnNetErrorPageName[]; extern const char kAutoFetchOnNetErrorPageDescription[]; extern const char kAutofillAccessoryViewName[]; extern const char kAutofillAccessoryViewDescription[]; extern const char kBackgroundLoaderForDownloadsName[]; extern const char kBackgroundLoaderForDownloadsDescription[]; extern const char kBackgroundTaskComponentUpdateName[]; extern const char kBackgroundTaskComponentUpdateDescription[]; extern const char kCCTModuleName[]; extern const char kCCTModuleDescription[]; extern const char kCCTModuleCacheName[]; extern const char kCCTModuleCacheDescription[]; extern const char kCCTModuleCustomHeaderName[]; extern const char kCCTModuleCustomHeaderDescription[]; extern const char kCCTModuleDexLoadingName[]; extern const char kCCTModuleDexLoadingDescription[]; extern const char kCCTModulePostMessageName[]; extern const char kCCTModulePostMessageDescription[]; extern const char kCCTModuleUseIntentExtrasName[]; extern const char kCCTModuleUseIntentExtrasDescription[]; extern const char kChromeDuetName[]; extern const char kChromeDuetDescription[]; extern const char kClearOldBrowsingDataName[]; extern const char kClearOldBrowsingDataDescription[]; extern const char kContentSuggestionsCategoryOrderName[]; extern const char kContentSuggestionsCategoryOrderDescription[]; extern const char kContentSuggestionsCategoryRankerName[]; extern const char kContentSuggestionsCategoryRankerDescription[]; extern const char kContentSuggestionsDebugLogName[]; extern const char kContentSuggestionsDebugLogDescription[]; extern const char kContextualSearchMlTapSuppressionName[]; extern const char kContextualSearchMlTapSuppressionDescription[]; extern const char kContextualSearchName[]; extern const char kContextualSearchDescription[]; extern const char kContextualSearchRankerQueryName[]; extern const char kContextualSearchRankerQueryDescription[]; extern const char kContextualSearchSecondTapName[]; extern const char kContextualSearchSecondTapDescription[]; extern const char kContextualSearchUnityIntegrationName[]; extern const char kContextualSearchUnityIntegrationDescription[]; extern const char kDisplayCutoutAPIName[]; extern const char kDisplayCutoutAPIDescription[]; extern const char kDontPrefetchLibrariesName[]; extern const char kDontPrefetchLibrariesDescription[]; extern const char kDownloadsLocationChangeName[]; extern const char kDownloadsLocationChangeDescription[]; extern const char kDownloadProgressInfoBarName[]; extern const char kDownloadProgressInfoBarDescription[]; extern const char kDownloadHomeV2Name[]; extern const char kDownloadHomeV2Description[]; extern const char kEnableAndroidPayIntegrationV1Name[]; extern const char kEnableAndroidPayIntegrationV1Description[]; extern const char kEnableAndroidPayIntegrationV2Name[]; extern const char kEnableAndroidPayIntegrationV2Description[]; extern const char kAutofillManualFallbackAndroidName[]; extern const char kAutofillManualFallbackAndroidDescription[]; extern const char kEnableAutofillRefreshStyleName[]; extern const char kEnableAutofillRefreshStyleDescription[]; extern const char kEnableAndroidSpellcheckerName[]; extern const char kEnableAndroidSpellcheckerDescription[]; extern const char kEnableCommandLineOnNonRootedName[]; extern const char kEnableCommandLineOnNoRootedDescription[]; extern const char kEnableContentSuggestionsNewFaviconServerName[]; extern const char kEnableContentSuggestionsNewFaviconServerDescription[]; extern const char kEnableContentSuggestionsThumbnailDominantColorName[]; extern const char kEnableContentSuggestionsThumbnailDominantColorDescription[]; extern const char kEnableCustomContextMenuName[]; extern const char kEnableCustomContextMenuDescription[]; extern const char kEnableMediaControlsExpandGestureName[]; extern const char kEnableMediaControlsExpandGestureDescription[]; extern const char kEnableOmniboxClipboardProviderName[]; extern const char kEnableOmniboxClipboardProviderDescription[]; extern const char kEnableNtpAssetDownloadSuggestionsName[]; extern const char kEnableNtpAssetDownloadSuggestionsDescription[]; extern const char kEnableNtpBookmarkSuggestionsName[]; extern const char kEnableNtpBookmarkSuggestionsDescription[]; extern const char kEnableNtpOfflinePageDownloadSuggestionsName[]; extern const char kEnableNtpOfflinePageDownloadSuggestionsDescription[]; extern const char kEnableNtpRemoteSuggestionsName[]; extern const char kEnableNtpRemoteSuggestionsDescription[]; extern const char kEnableNtpSnippetsVisibilityName[]; extern const char kEnableNtpSnippetsVisibilityDescription[]; extern const char kEnableNtpSuggestionsNotificationsName[]; extern const char kEnableNtpSuggestionsNotificationsDescription[]; extern const char kEnableOfflinePreviewsName[]; extern const char kEnableOfflinePreviewsDescription[]; extern const char kEnableOskOverscrollName[]; extern const char kEnableOskOverscrollDescription[]; extern const char kEnableWebNfcName[]; extern const char kEnableWebNfcDescription[]; extern const char kEnableWebPaymentsMethodSectionOrderV2Name[]; extern const char kEnableWebPaymentsMethodSectionOrderV2Description[]; extern const char kEphemeralTabName[]; extern const char kEphemeralTabDescription[]; extern const char kExploreSitesName[]; extern const char kExploreSitesDescription[]; extern const char kForegroundNotificationManagerName[]; extern const char kForegroundNotificationManagerDescription[]; extern const char kGestureNavigationName[]; extern const char kGestureNavigationDescription[]; extern const char kGrantNotificationsToDSEName[]; extern const char kGrantNotificationsToDSENameDescription[]; extern const char kHomePageButtonName[]; extern const char kHomePageButtonDescription[]; extern const char kHomepageTileName[]; extern const char kHomepageTileDescription[]; extern const char kIncognitoStringsName[]; extern const char kIncognitoStringsDescription[]; extern const char kInterestFeedContentSuggestionsName[]; extern const char kInterestFeedContentSuggestionsDescription[]; extern const char kKeepPrefetchedContentSuggestionsName[]; extern const char kKeepPrefetchedContentSuggestionsDescription[]; extern const char kLanguagesPreferenceName[]; extern const char kLanguagesPreferenceDescription[]; extern const char kLsdPermissionPromptName[]; extern const char kLsdPermissionPromptDescription[]; extern const char kModalPermissionDialogViewName[]; extern const char kModalPermissionDialogViewDescription[]; extern const char kMediaScreenCaptureName[]; extern const char kMediaScreenCaptureDescription[]; extern const char kModalPermissionPromptsName[]; extern const char kModalPermissionPromptsDescription[]; extern const char kNewContactsPickerName[]; extern const char kNewContactsPickerDescription[]; extern const char kNewNetErrorPageUIName[]; extern const char kNewNetErrorPageUIDescription[]; extern const char kNewPhotoPickerName[]; extern const char kNewPhotoPickerDescription[]; extern const char kNoCreditCardAbort[]; extern const char kNoCreditCardAbortDescription[]; extern const char kNtpButtonName[]; extern const char kNtpButtonDescription[]; extern const char kOfflineBookmarksName[]; extern const char kOfflineBookmarksDescription[]; extern const char kOfflineIndicatorAlwaysHttpProbeName[]; extern const char kOfflineIndicatorAlwaysHttpProbeDescription[]; extern const char kOfflineIndicatorChoiceName[]; extern const char kOfflineIndicatorChoiceDescription[]; extern const char kOfflinePagesCtName[]; extern const char kOfflinePagesCtDescription[]; extern const char kOfflinePagesCtV2Name[]; extern const char kOfflinePagesCtV2Description[]; extern const char kOfflinePagesCTSuppressNotificationsName[]; extern const char kOfflinePagesCTSuppressNotificationsDescription[]; extern const char kOfflinePagesDescriptiveFailStatusName[]; extern const char kOfflinePagesDescriptiveFailStatusDescription[]; extern const char kOfflinePagesDescriptivePendingStatusName[]; extern const char kOfflinePagesDescriptivePendingStatusDescription[]; extern const char kOfflinePagesInDownloadHomeOpenInCctName[]; extern const char kOfflinePagesInDownloadHomeOpenInCctDescription[]; extern const char kOfflinePagesLimitlessPrefetchingName[]; extern const char kOfflinePagesLimitlessPrefetchingDescription[]; extern const char kOfflinePagesLoadSignalCollectingName[]; extern const char kOfflinePagesLoadSignalCollectingDescription[]; extern const char kOfflinePagesPrefetchingName[]; extern const char kOfflinePagesPrefetchingDescription[]; extern const char kOfflinePagesResourceBasedSnapshotName[]; extern const char kOfflinePagesResourceBasedSnapshotDescription[]; extern const char kOfflinePagesRenovationsName[]; extern const char kOfflinePagesRenovationsDescription[]; extern const char kOfflinePagesSharingName[]; extern const char kOfflinePagesSharingDescription[]; extern const char kOfflinePagesLivePageSharingName[]; extern const char kOfflinePagesLivePageSharingDescription[]; extern const char kOfflinePagesShowAlternateDinoPageName[]; extern const char kOfflinePagesShowAlternateDinoPageDescription[]; extern const char kOfflinePagesSvelteConcurrentLoadingName[]; extern const char kOfflinePagesSvelteConcurrentLoadingDescription[]; extern const char kOffliningRecentPagesName[]; extern const char kOffliningRecentPagesDescription[]; extern const char kPayWithGoogleV1Name[]; extern const char kPayWithGoogleV1Description[]; extern const char kProgressBarThrottleName[]; extern const char kProgressBarThrottleDescription[]; extern const char kPullToRefreshEffectName[]; extern const char kPullToRefreshEffectDescription[]; extern const char kPwaImprovedSplashScreenName[]; extern const char kPwaImprovedSplashScreenDescription[]; extern const char kPwaPersistentNotificationName[]; extern const char kPwaPersistentNotificationDescription[]; extern const char kReaderModeHeuristicsName[]; extern const char kReaderModeHeuristicsDescription[]; extern const char kReaderModeHeuristicsMarkup[]; extern const char kReaderModeHeuristicsAdaboost[]; extern const char kReaderModeHeuristicsAllArticles[]; extern const char kReaderModeHeuristicsAlwaysOff[]; extern const char kReaderModeHeuristicsAlwaysOn[]; extern const char kReaderModeInCCTName[]; extern const char kReaderModeInCCTDescription[]; extern const char kSafeBrowsingTelemetryForApkDownloadsName[]; extern const char kSafeBrowsingTelemetryForApkDownloadsDescription[]; extern const char kSafeBrowsingUseLocalBlacklistsV2Name[]; extern const char kSafeBrowsingUseLocalBlacklistsV2Description[]; extern const char kSearchReadyOmniboxName[]; extern const char kSearchReadyOmniboxDescription[]; extern const char kSetMarketUrlForTestingName[]; extern const char kSetMarketUrlForTestingDescription[]; extern const char kSiteExplorationUiName[]; extern const char kSiteExplorationUiDescription[]; extern const char kSpannableInlineAutocompleteName[]; extern const char kSpannableInlineAutocompleteDescription[]; extern const char kStrictSiteIsolationName[]; extern const char kStrictSiteIsolationDescription[]; extern const char kTranslateAndroidManualTriggerName[]; extern const char kTranslateAndroidManualTriggerDescription[]; extern const char kUpdateMenuBadgeName[]; extern const char kUpdateMenuBadgeDescription[]; extern const char kUpdateMenuItemCustomSummaryDescription[]; extern const char kUpdateMenuItemCustomSummaryName[]; extern const char kUpdateMenuTypeName[]; extern const char kUpdateMenuTypeDescription[]; extern const char kUpdateMenuTypeNone[]; extern const char kUpdateMenuTypeUpdateAvailable[]; extern const char kUpdateMenuTypeUnsupportedOSVersion[]; extern const char kThirdPartyDoodlesName[]; extern const char kThirdPartyDoodlesDescription[]; extern const char kWebXrRenderPathName[]; extern const char kWebXrRenderPathDescription[]; extern const char kWebXrRenderPathChoiceClientWaitDescription[]; extern const char kWebXrRenderPathChoiceGpuFenceDescription[]; extern const char kWebXrRenderPathChoiceSharedBufferDescription[]; #if BUILDFLAG(ENABLE_ANDROID_NIGHT_MODE) extern const char kAndroidNightModeName[]; extern const char kAndroidNightModeDescription[]; #endif // BUILDFLAG(ENABLE_ANDROID_NIGHT_MODE) // Non-Android ---------------------------------------------------------------- #else // !defined(OS_ANDROID) extern const char kAccountConsistencyName[]; extern const char kAccountConsistencyDescription[]; extern const char kAccountConsistencyChoiceMirror[]; extern const char kAccountConsistencyChoiceDice[]; extern const char kAutofillDropdownLayoutName[]; extern const char kAutofillDropdownLayoutDescription[]; extern const char kDoodlesOnLocalNtpName[]; extern const char kDoodlesOnLocalNtpDescription[]; extern const char kSearchSuggestionsOnLocalNtpName[]; extern const char kSearchSuggestionsOnLocalNtpDescription[]; extern const char kPromosOnLocalNtpName[]; extern const char kPromosOnLocalNtpDescription[]; extern const char kEnableWebAuthenticationBleSupportName[]; extern const char kEnableWebAuthenticationBleSupportDescription[]; extern const char kEnableWebAuthenticationTestingAPIName[]; extern const char kEnableWebAuthenticationTestingAPIDescription[]; extern const char kHappinessTrackingSurveysForDesktopName[]; extern const char kHappinessTrackingSurveysForDesktopDescription[]; extern const char kInfiniteSessionRestoreName[]; extern const char kInfiniteSessionRestoreDescription[]; extern const char kOmniboxDriveSuggestionsName[]; extern const char kOmniboxDriveSuggestionsDescriptions[]; extern const char kOmniboxPedalSuggestionsName[]; extern const char kOmniboxPedalSuggestionsDescription[]; extern const char kOmniboxReverseAnswersName[]; extern const char kOmniboxReverseAnswersDescription[]; extern const char kOmniboxRichEntitySuggestionsName[]; extern const char kOmniboxRichEntitySuggestionsDescription[]; extern const char kOmniboxTabSwitchSuggestionsName[]; extern const char kOmniboxTabSwitchSuggestionsDescription[]; extern const char kOmniboxTailSuggestionsName[]; extern const char kOmniboxTailSuggestionsDescription[]; extern const char kPageAlmostIdleName[]; extern const char kPageAlmostIdleDescription[]; extern const char kProactiveTabFreezeAndDiscardName[]; extern const char kProactiveTabFreezeAndDiscardDescription[]; extern const char kShowManagedUiName[]; extern const char kShowManagedUiDescription[]; extern const char kSiteCharacteristicsDatabaseName[]; extern const char kSiteCharacteristicsDatabaseDescription[]; extern const char kUseGoogleLocalNtpName[]; extern const char kUseGoogleLocalNtpDescription[]; #if defined(GOOGLE_CHROME_BUILD) extern const char kGoogleBrandedContextMenuName[]; extern const char kGoogleBrandedContextMenuDescription[]; #endif // defined(GOOGLE_CHROME_BUILD) #endif // defined(OS_ANDROID) // Windows -------------------------------------------------------------------- #if defined(OS_WIN) extern const char kCalculateNativeWinOcclusionName[]; extern const char kCalculateNativeWinOcclusionDescription[]; extern const char kCloudPrintXpsName[]; extern const char kCloudPrintXpsDescription[]; extern const char kDisablePostscriptPrinting[]; extern const char kDisablePostscriptPrintingDescription[]; extern const char kEnableAppcontainerName[]; extern const char kEnableAppcontainerDescription[]; extern const char kEnableGpuAppcontainerName[]; extern const char kEnableGpuAppcontainerDescription[]; extern const char kGdiTextPrinting[]; extern const char kGdiTextPrintingDescription[]; extern const char kTraceExportEventsToEtwName[]; extern const char kTraceExportEventsToEtwDesription[]; extern const char kUseAngleName[]; extern const char kUseAngleDescription[]; extern const char kUseAngleDefault[]; extern const char kUseAngleGL[]; extern const char kUseAngleD3D11[]; extern const char kUseAngleD3D9[]; extern const char kUseWinrtMidiApiName[]; extern const char kUseWinrtMidiApiDescription[]; extern const char kWindows10CustomTitlebarName[]; extern const char kWindows10CustomTitlebarDescription[]; #endif // defined(OS_WIN) // Mac ------------------------------------------------------------------------ #if defined(OS_MACOSX) extern const char kContentFullscreenName[]; extern const char kContentFullscreenDescription[]; extern const char kHostedAppsInWindowsName[]; extern const char kHostedAppsInWindowsDescription[]; extern const char kCreateAppWindowsInAppShimProcessName[]; extern const char kCreateAppWindowsInAppShimProcessDescription[]; extern const char kEnableCustomMacPaperSizesName[]; extern const char kEnableCustomMacPaperSizesDescription[]; extern const char kMacTouchBarName[]; extern const char kMacTouchBarDescription[]; extern const char kMacV2GPUSandboxName[]; extern const char kMacV2GPUSandboxDescription[]; extern const char kMacViewsNativeAppWindowsName[]; extern const char kMacViewsNativeAppWindowsDescription[]; extern const char kMacViewsTaskManagerName[]; extern const char kMacViewsTaskManagerDescription[]; extern const char kTextSuggestionsTouchBarName[]; extern const char kTextSuggestionsTouchBarDescription[]; // Non-Mac -------------------------------------------------------------------- #else // !defined(OS_MACOSX) extern const char kPermissionPromptPersistenceToggleName[]; extern const char kPermissionPromptPersistenceToggleDescription[]; #endif // defined(OS_MACOSX) // Chrome OS ------------------------------------------------------------------ #if defined(OS_CHROMEOS) extern const char kAcceleratedMjpegDecodeName[]; extern const char kAcceleratedMjpegDecodeDescription[]; extern const char kAllowTouchpadThreeFingerClickName[]; extern const char kAllowTouchpadThreeFingerClickDescription[]; extern const char kArcAvailableForChildName[]; extern const char kArcAvailableForChildDescription[]; extern const char kArcBootCompleted[]; extern const char kArcBootCompletedDescription[]; extern const char kArcCupsApiName[]; extern const char kArcCupsApiDescription[]; extern const char kArcDocumentsProviderName[]; extern const char kArcDocumentsProviderDescription[]; extern const char kArcFilePickerExperimentName[]; extern const char kArcFilePickerExperimentDescription[]; extern const char kArcNativeBridgeExperimentName[]; extern const char kArcNativeBridgeExperimentDescription[]; extern const char kArcUsbHostName[]; extern const char kArcUsbHostDescription[]; extern const char kArcVpnName[]; extern const char kArcVpnDescription[]; extern const char kAshEnableDisplayMoveWindowAccelsName[]; extern const char kAshEnableDisplayMoveWindowAccelsDescription[]; extern const char kAshEnablePersistentWindowBoundsName[]; extern const char kAshEnablePersistentWindowBoundsDescription[]; extern const char kAshEnablePipRoundedCornersName[]; extern const char kAshEnablePipRoundedCornersDescription[]; extern const char kAshEnableUnifiedDesktopName[]; extern const char kAshEnableUnifiedDesktopDescription[]; extern const char kAshShelfColorName[]; extern const char kAshShelfColorDescription[]; extern const char kAshShelfColorScheme[]; extern const char kAshShelfColorSchemeDescription[]; extern const char kAshShelfColorSchemeLightVibrant[]; extern const char kAshShelfColorSchemeNormalVibrant[]; extern const char kAshShelfColorSchemeDarkVibrant[]; extern const char kAshShelfColorSchemeLightMuted[]; extern const char kAshShelfColorSchemeNormalMuted[]; extern const char kAshShelfColorSchemeDarkMuted[]; extern const char kBulkPrintersName[]; extern const char kBulkPrintersDescription[]; extern const char kCaptivePortalBypassProxyName[]; extern const char kCaptivePortalBypassProxyDescription[]; extern const char kCrOSComponentName[]; extern const char kCrOSComponentDescription[]; extern const char kCrOSContainerName[]; extern const char kCrOSContainerDescription[]; extern const char kCrosRegionsModeName[]; extern const char kCrosRegionsModeDescription[]; extern const char kCrosRegionsModeDefault[]; extern const char kCrosRegionsModeOverride[]; extern const char kCrosRegionsModeHide[]; extern const char kCrostiniAppSearchName[]; extern const char kCrostiniAppSearchDescription[]; extern const char kCrostiniBackupName[]; extern const char kCrostiniBackupDescription[]; extern const char kCrostiniFilesName[]; extern const char kCrostiniFilesDescription[]; extern const char kCrostiniUsbSupportName[]; extern const char kCrostiniUsbSupportDescription[]; extern const char kCryptAuthV2EnrollmentName[]; extern const char kCryptAuthV2EnrollmentDescription[]; extern const char kDisableExplicitDmaFencesName[]; extern const char kDisableExplicitDmaFencesDescription[]; extern const char kDisableSystemTimezoneAutomaticDetectionName[]; extern const char kDisableSystemTimezoneAutomaticDetectionDescription[]; extern const char kDisableTabletAutohideTitlebarsName[]; extern const char kDisableTabletAutohideTitlebarsDescription[]; extern const char kDisableTabletSplitViewName[]; extern const char kDisableTabletSplitViewDescription[]; extern const char kDoubleTapToZoomInTabletModeName[]; extern const char kDoubleTapToZoomInTabletModeDescription[]; extern const char kEnableAppListSearchAutocompleteName[]; extern const char kEnableAppListSearchAutocompleteDescription[]; extern const char kEnableAppShortcutSearchName[]; extern const char kEnableAppShortcutSearchDescription[]; extern const char kEnableAppDataSearchName[]; extern const char kEnableAppDataSearchDescription[]; extern const char kEnableAppsGridGapFeatureName[]; extern const char kEnableAppsGridGapFeatureDescription[]; extern const char kEnableArcUnifiedAudioFocusName[]; extern const char kEnableArcUnifiedAudioFocusDescription[]; extern const char kEnableAssistantVoiceMatchName[]; extern const char kEnableAssistantVoiceMatchDescription[]; extern const char kEnableAssistantAppSupportName[]; extern const char kEnableAssistantAppSupportDescription[]; extern const char kEnableBackgroundBlurName[]; extern const char kEnableBackgroundBlurDescription[]; extern const char kEnableChromeOsAccountManagerName[]; extern const char kEnableChromeOsAccountManagerDescription[]; extern const char kEnableDiscoverAppName[]; extern const char kEnableDiscoverAppDescription[]; extern const char kEnableDragTabsInTabletModeName[]; extern const char kEnableDragTabsInTabletModeDescription[]; extern const char kEnableDriveFsName[]; extern const char kEnableDriveFsDescription[]; extern const char kEnableMyFilesVolumeName[]; extern const char kEnableMyFilesVolumeDescription[]; extern const char kEnableEhvInputName[]; extern const char kEnableEhvInputDescription[]; extern const char kEnableEncryptionMigrationName[]; extern const char kEnableEncryptionMigrationDescription[]; extern const char kEnableFullscreenHandwritingVirtualKeyboardName[]; extern const char kEnableFullscreenHandwritingVirtualKeyboardDescription[]; extern const char kEnableGoogleAssistantName[]; extern const char kEnableGoogleAssistantDescription[]; extern const char kEnableGoogleAssistantDspName[]; extern const char kEnableGoogleAssistantDspDescription[]; extern const char kEnableGoogleAssistantStereoInputName[]; extern const char kEnableGoogleAssistantStereoInputDescription[]; extern const char kEnableHomeLauncherName[]; extern const char kEnableHomeLauncherDescription[]; extern const char kEnableHomeLauncherGesturesName[]; extern const char kEnableHomeLauncherGesturesDescription[]; extern const char kEnableImeMenuName[]; extern const char kEnableImeMenuDescription[]; extern const char kEnableOobeRecommendAppsScreenName[]; extern const char kEnableOobeRecommendAppsScreenDescription[]; extern const char kEnablePerUserTimezoneName[]; extern const char kEnablePerUserTimezoneDescription[]; extern const char kEnablePlayStoreSearchName[]; extern const char kEnablePlayStoreSearchDescription[]; extern const char kEnableSettingsShortcutSearchName[]; extern const char kEnableSettingsShortcutSearchDescription[]; extern const char kEnableStylusVirtualKeyboardName[]; extern const char kEnableStylusVirtualKeyboardDescription[]; extern const char kEnableVideoPlayerNativeControlsName[]; extern const char kEnableVideoPlayerNativeControlsDescription[]; extern const char kEnableVirtualKeyboardUkmName[]; extern const char kEnableVirtualKeyboardUkmDescription[]; extern const char kEnableZeroStateSuggestionsName[]; extern const char kEnableZeroStateSuggestionsDescription[]; extern const char kEolNotificationName[]; extern const char kEolNotificationDescription[]; extern const char kExperimentalAccessibilityChromeVoxLanguageSwitchingName[]; extern const char kExperimentalAccessibilityChromeVoxLanguageSwitchingDescription[]; extern const char kFileManagerTouchModeName[]; extern const char kFileManagerTouchModeDescription[]; extern const char kFirstRunUiTransitionsName[]; extern const char kFirstRunUiTransitionsDescription[]; extern const char kForceEnableStylusToolsName[]; extern const char kForceEnableStylusToolsDescription[]; extern const char kGestureEditingName[]; extern const char kGestureEditingDescription[]; extern const char kGestureTypingName[]; extern const char kGestureTypingDescription[]; extern const char kInputViewName[]; extern const char kInputViewDescription[]; extern const char kImeServiceName[]; extern const char kImeServiceDescription[]; extern const char kLockScreenNotificationName[]; extern const char kLockScreenNotificationDescription[]; extern const char kMashOopVizName[]; extern const char kMashOopVizDescription[]; extern const char kMaterialDesignInkDropAnimationSpeedName[]; extern const char kMaterialDesignInkDropAnimationSpeedDescription[]; extern const char kMaterialDesignInkDropAnimationFast[]; extern const char kMaterialDesignInkDropAnimationSlow[]; extern const char kMemoryPressureThresholdName[]; extern const char kMemoryPressureThresholdDescription[]; extern const char kConservativeThresholds[]; extern const char kAggressiveCacheDiscardThresholds[]; extern const char kAggressiveTabDiscardThresholds[]; extern const char kAggressiveThresholds[]; extern const char kMtpWriteSupportName[]; extern const char kMtpWriteSupportDescription[]; extern const char kNetworkPortalNotificationName[]; extern const char kNetworkPortalNotificationDescription[]; extern const char kNewKoreanImeName[]; extern const char kNewKoreanImeDescription[]; extern const char kNewZipUnpackerName[]; extern const char kNewZipUnpackerDescription[]; extern const char kOfficeEditingComponentAppName[]; extern const char kOfficeEditingComponentAppDescription[]; extern const char kPhysicalKeyboardAutocorrectName[]; extern const char kPhysicalKeyboardAutocorrectDescription[]; extern const char kPrinterProviderSearchAppName[]; extern const char kPrinterProviderSearchAppDescription[]; extern const char kQuickUnlockPinName[]; extern const char kQuickUnlockPinDescription[]; extern const char kQuickUnlockPinSignin[]; extern const char kQuickUnlockPinSigninDescription[]; extern const char kQuickUnlockFingerprint[]; extern const char kQuickUnlockFingerprintDescription[]; extern const char kShowTapsName[]; extern const char kShowTapsDescription[]; extern const char kShowTouchHudName[]; extern const char kShowTouchHudDescription[]; extern const char kSingleProcessMashName[]; extern const char kSingleProcessMashDescription[]; extern const char kSlideTopChromeWithPageScrollsName[]; extern const char kSlideTopChromeWithPageScrollsDescription[]; extern const char kSmartTextSelectionName[]; extern const char kSmartTextSelectionDescription[]; extern const char kUiShowCompositedLayerBordersName[]; extern const char kUiShowCompositedLayerBordersDescription[]; extern const char kUiShowCompositedLayerBordersRenderPass[]; extern const char kUiShowCompositedLayerBordersSurface[]; extern const char kUiShowCompositedLayerBordersLayer[]; extern const char kUiShowCompositedLayerBordersAll[]; extern const char kUiSlowAnimationsName[]; extern const char kUiSlowAnimationsDescription[]; extern const char kTetherName[]; extern const char kTetherDescription[]; extern const char kTouchscreenCalibrationName[]; extern const char kTouchscreenCalibrationDescription[]; extern const char kUiDevToolsName[]; extern const char kUiDevToolsDescription[]; extern const char kUiModeName[]; extern const char kUiModeDescription[]; extern const char kUiModeTablet[]; extern const char kUiModeClamshell[]; extern const char kUiModeAuto[]; extern const char kUnfilteredBluetoothDevicesName[]; extern const char kUnfilteredBluetoothDevicesDescription[]; extern const char kUsbguardName[]; extern const char kUsbguardDescription[]; extern const char kShillSandboxingName[]; extern const char kShillSandboxingDescription[]; extern const char kFsNosymfollowName[]; extern const char kFsNosymfollowDescription[]; extern const char kUseMashName[]; extern const char kUseMashDescription[]; extern const char kUseMonitorColorSpaceName[]; extern const char kUseMonitorColorSpaceDescription[]; extern const char kVaapiJpegImageDecodeAccelerationName[]; extern const char kVaapiJpegImageDecodeAccelerationDescription[]; extern const char kVideoPlayerChromecastSupportName[]; extern const char kVideoPlayerChromecastSupportDescription[]; extern const char kVirtualKeyboardName[]; extern const char kVirtualKeyboardDescription[]; extern const char kVirtualKeyboardOverscrollName[]; extern const char kVirtualKeyboardOverscrollDescription[]; extern const char kVoiceInputName[]; extern const char kVoiceInputDescription[]; extern const char kWakeOnPacketsName[]; extern const char kWakeOnPacketsDescription[]; #endif // #if defined(OS_CHROMEOS) // Random platform combinations ----------------------------------------------- #if defined(OS_WIN) || defined(OS_LINUX) extern const char kEnableInputImeApiName[]; extern const char kEnableInputImeApiDescription[]; #endif // defined(OS_WIN) || defined(OS_LINUX) extern const char kExperimentalUiName[]; extern const char kExperimentalUiDescription[]; #if defined(OS_WIN) || defined(OS_MACOSX) extern const char kAutomaticTabDiscardingName[]; extern const char kAutomaticTabDiscardingDescription[]; #endif // defined(OS_WIN) || defined(OS_MACOSX) #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) extern const char kDirectManipulationStylusName[]; extern const char kDirectManipulationStylusDescription[]; #endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) #if defined(OS_MACOSX) || defined(OS_CHROMEOS) extern const char kForceEnableSystemAecName[]; extern const char kForceEnableSystemAecDescription[]; #endif // defined(OS_MACOSX) || defined(OS_CHROMEOS) // Feature flags -------------------------------------------------------------- #if defined(DCHECK_IS_CONFIGURABLE) extern const char kDcheckIsFatalName[]; extern const char kDcheckIsFatalDescription[]; #endif // defined(DCHECK_IS_CONFIGURABLE) #if BUILDFLAG(ENABLE_VR) extern const char kWebVrVsyncAlignName[]; extern const char kWebVrVsyncAlignDescription[]; #if BUILDFLAG(ENABLE_OCULUS_VR) extern const char kOculusVRName[]; extern const char kOculusVRDescription[]; #endif // ENABLE_OCULUS_VR #if BUILDFLAG(ENABLE_OPENVR) extern const char kOpenVRName[]; extern const char kOpenVRDescription[]; #endif // ENABLE_OPENVR #if BUILDFLAG(ENABLE_WINDOWS_MR) extern const char kWindowsMixedRealityName[]; extern const char kWindowsMixedRealityDescription[]; #endif // ENABLE_WINDOWS_MR #if BUILDFLAG(ENABLE_ISOLATED_XR_SERVICE) extern const char kXRSandboxName[]; extern const char kXRSandboxDescription[]; #endif // ENABLE_ISOLATED_XR_SERVICE #endif // ENABLE_VR #if BUILDFLAG(ENABLE_NACL) extern const char kNaclDebugMaskName[]; extern const char kNaclDebugMaskDescription[]; extern const char kNaclDebugMaskChoiceDebugAll[]; extern const char kNaclDebugMaskChoiceExcludeUtilsPnacl[]; extern const char kNaclDebugMaskChoiceIncludeDebug[]; extern const char kNaclDebugName[]; extern const char kNaclDebugDescription[]; extern const char kNaclName[]; extern const char kNaclDescription[]; extern const char kPnaclSubzeroName[]; extern const char kPnaclSubzeroDescription[]; #endif // BUILDFLAG(ENABLE_NACL) #if BUILDFLAG(ENABLE_PLUGINS) #if defined(OS_CHROMEOS) extern const char kPdfAnnotations[]; extern const char kPdfAnnotationsDescription[]; #endif // defined(OS_CHROMEOS) extern const char kPdfFormSaveName[]; extern const char kPdfFormSaveDescription[]; extern const char kPdfIsolationName[]; extern const char kPdfIsolationDescription[]; #endif // BUILDFLAG(ENABLE_PLUGINS) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID) extern const char kAutofillCreditCardUploadName[]; extern const char kAutofillCreditCardUploadDescription[]; #endif // defined(TOOLKIT_VIEWS) || defined(OS_ANDROID) #if BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) extern const char kReopenTabInProductHelpName[]; extern const char kReopenTabInProductHelpDescription[]; #endif // BUILDFLAG(ENABLE_DESKTOP_IN_PRODUCT_HELP) extern const char kAvoidFlashBetweenNavigationName[]; extern const char kAvoidFlahsBetweenNavigationDescription[]; #if defined(WEBRTC_USE_PIPEWIRE) extern const char kWebrtcPipeWireCapturerName[]; extern const char kWebrtcPipeWireCapturerDescription[]; #endif // #if defined(WEBRTC_USE_PIPEWIRE) // ============================================================================ // Don't just add flags to the end, put them in the right section in // alphabetical order. See top instructions for more. // ============================================================================ } // namespace flag_descriptions #endif // CHROME_BROWSER_FLAG_DESCRIPTIONS_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
92d7b1167d4c0f75e8b3ff544376cb5864aa0f42
0e79b11e100c78e1d0b7159cb6ae369a2942d6d0
/dcmap/dcmapsys/utils.h
3214281e7a94340c416bfa8c52410425b3c53909
[]
no_license
JlblC/dcmap
e3be11c4c9da9ac4f0be693fee3b4fb2cf8af6ec
e2cbfa43dfe04125d19b4bae34e9a552db307198
refs/heads/master
2021-07-04T01:47:45.249683
2014-06-08T17:46:32
2014-06-08T17:46:32
20,622,342
3
2
null
null
null
null
UTF-8
C++
false
false
3,045
h
#pragma once #include <boost/format.hpp> #include "../dcmapsyslib.h" #include "g_file_util.h" template<class T> dcmap::string ToStr8(T const& d) { return gsys::to_str(d); } #define ToStr ToStr8 string WideToString(wstring wstr,int Codepage=-1); wstring ToWide(string str,int Codepage=-1); #if DCMAP_WCHAR_T_SIZE == 2 template<class T> dcmap::wstring ToStr16(T const& d) { return gsys::to_wstr(d); } template<class T> dcmap::wstring ToStr32(T const& d) { return gsys::to_wstr(d); } #define ToWStr ToStr16 #define ToDStr ToStr32 #define dcsncpy wcsncpy #define dcslen wcslen // string type conversions #define StrD2C(x) WideToString(x) #define StrC2D(x) ToWide(x) #define StrW2C(x) WideToString(x) #define StrC2W(x) ToWide(x) #define StrD2W(x) (x) #define StrW2D(x) (x) #else dstring StrW2D(wstring const& ws); wstring StrD2W(dstring const& ds); string StrD2C(dstring const& ws); dstring StrC2D(string const& ws); string StrW2C(wstring const& ws); wstring StrC2W(string const& ws); void dcsncpy(dcmapDSTR to,dcmapDCSTR from,size_t n); size_t dcslen(dcmapDCSTR to); template<class T> dcmap::dstring ToStr16(T const& d) { return StrW2D(gsys::to_wstr(d)); } template<class T> dcmap::wstring ToStr32(T const& d) { return gsys::to_wstr(d); } #define ToWStr ToStr32 #define ToDStr ToStr16 #endif #ifdef DCMAP_UNICODE_SYS #define ToFStr ToWStr #define ToUStr ToWStr #else #define ToFStr ToStr #define ToUStr ToStr #endif //std::string WideToString(dcmapDCSTR wstr,int CodePage=-1); //std::wstring ToWide(dcmapCSTR str,int CodePage=-1); sysstring ToSys(dcmapCSTR str,int CodePage=-1); dstring ToDStr(std::string str,int CodePage=-1); sysstring GetAppStartupDir(); bool StrToCoords(dcmapCSTR str,dcmapPOINT& pt); typedef std::vector<sysstring> VecFiles; bool ListDirectory(dcmapFCSTR filename, VecFiles &vec); void DestroyDir(dcmapFCSTR pDir); bool dcmapDeleteFile(dcmapFCSTR pDir); bool dcmapRename(dcmapFCSTR pFrom,dcmapFCSTR pTo); bool dcmapMakeDir(dcmapFCSTR pDir); bool dcmapFileExists(dcmapFCSTR pDir); bool dcmapHardLinkFile(dcmapDCSTR from,dcmapDCSTR to,bool FailIfExists); bool dcmapCopyFile(dcmapFCSTR from,dcmapFCSTR to,bool FailIfExists); boost::format inline format(const std::string & f_string) { using namespace boost::io; using namespace boost; boost::format fmter(f_string); fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) ); return fmter; } boost::wformat inline wformat(const std::wstring & f_string) { using namespace boost::io; using namespace boost; boost::wformat fmter(f_string); fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) ); return fmter; } dcmapWCSTR inline c_str(boost::wformat& f) { static wstring wstr; wstr = boost::str(f); return wstr.c_str(); } dcmapCSTR inline c_str(boost::format& f) { static string wstr; wstr = boost::str(f); return wstr.c_str(); } namespace gsys{class gfile;} using gsys::gfile; gfile* OpenFileReadZ(dcmapFCSTR Filename); gfile* OpenFileCreateZ(dcmapFCSTR Filename,bool z);
[ "jlblc@ya.ru" ]
jlblc@ya.ru
f25a096db0d6c2992ce89d14a563552feb21f764
02695b31daa88d8104956cbc00bce0d38af4499f
/armory/Projectile_Bolt.cpp
c9ad6e508ea734f480d2fc571449c286695cc521
[]
no_license
WeHaveCookie/Raven
c2770aa2e977172ed530e4fd84bf622bbe2feeb3
ac83b30e5651242f1c796e2a2475fb4777a00286
refs/heads/master
2021-01-19T02:35:58.527423
2016-11-30T15:02:24
2016-11-30T15:02:24
73,505,726
0
0
null
null
null
null
UTF-8
C++
false
false
3,074
cpp
#include "Projectile_Bolt.h" #include "../lua/Raven_Scriptor.h" #include "misc/cgdi.h" #include "../Raven_Bot.h" #include "../Raven_Game.h" #include "../constants.h" #include "2d/WallIntersectionTests.h" #include "../Raven_Map.h" #include "../Raven_Messages.h" #include "Messaging/MessageDispatcher.h" //-------------------------- ctor --------------------------------------------- //----------------------------------------------------------------------------- Bolt::Bolt(Raven_Bot* shooter, Vector2D target): Raven_Projectile(target, shooter->GetWorld(), shooter->ID(), shooter->Pos(), shooter->Facing(), script->GetFloat("Bolt_Damage"), script->GetDouble("Bolt_Scale"), script->GetDouble("Bolt_MaxSpeed"), script->GetDouble("Bolt_Mass"), script->GetDouble("Bolt_MaxForce")) { assert (target != Vector2D()); } //------------------------------ Update --------------------------------------- //----------------------------------------------------------------------------- void Bolt::Update() { if (!m_bImpacted) { m_vVelocity = MaxSpeed() * Heading(); //make sure vehicle does not exceed maximum velocity m_vVelocity.Truncate(m_dMaxSpeed); //update the position m_vPosition += m_vVelocity; //if the projectile has reached the target position or it hits an entity //or wall it should explode/inflict damage/whatever and then mark itself //as dead //test to see if the line segment connecting the bolt's current position //and previous position intersects with any bots. Raven_Bot* hit = GetClosestIntersectingBot(m_vPosition - m_vVelocity, m_vPosition); //if hit if (hit) { m_bImpacted = true; m_bDead = true; //send a message to the bot to let it know it's been hit, and who the //shot came from Dispatcher->DispatchMsg(SEND_MSG_IMMEDIATELY, m_iShooterID, hit->ID(), Msg_TakeThatMF, (void*)&m_info); } //test for impact with a wall double dist; if( FindClosestPointOfIntersectionWithWalls(m_vPosition - m_vVelocity, m_vPosition, dist, m_vImpactPoint, m_pWorld->GetMap()->GetWalls())) { m_bDead = true; m_bImpacted = true; m_vPosition = m_vImpactPoint; return; } } } //-------------------------- Render ------------------------------------------- //----------------------------------------------------------------------------- void Bolt::Render() { gdi->ThickGreenPen(); gdi->Line(Pos(), Pos()-Velocity()); }
[ "quentin.gerry@gmail.com" ]
quentin.gerry@gmail.com
ee81283b034dc523f85a3f83b501929963cf4f5c
a97a75e570ea1e21e85e8bf7c75aac6b7bd7df26
/Srishti1/Srishti1.ino
5c77df13d43e1e5fb1b83e490b83c2081001992b
[]
no_license
shawnalexsony/Srishti-projects
d77e8772022f701431f5d76ebef92c978df29393
be888cd49238af1de342b841b43c79ee2594eb91
refs/heads/master
2020-03-23T09:15:25.767349
2018-07-18T03:40:14
2018-07-18T03:40:14
141,376,867
0
0
null
null
null
null
UTF-8
C++
false
false
847
ino
/*LED sequence display with active low switch*/ void setup() { // put your setup code here, to run once: pinMode(5,INPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); digitalWrite(5,HIGH); } void loop() { // put your main code here, to run repeatedly: if(digitalRead(5)==LOW) { digitalWrite(8,HIGH); delay(100); digitalWrite(8,LOW); digitalWrite(9,HIGH); delay(100); digitalWrite(9,LOW); digitalWrite(10,HIGH); delay(100); digitalWrite(10,LOW); digitalWrite(11,HIGH); delay(100); digitalWrite(10,HIGH); digitalWrite(11,LOW); delay(100); digitalWrite(9,HIGH); digitalWrite(10,LOW); delay(100); digitalWrite(9,LOW); } else {digitalWrite(8,LOW); digitalWrite(9,LOW); digitalWrite(10,LOW); digitalWrite(11,LOW); } }
[ "noreply@github.com" ]
shawnalexsony.noreply@github.com
7fe0b843c680ec709989ae3f8d15f5997f6f2768
29b39d766420b0993e30d9895fdfe1b3a08c3074
/TypeInfo.h
10c0c320d2c8ddd949a9518ff1d4949cfc832a11
[ "MIT" ]
permissive
seunggu/ECMA-C-Compiler
65beeeac9c313d3e2b99d0adefd050a1f0d00d7e
4482515f2ad46dc8029af26582193cee891406d7
refs/heads/master
2020-06-13T01:32:12.794471
2016-12-22T14:38:04
2016-12-22T14:38:04
75,468,721
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
h
// // Created by seunggu on 2016. 12. 22.. // #ifndef CPLUS_PRACTICE_TYPEINFO_H #define CPLUS_PRACTICE_TYPEINFO_H #include <iostream> #include <vector> // NONE: 아직 정해지지 않음 enum typeKind {NONE, ID, INT, DOUBLE, BOOL, STRING, LIST, FUNCTION}; using namespace std; class TypeInfo { public: typeKind type; }; // ID Type 클래스 class IDType : public TypeInfo { public: TypeInfo * valTypeInfo; IDType(TypeInfo * valTypeInfo); }; // None Type 클래스 class NoneType : public TypeInfo { public: NoneType(); }; // Int Type 클래스 class IntType : public TypeInfo { public: IntType(); }; // Double Type 클래스 class DoubleType : public TypeInfo { public: DoubleType(); }; // Bool Type 클래스 class BoolType : public TypeInfo { public: BoolType(); }; // String Type 클래스 class StringType : public TypeInfo { public: int vectorLength; StringType(int vectorLength); }; // List Type 클래스 class ListType : public TypeInfo { public: int vectorLength; TypeInfo * typeInfo; ListType(int vectorLength, TypeInfo* typeInfo); }; #endif //CPLUS_PRACTICE_TYPEINFO_H
[ "imaster0209@naver.com" ]
imaster0209@naver.com
13e4a5d2875c4121b75214368652b5ad1955df34
9813b37706567312356aa0e3a6a014709a135942
/ch10/ch10_ir_send/ch10_ir_send.ino
2138991a3e6b8a606cafa760a46b860bb4b37014
[]
no_license
bjepson/Arduino-Cookbook-3ed-INO
3476f987b55ba8bfb4eb52e299f223b28dc5cd80
12148225ee774643a879d8f51e310917cb47ed8d
refs/heads/master
2022-02-02T22:15:12.097700
2022-01-29T15:12:32
2022-01-29T15:12:32
204,302,305
30
14
null
null
null
null
UTF-8
C++
false
false
1,321
ino
/* * irSend sketch * this code needs an IR LED connected to pin 3 * and 5 switches connected to pins 6 - 10 */ #include <IRremote.h> // IR remote control library const int numberOfKeys = 5; const int firstKey = 6; // the first pin of the 5 sequential pins connected // to buttons bool buttonState[numberOfKeys]; bool lastButtonState[numberOfKeys]; long irKeyCodes[numberOfKeys] = { 0x18E758A7, //0 key 0x18E708F7, //1 key 0x18E78877, //2 key 0x18E748B7, //3 key 0x18E7C837, //4 key }; IRsend irsend; void setup() { for (int i = 0; i < numberOfKeys; i++) { buttonState[i] = true; lastButtonState[i] = true; int physicalPin=i + firstKey; pinMode(physicalPin, INPUT_PULLUP); // turn on pull-ups } Serial.begin(9600); } void loop() { for (int keyNumber=0; keyNumber<numberOfKeys; keyNumber++) { int physicalPinToRead = keyNumber + firstKey; buttonState[keyNumber] = digitalRead(physicalPinToRead); if (buttonState[keyNumber] != lastButtonState[keyNumber]) { if (buttonState[keyNumber] == LOW) { irsend.sendSony(irKeyCodes[keyNumber], 32); Serial.println("Sending"); } lastButtonState[keyNumber] = buttonState[keyNumber]; } } }
[ "bjepson@gmail.com" ]
bjepson@gmail.com
cdc1aa965275e654189ebf2c450c2d48f51c157c
9fca389094aebaefa63692e76d3dde6d7272cec2
/Render/src/debug.h
2e96a0734be8eae9dcee1a1389a14f6223e9fbf6
[]
no_license
klinchuh/Graphic-Render
3c380ecc8aa35561ef4c870df57d04cd1c3e855a
d51fff14852b021cd630ce34eefed4776404875f
refs/heads/master
2020-03-27T13:25:14.189633
2018-11-23T16:58:25
2018-11-23T16:58:25
146,365,766
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
#ifndef DEBUG_H #define DEBUG_H //full debug output log #define DEBUG_LOG #ifdef DEBUG_LOG #include <iostream> #include <fstream> extern std::ofstream __debug_s; #define ERROR_FLT(x) __debug_s << __FILE__ << ":" << __LINE__ << "\nError:" << x << std::endl; #define DEBUG_S(x) __debug_s << x << std::endl; #endif // !DEBUG_LOG #ifndef DEBUG_LOG #define ERROR_FLT(x) ; #define DEBUG_S(x) ; #endif // !DEBUG_LOG #endif // !DEBUG_H
[ "klinchuh@gmail.com" ]
klinchuh@gmail.com
4b52811992b359e6bfcd536e019631b630c478bd
64ba1fb68e1bdab4f31ab3c03a1dfe238431da56
/include/column.inl
b96b66af1f2f2a671647c172485d2e3dbe82d3d2
[ "MIT" ]
permissive
XXGF/wiredtiger
2665cc639b7347920674a3d75928be25d5e68ac1
cf4ba57d68dd25620c9c0f0762e8e52f0b2ba4a2
refs/heads/master
2021-12-12T05:47:11.994310
2016-12-13T02:14:17
2016-12-13T02:14:17
null
0
0
null
null
null
null
GB18030
C++
false
false
6,026
inl
/*************************************************** * column存储方式的检索实现 **************************************************/ /*在inshead skip list中定位到一个刚好大于recno的记录位置*/ static inline WT_INSERT* __col_insert_search_gt(WT_INSERT_HEAD* inshead, uint64_t recno) { WT_INSERT *ins, **insp; int i; /* inshead不包含recno所在的范围,不需要继续检索 */ if ((ins = WT_SKIP_LAST(inshead)) == NULL) return NULL; /*直接判断recno序号是否已经到inshead skip list的末尾,如果到了末尾,直接返回未定位到*/ if (recno >= WT_INSERT_RECNO(ins)) return NULL; /*skip list定位过程*/ ins = NULL; for (i = WT_SKIP_MAXDEPTH - 1, insp = &inshead->head[i]; i > 0;){ if (*insp != NULL && recno >= WT_INSERT_RECNO(*insp)) { ins = *insp; /* GTE: keep going at this level */ insp = &(*insp)->next[i]; } else { --i; /* LT: drop down a level */ --insp; } } if (ins == NULL) ins = WT_SKIP_FIRST(inshead); while (recno >= WT_INSERT_RECNO(ins)) ins = WT_SKIP_NEXT(ins); return ins; } /*在inshead skip list中定位到比recno小的前一条记录位置*/ static inline WT_INSERT* __col_insert_search_lt(WT_INSERT_HEAD* inshead, uint64_t recno) { WT_INSERT *ins, **insp; int i; /*inshead 不包含recno所在的范围*/ if ((ins = WT_SKIP_FIRST(inshead)) == NULL) return (NULL); if (recno <= WT_INSERT_RECNO(ins)) return (NULL); for (i = WT_SKIP_MAXDEPTH - 1, insp = &inshead->head[i]; i >= 0;){ if (*insp != NULL && recno > WT_INSERT_RECNO(*insp)) { ins = *insp; /* GT: keep going at this level */ insp = &(*insp)->next[i]; } else { --i; /* LTE: drop down a level */ --insp; } } return ins; } /*在inshead skip list中精确定位到recno所在的位置*/ static inline WT_INSERT* __col_insert_search_match(WT_INSERT_HEAD* inshead, uint64_t recno) { WT_INSERT **insp, *ret_ins; uint64_t ins_recno; int cmp, i; if ((ret_ins = WT_SKIP_LAST(inshead)) == NULL) return NULL; if (recno > WT_INSERT_RECNO(ret_ins)) return NULL; else if (recno == WT_INSERT_RECNO(ret_ins)) return ret_ins; /*skip list定位过程*/ for (i = WT_SKIP_MAXDEPTH - 1, insp = &inshead->head[i]; i >= 0;) { if (*insp == NULL) { --i; --insp; continue; } ins_recno = WT_INSERT_RECNO(*insp); cmp = (recno == ins_recno) ? 0 : (recno < ins_recno) ? -1 : 1; if (cmp == 0) /* Exact match: return */ return (*insp); else if (cmp > 0) /* Keep going at this level */ insp = &(*insp)->next[i]; else { /* Drop down a level */ --i; --insp; } } return NULL; } /*为插入的新记录定位插入skip list的位置,并把skip 的路径返回*/ static inline WT_INSERT* __col_insert_search(WT_INSERT_HEAD* inshead, WT_INSERT*** ins_stack, WT_INSERT** next_stack, uint64_t recno) { WT_INSERT **insp, *ret_ins; uint64_t ins_recno; int cmp, i; /* If there's no insert chain to search, we're done. */ if ((ret_ins = WT_SKIP_LAST(inshead)) == NULL) return NULL; /*插入到skip list的最后面,构建插入前后节点的关系stack*/ if (recno >= WT_INSERT_RECNO(ret_ins)) { for (i = 0; i < WT_SKIP_MAXDEPTH; i++) { ins_stack[i] = (i == 0) ? &ret_ins->next[0] : (inshead->tail[i] != NULL) ? &inshead->tail[i]->next[i] : &inshead->head[i]; next_stack[i] = NULL; } return ret_ins; } /*在skip list中间进行定位,并保存前后关系*/ for (i = WT_SKIP_MAXDEPTH - 1, insp = &inshead->head[i]; i >= 0;) { if ((ret_ins = *insp) == NULL) { /*本层已经到最后了,保存前后关系, 需要进行下一层的定位*/ next_stack[i] = NULL; ins_stack[i--] = insp--; continue; } ins_recno = WT_INSERT_RECNO(ret_ins); cmp = (recno == ins_recno) ? 0 : (recno < ins_recno) ? -1 : 1; if (cmp > 0) /* Keep going at this level */ insp = &ret_ins->next[i]; else if (cmp == 0) /* Exact match: return */ for (; i >= 0; i--) { next_stack[i] = ret_ins->next[i]; ins_stack[i] = &ret_ins->next[i]; } else { /* Drop down a level */ next_stack[i] = ret_ins; ins_stack[i--] = insp--; } } return ret_ins; } /*获得variable-length column store page中最大的recno值*/ static inline uint64_t __col_var_last_recno(WT_PAGE* page) { WT_COL_RLE *repeat; if (page->pg_var_nrepeats == 0) return (page->pg_var_entries == 0 ? 0 : page->pg_var_recno + (page->pg_var_entries - 1)); repeat = &page->pg_var_repeats[page->pg_var_nrepeats - 1]; return ((repeat->recno + repeat->rle) - 1 + (page->pg_var_entries - (repeat->indx + 1))); } /*获得fix-length column store page中最大的recno值*/ static inline uint64_t __col_fix_last_recno(WT_PAGE* page) { return (page->pg_fix_entries == 0 ? 0 : page->pg_fix_recno + (page->pg_fix_entries - 1)); } /* */ static inline WT_COL* __col_var_search(WT_PAGE* page, uint64_t recno, uint64_t* start_recnop) { WT_COL_RLE *repeat; uint64_t start_recno; uint32_t base, indx, limit, start_indx; /*二分法进行定位*/ for (base = 0, limit = page->pg_var_nrepeats; limit != 0; limit >>= 1){ indx = base + (limit >> 1); repeat = page->pg_var_repeats + indx; /*定位到recno对应col位置直接返回*/ if (recno >= repeat->recno && recno < repeat->recno + repeat->rle) { if (start_recnop != NULL) *start_recnop = repeat->recno; return (page->pg_var_d + repeat->indx); } if (recno < repeat->recno) continue; base = indx + 1; --limit; } /*是在第一个repeat中,返回起始位置*/ if (base == 0) { start_indx = 0; start_recno = page->pg_var_recno; } else { /*在中间未存有和recno重叠的repeat中,从repeat的recno作为startrecno*/ repeat = page->pg_var_repeats + (base - 1); start_indx = repeat->indx + 1; start_recno = repeat->recno + repeat->rle; } /*对选定的repeat做校验*/ if (recno >= start_recno + (page->pg_var_entries - start_indx)) return NULL; /*确定返回的col对象*/ return page->pg_var_d + start_indx + (uint32_t)(recno - start_recno); }
[ "rongxi.yuan@wenba100.com" ]
rongxi.yuan@wenba100.com
4d316f58027298ecd84c5d9bccd23133b1bc9102
90a5e5288f080e82382e13f2026e5bd51e3bfe11
/CG4/CG4/mainwindow.h
ffe70dd102aa7d2232fae6411bc337eb126cb3d6
[]
no_license
MikeGus/CG
53855bfb0536c3655fbd1a49a3a41731dbbe397d
02f5c4bd2b732b74547e5ecfcd739ef90502c395
refs/heads/master
2021-01-19T09:03:25.269152
2017-05-23T09:21:37
2017-05-23T09:21:37
87,717,197
0
2
null
null
null
null
UTF-8
C++
false
false
968
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QGraphicsView> #include <QGraphicsScene> #include <QColor> #include <QPixmap> #include "drawdata.h" #include "draw.h" #include "draw_circle.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); DrawData data; QGraphicsScene* scene; QPixmap* map; private slots: void on_pushButton_4_clicked(); void on_pushButton_3_clicked(); void on_pushButton_2_clicked(); void on_pushButton_6_clicked(); void on_pushButton_clicked(); void on_pushButton_5_clicked(); void on_pushButton_8_clicked(); void on_pushButton_12_clicked(); void on_pushButton_10_clicked(); void on_pushButton_7_clicked(); void on_pushButton_9_clicked(); void on_pushButton_11_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "=" ]
=
dddf346b4edb48b71540d30306abaa9fad2079ba
8ea07b9697a0014ad89ae13b90e71fe644aef9c7
/src/resource_file.hpp
48d7122a7b38f2c83e8515904dea6b2c68144447
[]
no_license
snailbaron/buzz-legacy
4d620e5159f5cb9e8025639ebd175f74a827106a
80926da842a7260c12bd98c2577e8c6859b17168
refs/heads/master
2022-09-28T06:01:15.448177
2016-01-29T14:33:24
2016-01-29T14:33:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
hpp
#ifndef _RESOURCE_FILE_HPP_ #define _RESOURCE_FILE_HPP_ #include "resource.hpp" class ResourceFile { public: virtual bool Open() = 0; virtual int GetResourceSize(const Resource &r) = 0; virtual int GetResource(const Resource &r, char *buffer) = 0; virtual ~ResourceFile() {} }; #endif
[ "murbidodrus@gmail.com" ]
murbidodrus@gmail.com
2f6b71063ca761d56914f85118480a389e74fbf0
398f682da5d2c271fdd7b5f232647da21018e40e
/macchina/sam/libraries/due_wire/due_wire.h
a018c4a6f824344ba3fb631f1ce21c32b6180fad
[]
no_license
DanielOved/M2
87bb0c233ad04ce3bf1f327c5227a1996f43b40b
ce590aa4bd792fcd9fbc9f2b97df0e39cd3ce61d
refs/heads/master
2021-09-11T15:05:53.616442
2018-04-01T20:46:26
2018-04-01T20:46:26
126,085,513
1
1
null
null
null
null
UTF-8
C++
false
false
3,302
h
/* * TwoWire.h - TWI/I2C library for Arduino Due * Copyright (c) 2011 Cristian Maglie <c.maglie@bug.st>. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TwoWire_h #define TwoWire_h // Include Atmel CMSIS driver #include <include/twi.h> #include "Stream.h" #include "variant.h" //this buffer is much larger than the normal Arduino one //It allows for a 256 byte buffer to be sent along with //extra control data. #define BUFFER_LENGTH 260 class TwoWire : public Stream { public: TwoWire(Twi *twi, void(*begin_cb)(void)); void begin(); void begin(uint8_t); void begin(uint16_t); void begin(uint32_t); void begin(uint8_t, uint32_t); void begin(uint16_t, uint32_t); void begin(uint32_t, uint32_t); void beginTransmission(uint8_t); void beginTransmission(int); uint8_t endTransmission(void); uint8_t endTransmission(uint8_t); uint8_t requestFrom(uint8_t, uint16_t); uint8_t requestFrom(uint8_t, uint16_t, uint8_t); //uint8_t requestFrom(int, int); //uint8_t requestFrom(int, int, int); virtual size_t write(uint8_t); virtual size_t write(const uint8_t *, uint16_t); virtual size_t write(const uint8_t *, int); virtual int available(void); virtual int read(void); virtual int peek(void); virtual void flush(void); void onReceive(void(*)(int)); void onRequest(void(*)(void)); inline size_t write(unsigned long n) { return write((uint8_t)n); } inline size_t write(long n) { return write((uint8_t)n); } inline size_t write(unsigned int n) { return write((uint8_t)n); } inline size_t write(int n) { return write((uint8_t)n); } using Print::write; void onService(void); private: //TWI clock freq uint32_t twiSpeed; // RX Buffer uint8_t rxBuffer[BUFFER_LENGTH]; uint16_t rxBufferIndex; uint16_t rxBufferLength; // TX Buffer uint8_t txAddress; uint16_t txBuffer[BUFFER_LENGTH]; uint16_t txBufferLength; // Service buffer uint8_t srvBuffer[BUFFER_LENGTH]; uint16_t srvBufferIndex; uint16_t srvBufferLength; // Callback user functions void (*onRequestCallback)(void); void (*onReceiveCallback)(int); // Called before initialization void (*onBeginCallback)(void); // TWI instance Twi *twi; // TWI state enum TwoWireStatus { UNINITIALIZED, MASTER_IDLE, MASTER_SEND, MASTER_RECV, SLAVE_IDLE, SLAVE_RECV, SLAVE_SEND }; TwoWireStatus status; // Timeouts ( static const uint32_t RECV_TIMEOUT = 100000; static const uint32_t XMIT_TIMEOUT = 100000; }; #if WIRE_INTERFACES_COUNT > 0 extern TwoWire Wire; #endif #if WIRE_INTERFACES_COUNT > 1 extern TwoWire Wire1; #endif #endif
[ "daniel.oved@outlook.com" ]
daniel.oved@outlook.com
73bd0d933401aa20cd306040d6d393002df7434a
a8b937985a2a245195a039192be6b4334fe8a349
/tests/minkowski_error_test.h
0594b8171d6021ee21ef22ab72f36d9eddfeaff8
[]
no_license
Quanteek/OpenNN-CMake
f7e460758f6dd62a39fedfc148726a5e9fb64f50
1cecec74764ef70f1caa10fc76272673c9eb3b40
refs/heads/master
2021-01-01T05:40:41.148486
2014-06-26T11:49:59
2014-06-26T11:49:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,329
h
/****************************************************************************************************************/ /* */ /* OpenNN: Open Neural Networks Library */ /* www.intelnics.com/opennn */ /* */ /* M I N K O W S K I E R R O R T E S T C L A S S H E A D E R */ /* */ /* Roberto Lopez */ /* Intelnics - The artificial intelligence company */ /* robertolopez@intelnics.com */ /* */ /****************************************************************************************************************/ #ifndef __MINKOWSKIERRORTEST_H__ #define __MINKOWSKIERRORTEST_H__ // Unit testing includes #include "unit_testing.h" using namespace OpenNN; class MinkowskiErrorTest : public UnitTesting { #define STRING(x) #x #define TOSTRING(x) STRING(x) #define LOG __FILE__ ":" TOSTRING(__LINE__)"\n" public: // GENERAL CONSTRUCTOR explicit MinkowskiErrorTest(void); // DESTRUCTOR virtual ~MinkowskiErrorTest(void); // METHODS // Constructor and destructor methods void test_constructor(void); void test_destructor(void); // Get methods void test_get_Minkowski_parameter(void); // Set methods void test_set_Minkowski_parameter(void); // Objective methods void test_calculate_performance(void); void test_calculate_generalization_performance(void); void test_calculate_gradient(void); void test_calculate_Hessian(void); // Serialization methods void test_to_XML(void); void test_from_XML(void); // Unit testing methods void run_test_case(void); }; #endif // OpenNN: Open Neural Networks Library. // Copyright (C) 2005-2014 Roberto Lopez // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or any later version. // // This library 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
[ "benoitbayol@dhcp-23-78.wifi-auth.ecp.fr" ]
benoitbayol@dhcp-23-78.wifi-auth.ecp.fr
533826117bee6a42a045935f6d73be20c789ea93
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/third_party/pdfium/fpdfsdk/javascript/cjs_runtime.h
2668367c1b2fb2095a19ba016deba9f956592f60
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
2,817
h
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef FPDFSDK_JAVASCRIPT_CJS_RUNTIME_H_ #define FPDFSDK_JAVASCRIPT_CJS_RUNTIME_H_ #include <map> #include <memory> #include <set> #include <utility> #include <vector> #include "core/fxcrt/include/fx_basic.h" #include "fpdfsdk/javascript/JS_EventHandler.h" #include "fpdfsdk/javascript/ijs_runtime.h" #include "fpdfsdk/jsapi/include/fxjs_v8.h" class CJS_Context; class CJS_Runtime : public IJS_Runtime { public: class Observer { public: virtual void OnDestroyed() = 0; protected: virtual ~Observer() {} }; using FieldEvent = std::pair<CFX_WideString, JS_EVENT_T>; static CJS_Runtime* FromContext(const IJS_Context* cc); explicit CJS_Runtime(CPDFDoc_Environment* pApp); ~CJS_Runtime() override; // IJS_Runtime IJS_Context* NewContext() override; void ReleaseContext(IJS_Context* pContext) override; IJS_Context* GetCurrentContext() override; void SetReaderDocument(CPDFSDK_Document* pReaderDoc) override; CPDFSDK_Document* GetReaderDocument() override; int Execute(const CFX_WideString& script, CFX_WideString* info) override; CPDFDoc_Environment* GetReaderApp() const { return m_pApp; } // Returns true if the event isn't already found in the set. bool AddEventToSet(const FieldEvent& event); void RemoveEventFromSet(const FieldEvent& event); void BeginBlock() { m_bBlocking = TRUE; } void EndBlock() { m_bBlocking = FALSE; } FX_BOOL IsBlocking() const { return m_bBlocking; } v8::Isolate* GetIsolate() const { return m_isolate; } v8::Local<v8::Context> NewJSContext(); void SetConstArray(const CFX_WideString& name, v8::Local<v8::Array> array); v8::Local<v8::Array> GetConstArray(const CFX_WideString& name); #ifdef PDF_ENABLE_XFA FX_BOOL GetValueByName(const CFX_ByteStringC& utf8Name, CFXJSE_Value* pValue) override; FX_BOOL SetValueByName(const CFX_ByteStringC& utf8Name, CFXJSE_Value* pValue) override; #endif // PDF_ENABLE_XFA void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); private: void DefineJSObjects(); std::vector<std::unique_ptr<CJS_Context>> m_ContextArray; CPDFDoc_Environment* const m_pApp; CPDFSDK_Document* m_pDocument; FX_BOOL m_bBlocking; std::set<FieldEvent> m_FieldEventSet; v8::Isolate* m_isolate; bool m_isolateManaged; v8::Global<v8::Context> m_context; std::vector<v8::Global<v8::Object>*> m_StaticObjects; std::map<CFX_WideString, v8::Global<v8::Array>> m_ConstArrays; std::set<Observer*> m_observers; }; #endif // FPDFSDK_JAVASCRIPT_CJS_RUNTIME_H_
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
87280af077ade7725d266eaa244b36db7ce6962f
675799331c7b3812ec286ec6786a3020d9bdac3d
/CPP/AtCoder/arc/027/a.cpp
2945eec9c57e162164d104d07bccc79456eb8ef6
[]
no_license
kkisic/Procon
07436574c12ebb01347b92d98c7aebb31404085a
30f394c237369a7d706fe46b53dc9d0313ce053e
refs/heads/master
2021-10-24T17:29:13.390016
2021-10-04T14:03:51
2021-10-04T14:03:51
112,325,136
1
1
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include <cmath> #include <iostream> #include <vector> #include <queue> #include <algorithm> #include <utility> #include <iomanip> #define int long long int #define rep(i, n) for(int i = 0; i < (n); ++i) using namespace std; typedef pair<int, int> P; const int INF = 1e15; const int MOD = 1e9+7; signed main(){ int h, m; cin >> h >> m; cout << 60 * (17-h) + 60 - m << endl; return 0; }
[ "amareamo.pxhxc@gmail.com" ]
amareamo.pxhxc@gmail.com
644656c30cfb791bc7d2d91b51bc2f9b77c471e6
8a6aa8798436d8b256099fa163249fcab9f86d89
/C++/Airplane/Airplane/main.cpp
2549e667f273bf169c57713842e679bc71cef66b
[]
no_license
12330072/C-learning
39f2399c4c5413ef80bd62b90a4688555606dc96
94b92bcd5bdfe99627b46eb4f6f46d379b0b67fe
refs/heads/master
2021-01-14T13:21:22.999905
2016-05-12T23:58:24
2016-05-12T23:58:24
58,739,535
0
1
null
2016-05-13T12:43:31
2016-05-13T12:43:31
null
UTF-8
C++
false
false
327
cpp
#include "airplane.h" using namespace std; int main() { int flag; string dest; cin >> flag >> dest; Airplane* p = NULL; if (flag < 2) { p = new ModelA; } else if (flag < 4) { p = new ModelB; } else { p = new ModelC; } p->fly(dest); delete p; return 0; }
[ "“mgsweet@126.com”" ]
“mgsweet@126.com”
32329eac83fb67c8916660164188dc7d5641ec76
aae79375bee5bbcaff765fc319a799f843b75bac
/srm_5xx/srm_559/HyperKnight.cpp
bf8e6edd2431ec3cc89328465ef1b98cec9d97e0
[]
no_license
firewood/topcoder
b50b6a709ea0f5d521c2c8870012940f7adc6b19
4ad02fc500bd63bc4b29750f97d4642eeab36079
refs/heads/master
2023-08-17T18:50:01.575463
2023-08-11T10:28:59
2023-08-11T10:28:59
1,628,606
21
6
null
null
null
null
UTF-8
C++
false
false
3,320
cpp
// BEGIN CUT HERE /* // SRM 559 Div1 Easy (250) 問題 チェス盤の大きさと(±a,±b)で動けるナイトが与えられる。 移動可能な先がちょうどk箇所ある升目の総数を求める。 */ // END CUT HERE #include <algorithm> #include <string> #include <vector> #include <iostream> #include <sstream> using namespace std; typedef long long LL; class HyperKnight { public: long long countCells(int a, int b, int numRows, int numColumns, int k) { LL res = 0; LL A = min(a, b); LL B = max(a, b); LL H = numRows; LL W = numColumns; LL dx[] = {A,A,-A,-A,B,B,-B,-B}; LL dy[] = {B,-B,B,-B,A,-A,A,-A}; LL bh[] = {0,A,B,H-B,H-A,H}; LL bw[] = {0,A,B,W-B,W-A,W}; int i, j, l, c; for (i = 0; i < 5; ++i) { for (j = 0; j < 5; ++j) { c = 0; for (l = 0; l < 8; ++l) { LL x = bw[j] + dx[l]; LL y = bh[i] + dy[l]; if (x >= 0 && x < W && y >= 0 && y < H) { ++c; } } if (c == k) { res += (bh[i+1] - bh[i]) * (bw[j+1] - bw[j]); } } } return res; } // BEGIN CUT HERE private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } public: void run_test(int Case) { int n = 0; // test_case_0 if ((Case == -1) || (Case == n)){ int Arg0 = 2; int Arg1 = 1; int Arg2 = 8; int Arg3 = 8; int Arg4 = 4; long long Arg5 = 20LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; // test_case_1 if ((Case == -1) || (Case == n)){ int Arg0 = 3; int Arg1 = 2; int Arg2 = 8; int Arg3 = 8; int Arg4 = 2; long long Arg5 = 16LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; // test_case_2 if ((Case == -1) || (Case == n)){ int Arg0 = 1; int Arg1 = 3; int Arg2 = 7; int Arg3 = 11; int Arg4 = 0; long long Arg5 = 0LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; // test_case_3 if ((Case == -1) || (Case == n)){ int Arg0 = 3; int Arg1 = 2; int Arg2 = 10; int Arg3 = 20; int Arg4 = 8; long long Arg5 = 56LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; // test_case_4 if ((Case == -1) || (Case == n)){ int Arg0 = 1; int Arg1 = 4; int Arg2 = 100; int Arg3 = 10; int Arg4 = 6; long long Arg5 = 564LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; // test_case_5 if ((Case == -1) || (Case == n)){ int Arg0 = 2; int Arg1 = 3; int Arg2 = 1000000000; int Arg3 = 1000000000; int Arg4 = 8; long long Arg5 = 999999988000000036LL; verify_case(n, Arg5, countCells(Arg0, Arg1, Arg2, Arg3, Arg4)); } n++; } // END CUT HERE }; // BEGIN CUT HERE int main() { HyperKnight ___test; ___test.run_test(-1); return 0; } // END CUT HERE
[ "karamaki@gmail.com" ]
karamaki@gmail.com
de3ed251c08f23fe9162cff22b3237e140dae0d9
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/type_erasure/concept_interface.hpp
cc31173e5b38ece3c831b00b4f42de3523e8a99b
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
1,876
hpp
// Boost.TypeErasure library // // Copyright 2011 Steven Watanabe // // 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) // // $Id$ #ifndef BOOST_TYPE_ERASURE_CONCEPT_INTERFACE_HPP_INCLUDED #define BOOST_TYPE_ERASURE_CONCEPT_INTERFACE_HPP_INCLUDED namespace boost { namespace type_erasure { /** * The @ref concept_interface class can be specialized to * add behavior to an @ref any. An @ref any inherits from * all the relevant specializations of @ref concept_interface. * * @ref concept_interface can be specialized for either * primitive or composite concepts. If a concept @c C1 * contains another concept @c C2, then the library guarantees * that the specialization of @ref concept_interface for * @c C2 is a base class of the specialization for @c C1. * This means that @c C1 can safely override members of @c C2. * * @ref concept_interface may only be specialized for user-defined * concepts. The library owns the specializations of its own * built in concepts. * * \tparam Concept The concept that we're specializing * @ref concept_interface for. One of its * placeholders should be @c ID. * \tparam Base The base of this class. Specializations of @ref * concept_interface must inherit publicly from this type. * \tparam ID The placeholder representing this type. * \tparam Enable A dummy parameter that can be used for SFINAE. * * The metafunctions @ref derived, @ref rebind_any, and @ref as_param * (which can be applied to @c Base) are useful for determining the * argument and return types of functions defined in @ref concept_interface. * * For dispatching the function use \call. */ template<class Concept, class Base, class ID, class Enable = void> struct concept_interface : Base {}; } } #endif
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
3c20ee73470edabd9c28793460e7ed45b1e2fd09
6aba29da570f3c20937e3a6bae97a90639dc3b88
/src/Tests/.svn/text-base/Inizializzazione_LS.cpp.svn-base
9741c08d2a938348e92d0828a8aaa475fa187538
[]
no_license
Splinter83/ndimp
0484af4a629d4372b69330686aa59d1dc344b3f3
d8a785cc2f75b785bbf327eebe4b30054cf66c26
refs/heads/master
2020-04-30T13:42:03.866798
2013-06-03T09:40:59
2013-06-03T09:40:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,522
/* * Inizializzazione_LS.cpp * * Created on: 07/set/2012 * Author: grande */ #include <unistd.h> #include <stdarg.h> #include "Inizializzazione_LS.h" #include "external_vars.h" #include "Logger.h" #include "VmeAbstractionDevice.h" #include "GlobalTypes.h" Inizializzazione_LS::Inizializzazione_LS() { CONTROL_BLOCK_POINTER_WRITE = 0x00A8; PROGRAM_POINTER_WRITE = 0x0000; RT_ICW_UNION.raw[LOW] = 0x0; RT_ICW_UNION.raw[HIGH] = 0x0; LS_RT_CONTROL_BLOCK.BASE_ADDRESS = 0x00B4; } UINT8 Inizializzazione_LS::execTest(const BoardInterfaceType& bt,int num_argomenti, ...) { Logger::getLogger()->Log(INFO_LEVEL, "***Start Inizializzazione LS***"); BASE_ADDRESS = GlobalData::instance()->GetInterfaceData(bt)->base_address; vmeDev->write(BASE_ADDRESS + CB_POINTER_OFFSET, CONTROL_BLOCK_POINTER_WRITE); vmeDev->write(BASE_ADDRESS + PROGRAM_POINTER_OFFSET, PROGRAM_POINTER_WRITE); vmeDev->write(BASE_ADDRESS + CONTROL_BLOCK_POINTER_WRITE*2 + 0xA, 0xC000); vmeDev->write(BASE_ADDRESS + CONTROL_BLOCK_POINTER_WRITE*2 + LS_RT_INTERFACE_CONTROL_WORD_OFFSET, RT_ICW_UNION.raw[LOW] + (RT_ICW_UNION.raw[HIGH] << 8)); vmeDev->write(BASE_ADDRESS + CONTROL_BLOCK_POINTER_WRITE*2 + LS_RT_BASE_ADDRESS_WORD_OFFSET, LS_RT_CONTROL_BLOCK.BASE_ADDRESS); vmeDev->write(BASE_ADDRESS + CONTROL_BLOCK_POINTER_WRITE*2 + LS_RT_COMMAND_WORD_LIST_POINTER,0x300); Logger::getLogger()->Log(INFO_LEVEL, "***End Inizializzazione LS***"); return TEST_OK; }
[ "gabriele.fabiani05@fastwebnet.it" ]
gabriele.fabiani05@fastwebnet.it
4fc1bff7dd6abcd079e1dfec7bb8fcd45a1ab3fd
3ee11c65b0be69ec0fad51b930c8714fedcdddf0
/src/ChrCopyNumber.cpp
0298bc62bbe47c666dcf43cde3a4e51f9de8d0bc
[]
no_license
johanneskoester/FREEC
0a74ee436c6bbb4be4cfd613d0543ee4574b9ef8
fea52d306d1053df11335e70af87d794c54b82ee
refs/heads/master
2021-01-19T23:40:59.715779
2017-04-20T14:01:23
2017-04-20T14:01:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
55,197
cpp
/************************************************************************* Copyright (c) 2010-2011, Valentina BOEVA. >>> SOURCE LICENSE >>> 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 (www.fsf.org); either version 2 of the License, or (at your option) any later version. 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #include "ChrCopyNumber.h" using namespace std ; ChrCopyNumber::ChrCopyNumber(void) { isMedianCalculated_ = false; isSmoothed_ = false; normalContamination_=0; } ChrCopyNumber::ChrCopyNumber(std::string const& chrName) { chromosome_ = chrName; isMedianCalculated_ = false; isSmoothed_ = false; ploidy_=NA; normalContamination_=0; } ChrCopyNumber::ChrCopyNumber(int windowSize, int chrLength, std::string const& chrName) { windowSize_ = windowSize; chrLength_ = chrLength; chromosome_ = chrName; step_=windowSize; isMedianCalculated_ = false; isSmoothed_ = false; ploidy_=NA; if (windowSize ==0) { cerr << "Error: windowSize is set to Zero\n"; exit(-1); } length_ = chrLength/windowSize+1; coordinates_ = vector<int>(length_); readCount_ = vector<float>(length_,0); for (int i = 0; i<length_; i++) { coordinates_[i] = i*windowSize; } normalContamination_=0; } ChrCopyNumber::ChrCopyNumber(int windowSize, int chrLength, std::string const& chrName, int step, std::string targetBed) { windowSize_ = windowSize; step_=step; chrLength_ = chrLength; chromosome_ = chrName; isMedianCalculated_ = false; isSmoothed_ = false; ploidy_=NA; float meanTargetRegionLength=0; if (targetBed == "") { if (windowSize ==0) { cerr << "Error: windowSize is set to Zero\n"; exit(-1); } length_ = chrLength/step+1; coordinates_ = vector<int>(length_); readCount_ = vector<float>(length_,0); if (step<windowSize) { ends_ = vector<int>(length_,0); for (int i = 0; i<length_; i++) { ends_[i] = i*step+windowSize_-1; } } for (int i = 0; i<length_; i++) { coordinates_[i] = i*step; } } else { std::string const& captureFile = targetBed ; ifstream file (captureFile.c_str()); if (file.is_open()) { cout << "..Reading "<< captureFile << "\n"; cout << "..Your file must be in .BED format, and it must be sorted\n"; std::string line; // length_ should end up equal to the number of exons matching this chromosome. length_ = 0; size_t tried = 0; while (std::getline(file,line)) { // Avoid catching a carriage return if the file uses windows-style line endings if(line.size() != 0 && line[line.size() - 1] == '\r') line.erase(line.size() - 1); size_t offset = 0; // Treat 'chr1' and '1' equivalently if(line.substr(0, 3) == "chr") offset += 3; size_t chrstart = offset; advance_to(line, offset, '\t'); if(offset == line.size()) continue; if(line.substr(chrstart, offset - chrstart) == chromosome_) { ++tried; std::string start, endstr; ++offset; size_t startoff = offset; advance_to(line, offset, '\t'); start = line.substr(startoff, offset - startoff); if(start.size() == 0) continue; coordinates_.push_back(atoi(start.c_str())); ++offset; size_t endoff = offset; advance_to(line, offset, '\t'); endstr = line.substr(endoff, offset - endoff); if(endstr.size() == 0) continue; ends_.push_back(atoi(endstr.c_str())); advance_to(line, offset, ':'); ++offset; advance_to(line, offset, ':'); ++offset; size_t geneoff = offset; advance_to(line, offset, '\t'); if(offset != geneoff) genes_names.push_back(line.substr(geneoff, offset - geneoff)); else { // Print chr:start-end if a name isn't supplied. std::ostringstream oss; oss << chromosome_ << ":" << start << "-" << endstr; oss.flush(); genes_names.push_back(oss.str()); } meanTargetRegionLength+=atoi(endstr.c_str())-atoi(start.c_str()); ++length_; } } if(int(tried) != length_) { std::cerr << "Warning: skipped " << (tried - length_) << " lines due to formatting problems\n"; } exons_Countchr_ = length_; meanTargetRegionLength/=length_; readCount_ = vector<float>(exons_Countchr_,0); cout << "Number of exons analysed in chromosome "<< chromosome_ << " : " << exons_Countchr_ << "\n"; cout << "Average exon length in chromosome "<< chromosome_ << " : " << meanTargetRegionLength << "\n"; if (meanTargetRegionLength <30) { cerr << "WARNING: check your file with targeted regions: the average length of targeted regions is unexpectedly short\n"; } }else { std::cerr << "Failed to open " << captureFile << "\n"; exit(1); } } // while (std::getline(file,line) && l < exons_Countchr) // { // if (chr_namestmp[j] == chromosome_) // { // int i = 0; // while (line[i] != '\t') // { // chr_names[l] += line[i]; // i++; // } // i++; // // while (line[i] != '\t') // { // coordinatesTmp_[l] += line[i]; // i++; // } // i++; // while (line[i] != '\t') // { // endsTmp_[l] += line[i]; // i++; // } // i++; // while (line[i] != ':') // { // i++; // } // i++; // while (line[i] != ':') // { // i++; // } // i++; // while (line[i] != '\t') // { // genes_names[l] += line[i]; // i++; // } // i++; // l++; // } // j++; // } // } // else // { // cerr << "Error: Unable to open file "+captureFile+"\n"; // exit(-1); // } // readCount_ = vector<float>(exons_Countchr,0); // coordinates_ = vector<int>(exons_Countchr); // ends_ = vector<int>(exons_Countchr,0); // copy_number_subc = vector<int>(exons_Countchr,0); // population_subc = vector<float>(exons_Countchr,0); // for (int i = 0; i<exons_Countchr; i++) // { // ends_[i] = atoi(endsTmp_[i].c_str()); //Chaque fin d'exons // } // for (int i = 0; i<exons_Countchr; i++) // { // coordinates_[i] = atoi(coordinatesTmp_[i].c_str()); //Chaque début d'exons // } // cout << "Number of exons analysed in chromosome "<< chromosome_ << " : " << exons_Countchr << "\n"; // } normalContamination_=0; } void ChrCopyNumber::mappedPlusOneAtI(int i, int step, int l) { if (l == -1) { int pos = i/step; if ((int)readCount_.size()<=pos) { //should not normally happen unless we are at the very end of file cout << "Reaching end of file for chr "<<chromosome_ <<", position " << i <<"\n"; //readCount_.resize(pos+1); //length_ = pos+1; } else { readCount_[pos]++; while (step*(pos-1)+windowSize_>i && pos>=1) { readCount_[--pos]++; } } } else { int pos = l; if ((int)readCount_.size()<=pos) { //should not normally happen unless we are at the very end of file cout << "Reaching end of file for chr "<<chromosome_ <<", position " << i <<"\n"; //readCount_.resize(pos+1); //length_ = pos+1; } else { readCount_[pos]++; //while (step*(pos-1)+windowSize_>i && pos>=1) //{ //readCount_[--pos]++; //} } } } void ChrCopyNumber::setValueAt(int i, float val) { readCount_[i] = val; } void ChrCopyNumber::setCN_subc(int i, int CN_subc) { //cerr << copy_number_subc_[i]; //WHAT IS THIS OUTPUT, CARINO? copy_number_subc_[i] = CN_subc; //THIS VECTOR IS EMPTY! } int ChrCopyNumber::getCN_subc(int i) { return copy_number_subc_[i]; } void ChrCopyNumber::setPopulation_subc(int i, float pop_subc) { population_subc_[i] = pop_subc; } float ChrCopyNumber::getPopulation_subc(int i) { return population_subc_[i] ; } std::string ChrCopyNumber::getGeneNameAtBin(int i) { if (i<int(genes_names.size())) return genes_names[i]; return ""; } float ChrCopyNumber::getValueAt(int i) { return readCount_[i]; } int ChrCopyNumber::getCoordinateAtBin(int i) { return coordinates_[i]; } int ChrCopyNumber::getEndAtBin(int i) { if ((int)ends_.size()>i) return ends_[i]; else return coordinates_[i]+windowSize_-1; } int ChrCopyNumber::getExons_Countchr() { return exons_Countchr_; } void ChrCopyNumber::setNotNprofileAt(int i, float value) { if (i<int(notNprofile_.size())) notNprofile_[i] = value; else cout <<"out of boundaries!!\n"; } void ChrCopyNumber::setMappabilityProfileAt(int i, float value) { mappabilityProfile_[i] = value; } void ChrCopyNumber::setBAFat(int i, float value) { BAF_[i] = value; } void ChrCopyNumber::addToReadCount(float f) { readCount_.push_back(f); } void ChrCopyNumber::addToCoordinates(int i) { coordinates_.push_back(i); } void ChrCopyNumber::addToEnds(int i) { ends_.push_back(i); } void ChrCopyNumber::setWindowSize(int windowSize) { windowSize_ = windowSize; } void ChrCopyNumber::setPloidy(int ploidy) { ploidy_=ploidy; } void ChrCopyNumber::setNormalContamination(float normalContamination) { normalContamination_=normalContamination; } void ChrCopyNumber::setStep(int step) { step_ = step; } void ChrCopyNumber::setVectorLength(int length){ length_ = length; } void ChrCopyNumber::setCN_subcLength(int len) { copy_number_subc_.clear(); copy_number_subc_ = vector<int>(len,0); } void ChrCopyNumber::setpop_subcLength(int len) { population_subc_.clear(); population_subc_ = vector<float>(len,0); } void ChrCopyNumber::setChrLength(int chrLength) { chrLength_ = chrLength; } std::vector <float> ChrCopyNumber::getValues() { return readCount_; } void ChrCopyNumber::removeLowReadCountWindows(ChrCopyNumber control,const int RCThresh) { if (length_!=control.getLength()) { cerr << "Warning: control length is not equal to the sample length for chromosome " << chromosome_ << "\n"; return; } for (int i = 0; i<length_; i++) { if (control.getValueAt(i) < RCThresh){ readCount_[i]=NA; control.setValueAt(i,0); } } } void ChrCopyNumber::removeLowReadCountWindows(const int RCThresh) { for (int i = 0; i<length_; i++) { if (readCount_[i] < RCThresh){ readCount_[i]=0; } } } void ChrCopyNumber::fillInRatio(bool islog) { if ((int)ratio_.size()!=length_) ratio_.resize(length_); for (int i = 0; i<length_; i++) { if (readCount_[i]>=0 && !(mappabilityProfile_.size() > 0 && mappabilityProfile_[i] <= minMappabilityPerWindow)) { if (islog) { ratio_[i] = log(readCount_[i]+1)/log(2.0); }else { ratio_[i] = readCount_[i]; } } else { ratio_[i] = NA; } } } void ChrCopyNumber::calculateRatioLog(ChrCopyNumber control, const double * a, const int degree){ if ((int)ratio_.size()!=length_) ratio_.resize(length_); for (int i = 0; i<length_; i++) { if ((control.getLength()>i)&&(control.getValueAt(i) != 0)){ if (mappabilityProfile_.size() == 0 || mappabilityProfile_[i] > minMappabilityPerWindow) { ratio_[i] = readCount_[i]/polynomial(control.getValueAt(i),a,1,degree); if (ratio_[i]<0) ratio_[i] = NA; } else ratio_[i] = NA; } else if (readCount_[i]==0) //ratio_[i] = 1; ratio_[i] = NA; else ratio_[i] = NA; //cout << readCount_[i] << "\t" << control.getValueAt(i) << "\t" << ratio_[i] << "\n"; } } void ChrCopyNumber::calculateRatio(ChrCopyNumber control, const double * a, const int degree){ if ((int)ratio_.size()!=length_) ratio_.resize(length_); for (int i = 0; i<length_; i++) { if ((control.getLength()>i)&&(control.getValueAt(i) != 0)){ if (mappabilityProfile_.size() == 0 || mappabilityProfile_[i] > minMappabilityPerWindow) { ratio_[i] = readCount_[i]/polynomial(control.getValueAt(i),a,1,degree); if (ratio_[i]<0) ratio_[i] = NA; } else ratio_[i] = NA; } else if (readCount_[i]==0) //ratio_[i] = 1; ratio_[i] = NA; else ratio_[i] = NA; //cout << readCount_[i] << "\t" << control.getValueAt(i) << "\t" << ratio_[i] << "\n"; } } void ChrCopyNumber::recalculateRatio(ChrCopyNumber control){ for (int i = 0; i<length_; i++) { float controlRatio = control.getRatioAtBin(i); if ((control.getLength()>i)&&(controlRatio > 0)){ if (mappabilityProfile_.size() == 0 || mappabilityProfile_[i] > minMappabilityPerWindow) { ratio_[i] = ratio_[i]/controlRatio; if (ratio_[i]<0) ratio_[i] = NA; } else ratio_[i] = NA; } else ratio_[i] = NA; //cout << readCount_[i] << "\t" << control.getValueAt(i) << "\t" << ratio_[i] << "\n"; } } void ChrCopyNumber::calculateRatio(ChrCopyNumber control, double a0, double a1) { if ((int)ratio_.size()!=length_) ratio_.resize(length_); for (int i = 0; i<length_; i++) { if ((control.getLength()>i)&&(control.getValueAt(i) != 0) && (readCount_[i] > 0) && (control.getValueAt(i) > 0)) if (mappabilityProfile_.size() == 0 || mappabilityProfile_[i] > minMappabilityPerWindow) ratio_[i] = float(readCount_[i]/(control.getValueAt(i)*a0+a1)); else ratio_[i] = NA; else if ((readCount_[i] < 0) || (control.getValueAt(i) < 0)) { ratio_[i] = NA; } else if (readCount_[i]==0) //ratio_[i] = 1; ratio_[i] = NA; else ratio_[i] = NA; //cout << readCount_[i] << "\t" << control.getValueAt(i) << "\t" << ratio_[i] << "\n"; } } void ChrCopyNumber::calculateRatio(ChrCopyNumber control, float normalizationConst) { ratio_ = vector<float>(length_,0); for (int i = 0; i<length_; i++) { if ((control.getLength()>i)&&(control.getValueAt(i) != 0)) if (mappabilityProfile_.size() == 0 || mappabilityProfile_[i] > minMappabilityPerWindow) ratio_[i] = readCount_[i]/control.getValueAt(i)/normalizationConst; else ratio_[i] = NA; else if (readCount_[i]==0) //ratio_[i] = 1; ratio_[i] = NA; else ratio_[i] = NA; //cout << readCount_[i] << "\t" << control.getValueAt(i) << "\t" << ratio_[i] << "\n"; } } void ChrCopyNumber::setAllNormal() { if ((int)ratio_.size()!=length_) ratio_.resize(length_); for (int i = 0; i<length_; i++) { if (readCount_[i] != NA && i<int(notNprofile_.size()) &&notNprofile_[i]>0) { ratio_[i] = 1; } else { ratio_[i] = NA; } } } void ChrCopyNumber::recalculateRatio(double *a, int degree) { float x; for (int i = 0; i<length_; i++) { if (ratio_[i] != NA) { x = GCprofile_[i]; //use a threshold, but correct using notN profile if (mappabilityProfile_.size()>0) { if ((x>0)&&(mappabilityProfile_[i]>minMappabilityPerWindow)) //if ((x>0)&&(notNprofile_[i]!=0)) ratio_[i] = ratio_[i]/polynomial(x,a,1,degree); else ratio_[i] = NA; } else { if ((x>0)&&(notNprofile_[i]>minMappabilityPerWindow)) //if ((x>0)&&(notNprofile_[i]!=0)) ratio_[i] = ratio_[i]/polynomial(x,a,1,degree); else ratio_[i] = NA; } } if ((ratio_[i] != NA)&&(ratio_[i] < 0)) ratio_[i] = 0; //this happens if polynomial(x,a,b,c,d) < 0 } } void ChrCopyNumber::calculateRatio(double *a, int degree) { if ((int)ratio_.size()!=length_) ratio_.resize(length_); float x; for (int i = 0; i<length_; i++) { if (readCount_[i] != NA) { x = GCprofile_[i]; // if uniqueMatch, do correction to mappability if (uniqueMatch) { //use mappabilityProfile_ and correct if ((x>0)&&(mappabilityProfile_[i]>minMappabilityPerWindow)) //if ((x>0)&&(notNprofile_[i]!=0)) ratio_[i] = readCount_[i]/polynomial(x,a,1,degree)/mappabilityProfile_[i]; else ratio_[i] = NA; } else { //use a threshold, but correct using notN profile if (mappabilityProfile_.size()>0) { if ((x>0)&&(mappabilityProfile_[i]>minMappabilityPerWindow)) //if ((x>0)&&(notNprofile_[i]!=0)) ratio_[i] = readCount_[i]/polynomial(x,a,1,degree)/notNprofile_[i]; else ratio_[i] = NA; } else { if ((x>0)&&(notNprofile_[i]>minMappabilityPerWindow)) //if ((x>0)&&(notNprofile_[i]!=0)) ratio_[i] = readCount_[i]/polynomial(x,a,1,degree)/notNprofile_[i]; else ratio_[i] = NA; } } } else { ratio_[i] = NA; } if ((ratio_[i] != NA)&&(ratio_[i] < 0)) ratio_[i] = 0; //this happens if polynomial(x,a,b,c,d) < 0 } } //void ChrCopyNumber::calculateRatio(double a,double b, double c,double d) { // if ((int)ratio_.size()!=length_) // ratio_.resize(length_); // float x; // for (int i = 0; i<length_; i++) { // if (readCount_[i] != NA) { // x = GCprofile_[i]; // if ((x>0)&&(notNprofile_[i]!=0)) // ratio_[i] = readCount_[i]/polynomial(x,a,b,c,d)/notNprofile_[i]; // else // ratio_[i] = NA; // } else { // ratio_[i] = NA; // } // if ((ratio_[i] != NA)&&(ratio_[i] < 0)) // ratio_[i] = 0; //this happens if polynomial(x,a,b,c,d) < 0 // } //} void ChrCopyNumber::recalculateRatio (float constant) { for (int i = 0; i<length_; i++) if (ratio_[i] != NA) ratio_[i] /= constant; } void ChrCopyNumber::recalculateLogRatio (float constant) { for (int i = 0; i<length_; i++) if (ratio_[i] != NA) ratio_[i] -= constant; } void ChrCopyNumber::recalculateRatioWithContam (float contamination, float normGenytype, bool isLogged) { //normGenytype==1 if AB, normGenytype==0.5 if A if (!isLogged) { for (int i = 0; i<length_; i++) if (ratio_[i] != NA) { //ratio_[i] = (ratio_[i]-contamination*normGenytype)/(1-contamination); //correct only for ploidy 2 ratio_[i] = (ratio_[i]*(1-contamination+2*contamination/ploidy_) -contamination*normGenytype/ploidy_*2)/(1-contamination); if (ratio_[i]<0) ratio_[i] = 0; } } else { for (int i = 0; i<length_; i++) if (ratio_[i] != NA) { float realCopy = pow(2,ratio_[i]); ratio_[i] = (realCopy*(1-contamination+2*contamination/ploidy_) -contamination*normGenytype/ploidy_*2)/(1-contamination); if (ratio_[i]<0) ratio_[i] = NA; else { ratio_[i]=log2(ratio_[i]); } } } } int ChrCopyNumber::calculateBreakpoints(double threshold, int normalChrLength, int breakPointType) { int chrLen = calculateBreakpoints_general(threshold,length_,ratio_,bpfinal_,normalChrLength,breakPointType, getChromosome()); return chrLen; } int ChrCopyNumber::calculateBAFBreakpoints(double threshold, int normalChrLength, int breakPointType) { // bpfinal_ should already contain copy number breakpoints std::vector <int> bpBAF; //find breakpoints in the BAF profile int chrLen = calculateBreakpoints_general(threshold,length_,BAF_,bpBAF,normalChrLength,breakPointType, getChromosome()); //add detected breakpoints to the breakpoints detected using copy number profiles bpfinal_ = merge_no_dups(bpfinal_, bpBAF); sort (bpfinal_.begin(), bpfinal_.end()); return chrLen; } int ChrCopyNumber::getCoveredPart(int breakPointStart, int breakPointEnd) { //for exome-seq: get length of the genome covered by the targeted region (from breakPointStart to breakPointEnd) int lengthCovered = 0; for (int i = breakPointStart; i<=breakPointEnd; i++) { lengthCovered+=ends_[i]-coordinates_[i]+1; } return lengthCovered; } void ChrCopyNumber::calculateCopyNumberMedian(int ploidy, int minCNAlength, bool noisyData, bool CompleteGenomicsData, bool isLogged){ //create median profiles using 'bpfinal_' and store them in medianProfile_, info about medians themselves is stored in medianValues_ and about SD in sd_, lengths of fragments in bpLengths_ if (ploidy!=ploidy_) { cerr << "..Warning: in calculateCopyNumberMedian() class's ploidy is different from "<<ploidy<<"\n"; ploidy_=ploidy; } int breakPointStart = 0; int breakPointEnd; float median; bpfinal_.push_back(length_-1); //add last point vector <int> seg_ends; vector <int> seg_starts; if (int(medianProfile_.size())!=length_) { medianProfile_ = vector <float> (length_,NA); } //for BAF: bool isBAFpresent = false; //float medianBAF; float estimatedBAF; float fittedBAF; float uncertainty; string medianBAFSym; if (BAF_.size()>0) { isBAFpresent = true; //medianBAFProfile_ = vector <float> (length_,NA); estimatedBAFProfile_ = vector <float> (length_,NA); fittedBAFProfile_ = vector <float> (length_,NA); medianBAFSymbol_ = vector <std::string> (length_,"-"); estimatedBAFuncertainty_ = vector <float> (length_,NA); cout << "..Control: BAF profile is present\n"; } //clear existing values: sd_.clear(); medianValues_.clear(); fragmentNotNA_lengths_.clear(); fragment_lengths_.clear(); BAFsymbPerFrag_.clear(); estBAFuncertaintyPerFrag_.clear(); for (int i = 0; i < (int)bpfinal_.size();i++) { breakPointEnd = bpfinal_[i]; //int ndatapoints = breakPointEnd-breakPointStart+1; vector<float> data; //vector<float> dataBAF; int notNA = 0; string BAFValuesInTheSegment = ""; //here we merge all SNP Values of this segment for (int j = breakPointStart; j <= breakPointEnd; j++) { if (ratio_[j] != NA) { data.push_back(ratio_[j]); notNA++; if (isBAFpresent && BAF_[j]!=NA && BAFvalues_[j] != ""){ //dataBAF.push_back(BAF_[j]); if (BAFValuesInTheSegment != ""){ if (BAFvalues_[j].compare(BAFvalues_[j-1])!=0) { string suffix = findSmallestSuffix(BAFvalues_[j-1],BAFvalues_[j]); if (suffix != "") BAFValuesInTheSegment += ";"+suffix; //BAFValuesInTheSegment += ";"+BAFvalues_[j]; } } else BAFValuesInTheSegment = BAFvalues_[j]; } } } int totalCount = breakPointEnd-breakPointStart+1; bool ifHomoz = false; float locMedian=NA; if (int(data.size())>=minCNAlength && data.size()>0) { locMedian = get_median(data); //including the last point if (isLogged) locMedian=pow(2, locMedian); } if (isBAFpresent && notNA > 100 && locMedian < 1 && noisyData ) { vector<string>heteroValuesPerWindowStrings = split(BAFValuesInTheSegment, ';'); int numberofBAFpoints =heteroValuesPerWindowStrings.size(); heteroValuesPerWindowStrings.clear(); double threshold; if (step_ != 0) { threshold = 0.0001*step_*notNA; } else { threshold = 0.00001*getCoveredPart(breakPointStart, breakPointEnd); } if (numberofBAFpoints < threshold) ifHomoz = true; cout <<"chr"<<chromosome_ <<":"<<breakPointStart<<"-"<<breakPointEnd<<" totalCount=" << totalCount << " notNA="<<notNA<<" numberofBAFpoints="<<numberofBAFpoints<<" ratio="<< 1.*numberofBAFpoints/threshold<<" hom:"<<ifHomoz<<"\n"; } //check is totalCount is notNA is greater than minCNAlength if (totalCount<minCNAlength && i<(int)bpfinal_.size()-1) { //merge this fragment with next one //do nothing, do to the next cycle, keep the same position of "breakPointStart" } else { //fragment_lengths_.push_back(totalCount); //if (notNA <= (totalCount+0.5)/2) { // no more than 1/2 of NA windows if (notNA==0 || notNA<sqrt(float(totalCount))){ //instead of (notNA == 1 && totalCount>2) meaning that only one point is not sufficient if there are more than 2 windows to set the median //median = get_median(data); median = NA; if (isBAFpresent) { //medianBAF = NA; estimatedBAF = NA; fittedBAF=NA; medianBAFSym = "-"; uncertainty = NA; } } else { median = get_median(data); //including the last point if (isLogged) median=pow(2, median); if (isBAFpresent) { // if (dataBAF.size()>0) // medianBAF = get_median(dataBAF); // else // medianBAF = NA; //medianBAF = NA; getBAFinfo(BAFValuesInTheSegment,median*ploidy,estimatedBAF, fittedBAF, medianBAFSym,uncertainty, normalContamination_,ploidy_,noisyData,ifHomoz, CompleteGenomicsData); } } //check the previous median: may be one can merge the two regions? //if(totalCount==1 && median == NA && breakPointStart != 0){ // median = previousMedian; // //join two segments // medianValues_.pop_back(); // notNA += fragmentNotNA_lengths_.back(); // fragmentNotNA_lengths_.pop_back(); // //don't change the SDev // breakPointStart = seg_starts.back(); // seg_ends.pop_back(); //} //else if (round_by_ploidy(median,ploidy)==round_by_ploidy(previousMedian,ploidy)) { // //join two segments // medianValues_.pop_back(); // median = (median+previousMedian)/2; //approximatelly true... // notNA += fragmentNotNA_lengths_.back(); // fragmentNotNA_lengths_.pop_back(); // float sdLocal = (sd_.back()+sd(data,median))/2; //approximatelly true... // sd_.pop_back(); // sd_.push_back(sdLocal); // breakPointStart = seg_starts.back(); // seg_ends.pop_back(); //} else { sd_.push_back(sd(data,median)); seg_starts.push_back(breakPointStart); //} seg_ends.push_back(breakPointEnd); for (int j = breakPointStart; j<= breakPointEnd; j++) { medianProfile_[j] = median; if (isBAFpresent) { //medianBAFProfile_[j] = medianBAF; medianBAFSymbol_[j] = medianBAFSym; estimatedBAFProfile_[j]=estimatedBAF; fittedBAFProfile_[j]=fittedBAF; estimatedBAFuncertainty_[j]=uncertainty; } } medianValues_.push_back(median); fragmentNotNA_lengths_.push_back(notNA); if (isBAFpresent) { estBAFuncertaintyPerFrag_.push_back(uncertainty); BAFsymbPerFrag_.push_back(medianBAFSym); // cout << "..Control: adding "<<medianBAFSym<< " to a fragment with median*ploidy="<<median*ploidy<< "\n"; } breakPointStart = breakPointEnd+1; data.clear(); if (isBAFpresent) { // dataBAF.clear(); } //previousMedian = median; } } bpfinal_.clear(); bpfinal_ = seg_ends; seg_ends.clear(); seg_starts.clear(); //recalc fragment_lengths_ fragment_lengths_.push_back(bpfinal_[0]+1); for (int i = 1; i < int(bpfinal_.size()); i++) fragment_lengths_.push_back(bpfinal_[i]-bpfinal_[i-1]); bpfinal_.pop_back(); //delete last point which is (length_-1) isMedianCalculated_ = true; } //old version, only with ploidy //void ChrCopyNumber::calculateCopyNumberMedian(int ploidy){ //create median profiles using 'bpfinal_' and store them in medianProfile_, info about medians themselves is stored in medianValues_ and about SD in sd_, lengths of fragments in bpLengths_ // int breakPointStart = 0; // int breakPointEnd; // float median; // float previousMedian = -22; //something strange // // bpfinal_.push_back(length_-1); //add last point // // vector <int> seg_ends; // vector <int> seg_starts; // // medianProfile_ = vector <float> (length_); // for (int i = 0; i < (int)bpfinal_.size();i++) { // breakPointEnd = bpfinal_[i]; // //int ndatapoints = breakPointEnd-breakPointStart+1; // vector<float> data; // int notNA = 0; // for (int j = breakPointStart; j <= breakPointEnd; j++) // if (ratio_[j] != NA) { // data.push_back(ratio_[j]); // notNA++; // } // int totalCount = breakPointEnd-breakPointStart+1; // //fragment_lengths_.push_back(totalCount); // if (notNA <= (totalCount+0.5)/3) { // no more than 2/3 of NA windows // median = NA; // } else { // median = get_median(data); //including the last point!!!! Ask Kevin or check if it is correct!! // } // // //check the previous median: may be one can merge the two regions? // // if(totalCount==1 && median == NA && breakPointStart != 0){ // median = previousMedian; // //join two segments // medianValues_.pop_back(); // notNA += fragmentNotNA_lengths_.back(); // fragmentNotNA_lengths_.pop_back(); // //don't change the SDev // breakPointStart = seg_starts.back(); // seg_ends.pop_back(); // } // else if (round_by_ploidy(median,ploidy)==round_by_ploidy(previousMedian,ploidy)) { // // //join two segments // medianValues_.pop_back(); // median = (median+previousMedian)/2; //approximatelly true... // notNA += fragmentNotNA_lengths_.back(); // fragmentNotNA_lengths_.pop_back(); // float sdLocal = (sd_.back()+sd(data,median))/2; //approximatelly true... // sd_.pop_back(); // sd_.push_back(sdLocal); // breakPointStart = seg_starts.back(); // seg_ends.pop_back(); // } else { // sd_.push_back(sd(data,median)); // seg_starts.push_back(breakPointStart); // } // // seg_ends.push_back(breakPointEnd); // for (int j = breakPointStart; j<= breakPointEnd; j++) // medianProfile_[j] = median; // medianValues_.push_back(median); // fragmentNotNA_lengths_.push_back(notNA); // // breakPointStart = breakPointEnd+1; // data.clear(); // previousMedian = median; // } // // bpfinal_.clear(); // bpfinal_ = seg_ends; // seg_starts.clear(); ////recalc fragment_lengths_ // //fragment_lengths_.clear(); // fragment_lengths_.push_back(bpfinal_[0]+1); // for (int i = 1; i < int(bpfinal_.size()); i++) // fragment_lengths_.push_back(bpfinal_[i]-bpfinal_[i-1]); // // bpfinal_.pop_back(); //delete last point which is (length_-1) // isMedianCalculated_ = true; //} //old version void ChrCopyNumber::calculateCopyNumberMedian(){ //create median profiles using 'bpfinal_' and store them in medianProfile_, info about medians themselves is stored in medianValues_ and about SD in sd_, lengths of fragments in bpLengths_ int breakPointStart = 0; int breakPointEnd; float median; bpfinal_.push_back(length_-1); //add last point medianProfile_ = vector <float> (length_); for (int i = 0; i < (int)bpfinal_.size();i++) { breakPointEnd = bpfinal_[i]; //int ndatapoints = breakPointEnd-breakPointStart+1; vector<float> data; int notNA = 0; for (int j = breakPointStart; j <= breakPointEnd; j++) if (ratio_[j] != NA) { data.push_back(ratio_[j]); notNA++; } int totalCount = breakPointEnd-breakPointStart+1; fragment_lengths_.push_back(totalCount); if (notNA <= (totalCount+0.5)/2) { median = NA; } else { median = get_median(data); //including the last point!!!! Ask Kevin or check if it is correct!! } medianValues_.push_back(median); fragmentNotNA_lengths_.push_back(notNA); sd_.push_back(sd(data,median)); for (int j = breakPointStart; j<= breakPointEnd; j++) medianProfile_[j] = median; breakPointStart = breakPointEnd+1; data.clear(); } bpfinal_.pop_back(); //delete last point which is (length_-1) isMedianCalculated_ = true; } float ChrCopyNumber::getMedianProfileAtI (int i) { return medianProfile_[i]; } float ChrCopyNumber::getMedianValuesAt (int i) { return medianValues_[i]; } float ChrCopyNumber::getCGprofileAt(int i) { return GCprofile_[i]; } float ChrCopyNumber::getNotNprofileAt(int i) { return notNprofile_[i]; } float ChrCopyNumber::getMappabilityProfileAt(int i) { return mappabilityProfile_[i]; } std::vector <float> ChrCopyNumber::getRatio() { return ratio_; } bool ChrCopyNumber::isMedianCalculated() { return isMedianCalculated_; } bool ChrCopyNumber::isSmoothed(){ return isSmoothed_; } void ChrCopyNumber::setIsSmoothed(bool value) { isSmoothed_ = value; smoothedProfile_.clear(); } //void ChrCopyNumber::printLog2Ratio(std::ofstream const& file) { // /*for (int i = 0; i<length_; i++) { // file << ratio_[i] << "\n"; // }*/ //} int ChrCopyNumber::getLength() { return length_; } int ChrCopyNumber::getChrLength() { return chrLength_; } int ChrCopyNumber::getMappabilityLength() { return mappabilityProfile_.size(); } std::string ChrCopyNumber::getChromosome() { return chromosome_; } float ChrCopyNumber::getRatioAtBin(int i) { return ratio_[i]; } float ChrCopyNumber::getEstimatedBAFuncertaintyAtBin(int i) { return estBAFuncertaintyPerFrag_[i]; } std::string ChrCopyNumber::getBAFsymbPerFrg (int i) { return BAFsymbPerFrag_[i]; } std::vector <float> ChrCopyNumber::getMedianValues () { return medianValues_; } std::vector <float> ChrCopyNumber::getSDs () { return sd_; } std::vector <int> ChrCopyNumber::getFragmentLengths_notNA () { return fragmentNotNA_lengths_; } std::vector <int> ChrCopyNumber::getFragmentLengths () { return fragment_lengths_; } int ChrCopyNumber::getFragmentLengthsAt (int i) { return fragment_lengths_[i]; } int ChrCopyNumber::getFragmentLengths_notNA_At(int i) { return fragmentNotNA_lengths_[i]; } std::vector <int> ChrCopyNumber::getBreakPoints() { return bpfinal_; } int ChrCopyNumber::getNumberOfFragments() { return bpfinal_.size()+1; } int ChrCopyNumber::nextNoNAIndex(int i1, int ploidy, int min_fragment) { for (int i = i1+1; i<(int)medianValues_.size(); i++) //if (round_by_ploidy(medianValues_[i], ploidy)>=0) // !!! >= and not > 0. if (getLevelAt(i, ploidy)>=0) // !!! >= and not > 0. if (fragment_lengths_[i] > min_fragment) return i; return NA; } float ChrCopyNumber::nextNoNAMedian(int i1, int ploidy) { for (int i = i1+1; i<(int)medianValues_.size(); i++) if (getLevelAt(i, ploidy)>0) return medianValues_[i]; return NA; } int ChrCopyNumber::nextNoNALength(int i1, int ploidy) { for (int i = i1+1; i<(int)medianValues_.size(); i++) if (getLevelAt(i, ploidy)>0) return fragment_lengths_[i]; return 0; } int ChrCopyNumber::getNumberOfGoodFragments() { int count = 0; for (int i = 0; i < (int)fragmentNotNA_lengths_.size(); i++) if (fragmentNotNA_lengths_[i] != 0) count++; return count; } double ChrCopyNumber::getXiSum(int ploidy, float minSD) { double sum = 0; const double PI = 3.141592; for (int i = 0; i <= (int)bpfinal_.size();i++) { double theta_i = getLevelAt(i,ploidy); //bpLengths_[i]; //sd_[i]; double d = medianValues_[i]-theta_i; if (!(d == 0 && fragmentNotNA_lengths_[i] == 0)) { double sqrtVar = sqrt(float(PI/2./fragmentNotNA_lengths_[i]))*max(minSD,sd_[i]); double term = pow(d/sqrtVar,2); sum += term; } } return sum; } double ChrCopyNumber::calculateXiSum(int ploidy, map <float,float> &sds, map <float,float> &meds) { double sum = 0; const double PI = 3.141592; for (int i = 0; i <= (int)bpfinal_.size();i++) { float level = getLevelAt(i,ploidy); if (level != NA) { double theta_i = meds.find(level)->second; //bpLengths_[i]; //sd_[i]; double d = medianValues_[i]-theta_i; if (fragmentNotNA_lengths_[i] != 0) { double sqrtVar = sqrt(float(PI/2./fragmentNotNA_lengths_[i]))*max(sds.find(level)->second,sd_[i]); double term = pow(d/sqrtVar,2); sum += term; } } } /*ofstream myfile; myfile.open ("example.txt"); myfile <<"ratio\tmedianValues\n"; for (int i = 0; i < (int)ratio_.size();i++) { myfile << ratio_[i] << "\t" <<medianProfile_[i] <<"\n"; } myfile.close();*/ return sum; } double ChrCopyNumber::calculateXiSum(int ploidy, map <float,float> &sds) { double sum = 0; const double PI = 3.141592; for (int i = 0; i <= (int)bpfinal_.size();i++) { float level = getLevelAt(i,ploidy); if (level != NA) { //bpLengths_[i]; //sd_[i]; double d = medianValues_[i]-level; if ((fragmentNotNA_lengths_[i] != 0)&&(sd_[i] != 0)) { float localSV = sd_[i]; //float globalSV = sds.find(level)->second; //double sqrtVar = sqrt(float(PI/2./fragmentNotNA_lengths_[i]))*max(sds.find(level)->second,sd_[i]); double sqrtVar = sqrt(float(PI/2./fragmentNotNA_lengths_[i]))*localSV; double term = pow(d/sqrtVar,2); sum += term; } } } return sum; } void ChrCopyNumber::deleteFlanks(int telo_centromeric_flanks) { int maxRegionLengthToDelete = int(telo_centromeric_flanks/windowSize_); for (int i = 0; i < (int)medianValues_.size(); i++) { if (medianValues_[i]==NA) { if ((i-1>=0)&&(fragmentNotNA_lengths_[i-1]<=maxRegionLengthToDelete)) { deleteFragment(i-1); for (int j=i-2; j>0; j--) { if (fragmentNotNA_lengths_[j]<=maxRegionLengthToDelete) deleteFragment(j); else break; } } if ((i+1<(int)medianValues_.size())&&(fragmentNotNA_lengths_[i+1]<=maxRegionLengthToDelete)) deleteFragment(i+1); } } //detele telomeric flanks: if (medianValues_[0]!=NA) if (fragmentNotNA_lengths_[0]<=maxRegionLengthToDelete) deleteFragment(0); if ((medianValues_[medianValues_.size()-1]!=NA)&&(fragmentNotNA_lengths_[medianValues_.size()-1]<=maxRegionLengthToDelete)) deleteFragment(medianValues_.size()-1); } int ChrCopyNumber::removeLargeExons(float threshold) { int howManyRemoved = 0; for (int i =0; i< length_; i++) { if (ends_[i]-coordinates_[i]>threshold) { howManyRemoved++; readCount_[i]=NA; } } return howManyRemoved; } void ChrCopyNumber::recalcFlanks(int telo_centromeric_flanks, int minNumberOfWindows) { int maxRegionLengthToDelete = int(telo_centromeric_flanks/step_); for (int i = 0; i < (int)medianValues_.size(); i++) { if (medianValues_[i]==NA && fragment_lengths_[i]>=minNumberOfWindows) { int left = i; int right = i; if ((i-1>=0)&&(fragmentNotNA_lengths_[i-1]<=maxRegionLengthToDelete && medianValues_[i-1]!=NA )) { left = i-1; for (int j=i-2; j>0; j--) { if (fragmentNotNA_lengths_[j]<=maxRegionLengthToDelete && medianValues_[j]!=NA ) left = j; else break; } } if ((i+1<(int)medianValues_.size())&&(fragmentNotNA_lengths_[i+1]<=maxRegionLengthToDelete)&& medianValues_[i+1]!=NA) { right = i+1; for (int j=i+2; j<(int)fragment_lengths_.size()-1; j++) { if (fragmentNotNA_lengths_[j]<=maxRegionLengthToDelete && medianValues_[j]!=NA ) right = j; else break; } } if (left < i-1) recalcFlanksForIndeces (left,i-1); if (i+1 < right) recalcFlanksForIndeces (i+1, right); } } //recalculate telomeric flanks: if (medianValues_[0]!=NA) if (fragmentNotNA_lengths_[0]<=maxRegionLengthToDelete) { int i = 0; int right = 0; if ((i+1<(int)medianValues_.size())&&(fragmentNotNA_lengths_[i+1]<=maxRegionLengthToDelete)) { right = i+1; for (int j=i+2; j<(int)fragment_lengths_.size()-1; j++) { if (fragmentNotNA_lengths_[j]<=maxRegionLengthToDelete) right = j; else break; } } recalcFlanksForIndeces (i, right); } if ((medianValues_[medianValues_.size()-1]!=NA)&&(fragmentNotNA_lengths_[medianValues_.size()-1]<=maxRegionLengthToDelete)) { int i = medianValues_.size()-1; int left = medianValues_.size()-1; if ((i-1>=0)&&(fragmentNotNA_lengths_[i-1]<=maxRegionLengthToDelete)) { left = i-1; for (int j=i-2; j>0; j--) { if (fragmentNotNA_lengths_[j]<=maxRegionLengthToDelete) left = j; else break; } recalcFlanksForIndeces (left,i); } } } void ChrCopyNumber::recalcFlanksForIndeces (int i_start, int i_end) { vector <float> data; int notNA = 0; int totalCount = 0; int breakPointStart = 0; int breakPointEnd = 0; for (int i = i_start; i<=i_end; i++) { //collect data points: breakPointStart = 0; if (i>0) breakPointStart = bpfinal_[i-1]+1; breakPointEnd = bpfinal_[i]; for (int j = breakPointStart; j <= breakPointEnd; j++) if (ratio_[j] != NA) { data.push_back(ratio_[j]); notNA++; } totalCount += breakPointEnd-breakPointStart+1; } float median; if (notNA==0 ||(notNA == 1 && totalCount>2)) { // median = get_median(data); median = NA; } else { median = get_median(data); //including the last point!!!! } float sd_local = sd(data,median); for (int i = i_start; i<=i_end; i++) { medianValues_[i] = median; sd_[i] = sd_local; } breakPointStart = 0; if (i_start>0) breakPointStart = bpfinal_[i_start-1]+1; for (int j = breakPointStart; j<= breakPointEnd; j++) medianProfile_[j] = median; } void ChrCopyNumber::clearCGcontent () { GCprofile_.clear (); } void ChrCopyNumber::clearNonNpercent () { notNprofile_.clear (); } void ChrCopyNumber::clearMappabilityProfile () { mappabilityProfile_.clear (); } void ChrCopyNumber::addToCGcontent (float valueToAdd) { GCprofile_.push_back(valueToAdd); } void ChrCopyNumber::addToNonNpercent (float valueToAdd) { notNprofile_.push_back(valueToAdd); } void ChrCopyNumber::addToMappabilityProfile (float valueToAdd) { mappabilityProfile_.push_back(valueToAdd); } void ChrCopyNumber::addToGenes_name(string i) { genes_names.push_back(i); } void ChrCopyNumber::createMappabilityProfile() { for (int i=0; i<length_; i++) mappabilityProfile_.push_back(0); } void ChrCopyNumber::checkOrCreateNotNprofileWithZeros() { int sizeOfNonN = notNprofile_.size(); if (sizeOfNonN<length_) { notNprofile_ = vector <float> (length_); } for (int i = 0; i< length_; i++) notNprofile_[i]=0; } void ChrCopyNumber::fillCGprofile(std::string const& chrFolder) { GCprofile_ = vector <float> (length_); notNprofile_ = vector <float> (length_); ifstream file; string filename = chromosome_; string possibleFilenames[] = {filename,filename+".fa",filename+".fasta","chr"+filename+".fa","chr"+filename+".fasta"}; for (int i = 0; i < 5; i++) { string myFilename = possibleFilenames[i]; string myFullPath = pathAppend(chrFolder,myFilename); file.open(myFullPath.c_str()); if(!file.is_open()) file.clear(); else i = 6; } if (!file.is_open()) { // throw ("Unable to open fasta file for chr "+chromosome_+" in "+chrFolder+"\n"); cerr << "Unable to open fasta file for chr "+chromosome_+" in folder "+chrFolder+"\n\nPlease note, "<< chrFolder << " should be a folder, not a file!\n\n"; exit (-1); } //string myString; char letter; // here we read the chromosome letter by letter. Can do it better! file >> letter; int count = 0; int countCG = 0; int countN = 0; string line; string text = ""; if (letter == '>') getline (file,line); else { count = 1; countCG = isCG(letter); countN = isN(letter); text.push_back(letter); } if (ends_.size()==0) { //all windows have equal length => can use the same windowsize for all windows for (int i = 0; i<length_; i++) { if (file.eof()) { GCprofile_[i] = NA; //cout << "End-of-file reached.." << endl; } while((!file.eof()) && (count < windowSize_)) { file>>letter; countCG += isCG(letter); countN += isN(letter); count ++; } notNprofile_[i] = float(count-countN)/count; if (count == countN) GCprofile_[i] = NA; else GCprofile_[i] = float(countCG)/(count-countN); //reset countCG = 0; countN = 0; count = 0; } } else { int start, end; for (int i = 0; i<length_; i++) { if (file.eof()) { GCprofile_[i] = NA; //cout << "End-of-file reached.." << endl; } start = coordinates_[i]; end = ends_[i]; while((!file.eof()) && (count < start)) { file>>letter; count ++; } while((!file.eof()) && (count <= end)) { file>>letter; text.push_back(letter); count ++; } notNprofile_[i] = 1; //notNprofile_[i] = float(end-start+1-countN)/(end-start+1); /*if (end-start+1 == countN) GCprofile_[i] = NA; else */ countCG =0; countN = 0; for(int j = 0; j < (int)text.length(); j++) //++j???? if (text[j] == 'C' || text[j] == 'G' || text[j] == 'c' || text[j] == 'g') countCG++; else if (text[j] == 'N') countN++; if (end-start+1-countN>0) GCprofile_[i] = float(countCG)/(end-start+1-countN); else GCprofile_[i] = NA; //reset if (i+1<length_) { int nextStart = coordinates_[i+1]; if (nextStart<=end) { //count = end; //and delete prefix in text; int howMuchToDelete = nextStart - start; if (howMuchToDelete<0) { cerr << "Error: your BED file with coordinates of targeted regions does not seem to be sorted\nCheck chromosome "<<chromosome_<<"\n"; cout << "Exit Control-FREEC: before reruning, please, sort the BED file with coordinates of the targeted regions\n"; exit(-1); } if (howMuchToDelete==0) { cerr << "Error: your BED file with coordinates of targeted regions may contain duplicates\nCheck chromosome "<<chromosome_<<"\n"; cout << "Exit Control-FREEC: before reruning sort the BED file with coordinates of the targeted regions and REMOVE DUPLICATED REGIONS\n"; exit(-1); } text = text.substr(howMuchToDelete); } else { text = ""; } } } } file.close(); } void ChrCopyNumber::deleteFragment(int i) { fragmentNotNA_lengths_[i] = 0; medianValues_[i] = NA; sd_[i] = NA; } float ChrCopyNumber::getBAFat (int i){ return BAF_[i]; } float ChrCopyNumber::getBAFProfileAt (int i){ return estimatedBAFProfile_[i]; } float ChrCopyNumber::getFittedBAFProfileAt (int i){ return fittedBAFProfile_[i]; } std::string ChrCopyNumber::getBAFsymbolAt (int i) { return medianBAFSymbol_[i]; } float ChrCopyNumber::getEstimatedBAFuncertaintyAtI(int i) { if (i>0 &&i<int(estimatedBAFuncertainty_.size())) return estimatedBAFuncertainty_[i]; return NA; } float ChrCopyNumber::getSmoothedProfileAtI(int i) { return smoothedProfile_[i]; } float ChrCopyNumber::getSmoothedForInterval(int start , int end) { return get_median (smoothedProfile_,start,end); } void ChrCopyNumber::pushSmoothedProfile(float value) { smoothedProfile_.push_back(value); } int ChrCopyNumber::getEndsSize() { return ends_.size(); } void ChrCopyNumber::setLookingForSubclones(bool value) { isLookingForSubclones_=value; if (value) { if (coordinates_.size()==0) {cerr << "Warning: you should intialize the ChrCopyNumber object before calling this function!!!\n";} if (copy_number_subc_.size()==0) { copy_number_subc_=vector <int> (coordinates_.size(),0); } if (population_subc_.size()==0) { population_subc_=vector <float> (coordinates_.size(),0.0); } } } ChrCopyNumber::~ChrCopyNumber(void) { coordinates_.clear(); readCount_.clear(); smoothedProfile_.clear(); fragmentNotNA_lengths_.clear(); //TODO all other vectors length_ = 0; copy_number_subc_.clear(); population_subc_.clear(); } void ChrCopyNumber::createBAF(float value) { for (int i=0; i<length_; i++) BAF_.push_back(value); } void ChrCopyNumber::createBAFvalues() { for (int i=0; i<length_; i++) BAFvalues_.push_back(""); } void ChrCopyNumber::addBAFinfo(SNPinGenome & snpingenome,int indexSNP) { SNPatChr SNPsatChr = snpingenome.SNP_atChr(indexSNP); //create a vector with BAF createBAF(NA); createBAFvalues(); //BAFvalues_ int totalSNPnumber = SNPsatChr.getSize() ; cout << "..Total Number of SNPs: "<< totalSNPnumber <<"\n"; int SNPcount = 0; float currentBAF = SNPsatChr.getValueAt(SNPcount); float currentBAFstatus = SNPsatChr.getStatusAt(SNPcount); int getSNPpos = SNPsatChr.getPositionAt(SNPcount); float minBAF; for (int i = 0; i<length_; i++) { int left = coordinates_[i]; int right = getEndAtBin(i); if (getSNPpos>=left && getSNPpos <=right) { // snpingenome.SNP_atChr(indexSNP).setBinAt(SNPcount,i); snpingenome.setBinAt(indexSNP,SNPcount,i); if (currentBAFstatus !=0 && currentBAF != NA) { //there are values that indicate that this SNP can be heterozygios if (BAFvalues_[i] != "") BAFvalues_[i] += ";"; stringstream ss (stringstream::in | stringstream::out); ss << currentBAF; BAFvalues_[i] += ss.str(); } minBAF = BAF_[i]; if (minBAF==NA) { BAF_[i]=currentBAF; } else { if (fabs(minBAF-0.5) > fabs(currentBAF-0.5)){ BAF_[i]=currentBAF; //BAF_[i]=min(minBAF,currentBAF); } } } else if (getSNPpos<left) { if (SNPcount+1 < totalSNPnumber) { // EV bug fix: 2013-01-17 SNPcount++; getSNPpos = SNPsatChr.getPositionAt(SNPcount); currentBAF = SNPsatChr.getValueAt(SNPcount); currentBAFstatus = SNPsatChr.getStatusAt(SNPcount); if (windowSize_ == 0 && step_ == 0) { i=max(i-2,0); // assuming that the positions of SNPs are sorted } else { i=max(-1,i-windowSize_/step_-1); } //cout << SNPcount << " out of "<< totalSNPnumber<<"\n"; } } } for (int i = 0; i<length_; i++) { if (ratio_[i]==NA && BAF_[i]!=NA) //set BAF=NA in windows with ratio==NA to remove the noise from windows with low mappability BAF_[i]=NA; if (BAF_[i]==0) //remove windows with 100% AA counts BAF_[i]=NA; if (BAF_[i]!=NA && BAF_[i]!=0 && BAF_[i]!=1) { //recalculate if using BAFvalues_[i] vector<string>heteroValuesPerWindowStrings = split(BAFvalues_[i], ';'); if (heteroValuesPerWindowStrings.size()>0) { vector<float>heteroValuesPerWindow; for (int unsigned j = 0; j < heteroValuesPerWindowStrings.size(); j++) { stringstream ss; float f; ss << heteroValuesPerWindowStrings[j]; ss >> f; heteroValuesPerWindow.push_back(fabs(f-0.5)); } float median = get_median(heteroValuesPerWindow)+0.5; BAF_[i] = median; } else { // if (BAF_[i]>0 && BAF_[i] <0.5) //put the noise on top // BAF_[i] = 1-BAF_[i]; BAF_[i] = NA; //delete all homoz.! } } } } //find closest value to k/ploidy for medianValue float ChrCopyNumber::getLevelAt(int unsigned i, int ploidy) { float value = medianValues_[i]; float valueToReturn; if (value >0) valueToReturn = float(int(value*ploidy + 0.5))/ploidy; else valueToReturn = float(int(value*ploidy))/ploidy; //use BAF for ambigious cases: if (valueToReturn>0 && estBAFuncertaintyPerFrag_.size()>i && BAFsymbPerFrag_[i].compare("-")!=0 &&BAFsymbPerFrag_[i]!="" && BAFsymbPerFrag_[i].length()!=valueToReturn*ploidy && (estBAFuncertaintyPerFrag_[i] < MAXUncertainty)) { //change Level value if there is no incertainty: valueToReturn=BAFsymbPerFrag_[i].length()*1./ploidy; } return valueToReturn; } void ChrCopyNumber::setRCountToZeroForNNNN() { for (unsigned int i = 0; i< notNprofile_.size(); i++) { if (notNprofile_[i]==0) { readCount_[i]=0; } } for (unsigned int i = notNprofile_.size(); i< readCount_.size(); i++) { readCount_[i]=0; } } void* ChrCopyNumber_calculateBreakpoint_wrapper(void *arg) { ChrCopyNumberCalculateBreakpointArgWrapper* warg = (ChrCopyNumberCalculateBreakpointArgWrapper*)arg; int result = warg->chrCopyNumber.calculateBreakpoints(warg->breakPointThreshold, 0, warg->breakPointType); if (result <= 0) { cerr << "..failed to run segmentation on chr" << warg->chrCopyNumber.getChromosome() << "\n"; } return NULL; } void* ChrCopyNumber_calculateBAFBreakpoint_wrapper(void *arg) { ChrCopyNumberCalculateBreakpointArgWrapper* warg = (ChrCopyNumberCalculateBreakpointArgWrapper*)arg; int result = warg->chrCopyNumber.calculateBAFBreakpoints(warg->breakPointThreshold, 0, warg->breakPointType); if (result == 0) { cerr << "..failed to run BAF segmentation on chr" << warg->chrCopyNumber.getChromosome() << "\n"; } return NULL; }
[ "valentina.boeva@gmail.com" ]
valentina.boeva@gmail.com
85ae2b4f34673aa25e1cd8ba8723f2ef6cf74397
6ef4a73fc1ea09e7de7465eaef001f47b8dfa893
/Fontes/TopologiaDMS/TEqptoTopologia.cpp
610a0f85ec3112b70d3234d5028639c0344a20d5
[]
no_license
danilodesouzapereira/ProjetoEDPDMS
aa8ca3cdada9b1f7506c0a8e33cfb37e82479cab
d87c5603b0ac368f58e597b24576c384113b75c7
refs/heads/master
2020-09-26T19:53:55.301750
2020-01-22T12:12:20
2020-01-22T12:12:20
226,331,180
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
//--------------------------------------------------------------------------- #pragma hdrstop //--------------------------------------------------------------------------- #include "TEqptoTopologia.h" #include <PlataformaSinap\Fontes\Apl\VTApl.h> //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- __fastcall TEqptoTopologia::TEqptoTopologia(VTApl* apl) { this->apl = apl; } //--------------------------------------------------------------------------- __fastcall TEqptoTopologia::~TEqptoTopologia() { } //---------------------------------------------------------------------------
[ "danilodesouzapereira@gmail.com" ]
danilodesouzapereira@gmail.com
a6a11158d45e3b4e6005aa9f2c9da28f8c050a43
83ba2247eb65387eef544ef235c5aa28fe117119
/Connecter.h
b02f7ae216ea1e628bded911cff3b2c0070c85e1
[]
no_license
kspine/window-network-IOCP
03ff2629974c5a8d2c3ece7dca57b9dc3980f606
d18030ce4f0c7e3be64d89eb5b764577515b35f5
refs/heads/master
2021-01-20T05:44:08.384390
2015-06-03T16:20:00
2015-06-03T16:20:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
#ifndef CONNECTER_H__ #define CONNECTER_H__ #include "NetObject.h" class Connecter : public NetObject { public: Connecter(void); ~Connecter(void); bool Connect_To_Server(const std::string strIP,unsigned short nPort); private: SOCKET _socket; std::string _strIP; unsigned short _nPort; }; #endif
[ "freexleisure@126.com" ]
freexleisure@126.com
864262fb09bf30229d80da42229f2bf4310f8d3c
0cda2dcf353c9dbb42e7b820861929948b9942ea
/fileedit/2009/SyllableSorting.cpp
54438fd16b16fea8d23863ecfd13e23d1e098f45
[]
no_license
naoyat/topcoder
618853a31fa339ac6aa8e7099ceedcdd1eb67c64
ec1a691cd0f56359f3de899b03eada9efa01f31d
refs/heads/master
2020-05-30T23:14:10.356754
2010-01-17T04:03:52
2010-01-17T04:03:52
176,567
1
1
null
null
null
null
UTF-8
C++
false
false
9,352
cpp
// BEGIN CUT HERE /* // PROBLEM STATEMENT // Syllable sorting is a method of sorting words based on their syllabic decompositions. The first step is to decompose each word into syllables. A syllable is defined as a maximal non-empty substring of consonants followed by a maximal non-empty substring of vowels. The only vowels are 'a', 'e', 'i', 'o' and 'u'. All other letters are considered consonants. All words will start with a consonant and end with a vowel. To compare two words syllabically, first decompose them into sequences of syllables. For example, the words "zcdbadaerfe" and "foubsyudba" decompose as follows: "zcdbadaerfe" = {"zcdba", "dae", "rfe"} "foubsyudba" = {"fou", "bsyu", "dba"} Then, sort each sequence of syllables alphabetically. In the above example, the sequences become: {"dae", "rfe", "zcdba"} {"bsyu", "dba", "fou"} Then, compare these sorted sequences lexicographically. A sequence S1 comes before a sequence S2 lexicographically if S1 has an alphabetically earlier element at the first index at which they differ. In the above example, the second sequence comes earlier lexicographically because "bsyu" comes before "dae" alphabetically. If two sorted sequences are equal, then compare their corresponding unsorted sequences instead. For example, the words "daba" and "bada" decompose into the same sorted sequence {"ba", "da"}. Compare the unsorted sequences {"da", "ba"} and {"ba", "da"} to determine that "bada" comes before "daba". You are given a vector <string> words. Sort the words using the method above and return the resulting vector <string>. DEFINITION Class:SyllableSorting Method:sortWords Parameters:vector <string> Returns:vector <string> Method signature:vector <string> sortWords(vector <string> words) CONSTRAINTS -words will contain between 1 and 50 elements, inclusive. -Each element of words will contain between 2 and 50 characters, inclusive. -Each element of words will contain only lowercase letters ('a'-'z'). -The first character of each element of words will be a consonant. -The last character of each element of words will be a vowel. EXAMPLES 0) {"xiaoxiao", "yamagawa", "gawayama"} Returns: {"gawayama", "yamagawa", "xiaoxiao" } After decomposing the words into sequences of syllables, we get the following unsorted and sorted sequences of syllables: WORD | UNSORTED SEQUENCES | SORTED SEQUENCES -----------+--------------------------+-------------------------- "xiaoxiao" | {"xiao", "xiao"} | {"xiao", "xiao"} "yamagawa" | {"ya", "ma", "ga", "wa"} | {"ga", "ma", "ya", "wa"} "gawayama" | {"ga", "wa", "ya", "ma"} | {"ga", "ma", "ya", "wa"} To compare "xiaoxiao" with the other two words, we use the sorted sequences of syllables. However, to compare "yamagawa" with "gawayama" we have to use the unsorted sequences because the sorted ones are equal. 1) {"bcedba", "dbabce", "zyuxxo"} Returns: {"bcedba", "dbabce", "zyuxxo" } 2) {"hgnibqqaxeiuteuuvksi", "jxbuzui", "zrotyqeruiydozui", "ywuuzkto", "lmopbookoagyco", "vredfvavvexliu"} Returns: {"hgnibqqaxeiuteuuvksi", "vredfvavvexliu", "lmopbookoagyco", "jxbuzui", "zrotyqeruiydozui", "ywuuzkto" } 3) {"crazgo", "cwsoygiokiuo", "yueoseeu", "tuadiojvugeoe", "naumxditui", "sgukkelyoi", "nrohjuasoia", "mgabmo"} Returns: {"mgabmo", "crazgo", "cwsoygiokiuo", "tuadiojvugeoe", "nrohjuasoia", "sgukkelyoi", "naumxditui", "yueoseeu" } 4) {"wheewjuguoi", "coutcu", "hqivaa", "sgiibgwi", "ypaqpki", "bgyikouapae", "wqakeu", "skolfo", "pzesaa", "ypivhi"} Returns: {"sgiibgwi", "bgyikouapae", "coutcu", "wheewjuguoi", "hqivaa", "wqakeu", "skolfo", "pzesaa", "ypaqpki", "ypivhi" } */ // END CUT HERE #line 96 "SyllableSorting.cpp" #include <string> #include <vector> #include <set> #include <map> #include <list> #include <queue> #include <algorithm> // BEGIN CUT HERE #include <iostream> #include "cout.h" // END CUT HERE #include <sstream> #include <cmath> using namespace std; #define sz(a) int((a).size()) #define pb push_back #define all(c) (c).begin(),(c).end() #define tr(c,i) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++) #define rep(var,n) for(int var=0;var<(n);var++) #define found(s,e) ((s).find(e)!=(s).end()) #define remove_(c,val) (c).erase(remove((c).begin(),(c).end(),(val)),(c).end()) #define lastc(str) (*((str).end()-1)) typedef long long ll; typedef vector<int> vi; typedef vector<string> vs; typedef vector<long long> vll; string join(const vector<string> &v){ stringstream ss; tr(v,it) ss << *it; return ss.str(); } class SyllableSorting { int vowelp(int c){ switch(c){ case 'a':case 'e':case 'i':case 'o':case 'u': return true; default: return false; } } vector<string> parse(string s){ vector<string> res; int st=1,l=sz(s),b=0; for(int i=0;i<l;i++){ if(vowelp(s[i])){ st=2; }else{ if(st==2){ res.pb(s.substr(b,i-b)); b=i; st=1; } } } if(b<l) res.pb(s.substr(b)); //cout << s << " => " << res << endl; return res; } public: vector<string> sortWords(vector<string> words) { int n=sz(words); vector<pair<vector<string>,pair<vector<string>,string> > > res(n); rep(i,n){ vector<string> syls=parse(words[i]); vector<string> sorted(all(syls)); sort(all(sorted)); res[i]=make_pair(sorted,make_pair(syls,words[i])); //cout << res[i] << endl; } sort(all(res)); //cout << res << endl; vector<string> ans(n); rep(i,n) ans[i]=res[i].second.second; return ans; } }; // BEGIN CUT HERE #include <time.h> clock_t start_time; void timer_clear() { start_time = clock(); } string timer() { clock_t end_time = clock(); double interval = (double)(end_time - start_time)/CLOCKS_PER_SEC; ostringstream os; os << " (" << interval*1000 << " msec)"; return os.str(); } template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } int verify_case(const vector <string> &Expected, const vector <string> &Received) { if (Expected == Received) cerr << "PASSED" << timer() << endl; else { cerr << "FAILED" << timer() << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } return 0;} template<int N> struct Case_ {}; char Test_(...); int Test_(Case_<0>) { timer_clear(); string words_[] = {"xiaoxiao", "yamagawa", "gawayama"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"gawayama", "yamagawa", "xiaoxiao" }; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } int Test_(Case_<1>) { timer_clear(); string words_[] = {"bcedba", "dbabce", "zyuxxo"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"bcedba", "dbabce", "zyuxxo" }; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } int Test_(Case_<2>) { timer_clear(); string words_[] = {"hgnibqqaxeiuteuuvksi", "jxbuzui", "zrotyqeruiydozui", "ywuuzkto", "lmopbookoagyco", "vredfvavvexliu"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"hgnibqqaxeiuteuuvksi", "vredfvavvexliu", "lmopbookoagyco", "jxbuzui", "zrotyqeruiydozui", "ywuuzkto" }; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } int Test_(Case_<3>) { timer_clear(); string words_[] = {"crazgo", "cwsoygiokiuo", "yueoseeu", "tuadiojvugeoe", "naumxditui", "sgukkelyoi", "nrohjuasoia", "mgabmo"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"mgabmo", "crazgo", "cwsoygiokiuo", "tuadiojvugeoe", "nrohjuasoia", "sgukkelyoi", "naumxditui", "yueoseeu" }; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } int Test_(Case_<4>) { timer_clear(); string words_[] = {"wheewjuguoi", "coutcu", "hqivaa", "sgiibgwi", "ypaqpki", "bgyikouapae", "wqakeu", "skolfo", "pzesaa", "ypivhi"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"sgiibgwi", "bgyikouapae", "coutcu", "wheewjuguoi", "hqivaa", "wqakeu", "skolfo", "pzesaa", "ypaqpki", "ypivhi" }; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } int Test_(Case_<5>) { timer_clear(); string words_[] = {"baqibae", "baebaqi"}; vector <string> words(words_, words_+sizeof(words_)/sizeof(*words_)); string RetVal_[] = {"baqibae", "baebaqi"}; vector <string> RetVal(RetVal_, RetVal_+sizeof(RetVal_)/sizeof(*RetVal_)); return verify_case(RetVal, SyllableSorting().sortWords(words)); } template<int N> void Run_() { cerr << "Test Case #" << N << "..." << flush; Test_(Case_<N>()); Run_<sizeof(Test_(Case_<N+1>()))==1 ? -1 : N+1>(); } template<> void Run_<-1>() {} int main() { Run_<0>(); } // END CUT HERE
[ "naoya_t@users.sourceforge.jp" ]
naoya_t@users.sourceforge.jp