blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
be940be05969aeb9a22f80ed0f518cd5c09b78bc
97fdd9cf69202e357ebcf9aed822216a1a9f3e13
/6thJan/threading/1.cpp
3d78ff5bf5844359f584ed5cb61877cafd4a0fea
[]
no_license
kuldipsinh1993/Features-of-C-11
39a4f6e659984d33a2118ab8211d36165e788225
e69d907873f8eae16419a8166af07c492e388499
refs/heads/master
2020-12-07T13:55:24.479226
2020-01-11T05:23:02
2020-01-11T05:23:02
232,732,995
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> #include <thread> using namespace std; void print() { cout << "Hello" << endl; } void add(int a, int b) { cout << a << " + " << b << " = " << a+b << endl; } int main() { thread t1{print}; thread t2{add, 1, 2}; t1.join(); t2.join(); return 0; }
34393b9024405569c5537a269fe1c45bb1e7377b
08975710b7b1327d21876484337e26b56f988967
/test_floats.cpp
19558ef148fe7f31ad436b69aeb94614559b4d59
[]
no_license
manucorporat/OBME
2e64463f21986c14873a078285397c4a6a2470f4
87c30bec845ddeab002ca76f6804798524c4cfa2
refs/heads/master
2021-06-06T18:22:04.545983
2017-06-16T08:32:59
2017-06-16T08:32:59
9,354,938
21
3
null
null
null
null
UTF-8
C++
false
false
417
cpp
// // test.cpp // OBME: OBfuscated MEmory // // Created by Manuel Martinez-Almeida on 04/10/13. // Copyright 2013 Manuel Martinez-Almeida. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "obme.h" using namespace obme; int main() { long long i = -1000; for(; i < 1000; ++i) { float obf = OBME(i*1.123f); printf("%f: %f \n", OBME(obf), obf); } return 1; }
deca0b2f5d97b4e7f116b85c43a49d435b7cc471
24f26275ffcd9324998d7570ea9fda82578eeb9e
/ash/system/tray/tray_utils.cc
19eeb01541c40a9d037677c313ce0ca764919015
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
1,092
cc
// Copyright (c) 2012 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 "ash/system/tray/tray_utils.h" #include "ash/style/ash_color_provider.h" #include "ash/system/tray/tray_constants.h" #include "ui/gfx/font_list.h" #include "ui/views/controls/label.h" namespace ash { void SetupLabelForTray(views::Label* label) { // The text is drawn on an transparent bg, so we must disable subpixel // rendering. label->SetSubpixelRenderingEnabled(false); label->SetFontList(gfx::FontList().Derive( kTrayTextFontSizeIncrease, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); } SkColor TrayIconColor(session_manager::SessionState session_state) { const bool light_icon = session_state == session_manager::SessionState::OOBE; return AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconPrimary, light_icon ? AshColorProvider::AshColorMode::kLight : AshColorProvider::AshColorMode::kDark); } } // namespace ash
ebcfbbad9945aa34d6c0c59651036202e5beb737
5129977ddf8314c42b41d6bd63014c4732fb924e
/0714/dp.cpp
67bef3273950ad04995ca1a379be16c7d134d244
[]
no_license
ysk24ok/leetcode-submissions
516e1b6107c75867b455e5c21cc9e6ba72e5c52e
5ba25812a74e8eb98c68a8265f8cccd4a26f3be8
refs/heads/master
2022-07-01T15:32:50.258102
2022-06-28T12:06:19
2022-06-28T12:06:19
66,719,593
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
#include <algorithm> #include <cassert> #include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int>& prices, int fee) { size_t size = prices.size(); if (size <= 1) return 0; vector<int> buy(size); vector<int> sell(size); buy[0] = - prices[0] - fee; for (size_t i = 1; i < size; i++) { buy[i] = max(sell[i-1] - prices[i] - fee, buy[i-1]); // buy stock or do nothing sell[i] = max(prices[i] + buy[i-1], sell[i-1]); // sell stock or do nothing } return sell[size - 1]; } }; int main() { Solution sol; vector<int> prices; int got; prices = {1,3,2,8,4,9}; assert(sol.maxProfit(prices, 2) == 8); prices = {7,1,5,3,6,7,4}; assert(sol.maxProfit(prices, 3) == 3); prices = {1,3,7,5,10,3}; assert(sol.maxProfit(prices, 3) == 6); prices = {}; assert(sol.maxProfit(prices, 1) == 0); prices = {1,2}; assert(sol.maxProfit(prices, 1) == 0); prices = {1,4}; assert(sol.maxProfit(prices, 1) == 2); prices = {2,1}; assert(sol.maxProfit(prices, 1) == 0); prices = {1,4,3}; assert(sol.maxProfit(prices, 1) == 2); }
353e68fd1d097860258eeaa7bd094dfa1ffc41e1
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Game/GameCommon/stdafx.h
b2a60820d874ca1bfa0aa31a1458d7f176452ef5
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UHC
C++
false
false
782
h
// stdafx.h : 자주 사용하지만 자주 변경되지는 않는 // 표준 시스템 포함 파일 및 프로젝트 관련 포함 파일이 // 들어 있는 포함 파일입니다. // #pragma once #ifndef _WIN32_WINNT // Windows XP 이상에서만 기능을 사용할 수 있습니다. #define _WIN32_WINNT 0x0501 // 다른 버전의 Windows에 맞도록 적합한 값으로 변경해 주십시오. #endif #define WIN32_LEAN_AND_MEAN // 거의 사용되지 않는 내용은 Windows 헤더에서 제외합니다. #include <vector> #include <list> #include <set> #include <map> #include <algorithm> #include <string> using namespace std; #include "RTypes.h" #include "RTimer.h" using namespace rs3; #include "MDebug.h"
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
a2be4cfebcc02c6fe2a127c2cce850908cfb17a2
f006a6dde178b6938df2535184bc2bc679cf7908
/DataDecoder.cpp
4e791a5b4006830462162951cbd814afa1da674d
[ "MIT" ]
permissive
ReimuNotMoe/NVITools
3fffee4f95d19783648b91dd569556115976b1c1
5659996e622dfe4710ec1fb246294a4d6f5ddfea
refs/heads/master
2020-04-07T15:28:45.221468
2018-11-21T07:56:22
2018-12-18T00:50:01
158,487,366
2
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include <cstdio> #include <cstdlib> #include <cinttypes> #include <vector> #include <cstring> int main(int argc, char **argv) { int base = 10; int i = 1; if (argv[1]) { if (0 == strcmp(argv[1], "--hex")) { base = 16; i = 2; printf("Using hex mode.\n"); } } std::vector<uint8_t> buf; for (; i<argc; i++) { auto byte = (uint8_t)strtol(argv[i], NULL, base); buf.push_back(byte); } printf("Length: %zu\n", buf.size()); // printf("Data: "); // // for (auto &it : buf) { // printf("%" PRIu8 " ", it); // } // // printf("\n\n"); if (buf.size() == 4) { printf("x32: %" PRIx32 "\n", *(uint32_t *)buf.data()); printf("u32: %" PRIu32 "\n", *(uint32_t *)buf.data()); printf("d32: %" PRId32 "\n", *(uint32_t *)buf.data()); printf("\n\n"); } if (buf.size() == 8) { printf("x64: %" PRIx64 "\n", *(uint64_t *)buf.data()); printf("u64: %" PRIu64 "\n", *(uint64_t *)buf.data()); printf("d64: %" PRId64 "\n", *(uint64_t *)buf.data()); printf("\n\n"); } buf.push_back(0); printf("String: %s\n", buf.data()); return 0; }
1be3d278bd3e21dc31067d6131dd49cd9ab5795c
a2bde27da5b65e500c13ff4931ef8ccea025d86c
/view_add_edit_delete/Edit.cpp
15ec5e0390cccd98bd1be3c8f23c0d757ee47630
[]
no_license
dzikrafathin/pengantar_algoritma_cpp
8913c584efe6adeeca326bc621e8aa7ee4ed2f6e
1b3ddeeaa3d926267e1df5ed85b481cb08657f44
refs/heads/master
2020-04-05T03:03:24.428984
2019-01-09T00:45:36
2019-01-09T00:45:36
156,499,831
0
0
null
null
null
null
UTF-8
C++
false
false
814
cpp
#include<iostream> using namespace std; int main(){ int a[5]={23,12,32,11,33}; int ubah_a, b; int x=0; for (int c=0; c<5; c++){ cout << "Data Array [" << c << "]: " << a[c] <<endl; } cout << "Masukkan Nilai Yang Akan Diubah : "; cin >> b; for(int i=0;i<5;i++){ if(a[i] == b){ x=1 ; cout << "Data dengan nilai "<< b <<" di index ke-"<<i<<"\n"; cout << "Masukkan data yang baru: "; cin >> a[i]; cout << "Data yang baru: "<<endl; for(i=0;i<5;i++){ cout<<"Data ke-"<< i <<" :"<< a[i] << endl; } } else{ cout << "Tidak ditemukan!"; } } }
7752198aba370f9fab7e8b369621aa1a7df03841
e62853e23bb87183850139a344ff2d0384a6021c
/2019.04.13-16-12/2019.04.13-16-12.ino
1686cc2b7b770af027c3c33458664fa90db2556f
[]
no_license
maeng-gu/DGSW_RTOS
c8ca489fd9e7bc933c983cd6fce3edee64417620
fcb6bb2458e3603b6d8e0a90f842fe475c6b5ed8
refs/heads/master
2020-05-22T15:09:59.836341
2019-05-13T10:53:43
2019-05-13T10:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,564
ino
#define X_STEP_PIN 54 #define X_DIR_PIN 55 #define X_ENABLE_PIN 38 #define X_MIN_PIN 3 #define X_MAX_PIN 2 #define Y_STEP_PIN 60 #define Y_DIR_PIN 61 #define Y_ENABLE_PIN 56 #define Y_MIN_PIN 14 #define Y_MAX_PIN 15 #define Z_STEP_PIN 46 #define Z_DIR_PIN 48 #define Z_ENABLE_PIN 62 #define Z_MIN_PIN 18 #define Z_MAX_PIN 19 #define E_STEP_PIN 26 #define E_DIR_PIN 28 #define E_ENABLE_PIN 24 #define SDPOWER -1 #define SDSS 53 #define LED_PIN 13 #define FAN_PIN 9 #define PS_ON_PIN 12 #define KILL_PIN -1 #define HEATER_0_PIN 10 #define HEATER_1_PIN 8 #define TEMP_0_PIN 13 // ANALOG NUMBERING #define TEMP_1_PIN 14 // ANALOG NUMBERING bool init_x = true, init_y = true; bool center_x = false, center_y = false; bool toggle_x, toggle_y; bool toggle_dir_x, toggle_dir_y; bool toggle_stop_x, toggle_stop_y; unsigned long per, per2, milpre; int count_x, count_y; unsigned long limit_x,limit_y; void firstSetting() { pinMode(X_STEP_PIN, OUTPUT); pinMode(X_DIR_PIN, OUTPUT); pinMode(X_ENABLE_PIN, OUTPUT); pinMode(Y_STEP_PIN, OUTPUT); pinMode(Y_DIR_PIN, OUTPUT); pinMode(Y_ENABLE_PIN, OUTPUT); pinMode(X_MIN_PIN, INPUT); pinMode(Y_MIN_PIN, INPUT); ////////////// PINMODE ////////////// digitalWrite(X_MIN_PIN, 1); digitalWrite(Y_MIN_PIN, 1); digitalWrite(X_ENABLE_PIN, 0); digitalWrite(Y_ENABLE_PIN, 0); digitalWrite(X_DIR_PIN, 1); digitalWrite(Y_DIR_PIN, 1); toggle_stop_x = 0; center_x = 0; } void Input_Key() { if (Serial.available()) { char key = Serial.read(); if (key == 'a') { toggle_stop_x = 0; digitalWrite(X_DIR_PIN, 0); } if (key == 'd') { toggle_stop_x = 0; digitalWrite(X_DIR_PIN, 1); } if (key == 'w') { toggle_stop_y = 0; digitalWrite(Y_DIR_PIN, 0); } if (key == 's') { toggle_stop_y = 0; digitalWrite(Y_DIR_PIN, 1); } if (key == 'r') { toggle_stop_x = 0; toggle_stop_y = 0; digitalWrite(X_DIR_PIN, 1); digitalWrite(Y_DIR_PIN, 1); init_x = true; init_y = true; } if (key == 'o') { toggle_stop_x = 0; toggle_stop_y = 0; if (limit_x > 12500) digitalWrite(X_DIR_PIN, 1); else digitalWrite(X_DIR_PIN, 0); if (limit_x > 11500) digitalWrite(Y_DIR_PIN, 1); else digitalWrite(Y_DIR_PIN, 0); center_x = true; center_y = true; } } } void MOVE_XY(unsigned long cur) { if (cur - per >= 100 && toggle_stop_x == 0) { per = cur; limit_switch_check('x'); limit_position_check('x'); center_position_check('x'); //center position if (toggle_x == true) { count_x++; if (digitalRead(X_DIR_PIN)) limit_x--; else limit_x++; if (center_x) count_x = 0; else if (init_x) count_x = 0; else if (count_x >= 300) { toggle_stop_x = 1; count_x = 0; } digitalWrite(X_STEP_PIN, 1); toggle_x = false; } else { digitalWrite(X_STEP_PIN, 0); toggle_x = true; } //PWM } //x if (cur - per2 >= 100 && toggle_stop_y == 0) { per2 = cur; limit_switch_check('y'); limit_position_check('y'); center_position_check('y'); if (toggle_y == true) { count_y++; if (digitalRead(Y_DIR_PIN)) limit_y--; else limit_y++; if (center_x) count_y = 0; else if (init_y) count_y = 0; else if (count_y >= 300) { toggle_stop_y = 1; count_y = 0; } digitalWrite(Y_STEP_PIN, 1); toggle_y = false; } else { digitalWrite(Y_STEP_PIN, 0); toggle_y = true; } } //y } void limit_switch_check(char xy) { if (xy == 'x') { if (!(digitalRead(X_MIN_PIN))) { if (digitalRead(X_DIR_PIN)) toggle_stop_x = 1; else toggle_stop_x = 0; limit_x = 0; init_x = false; } } else { if (!(digitalRead(Y_MIN_PIN))) { if (digitalRead(Y_DIR_PIN)) toggle_stop_y = 1; else toggle_stop_y = 0; limit_y = 0; init_y = false; } } } void limit_position_check(char xy) { if (xy == 'x') { if (limit_x >= 19000) { if (!(digitalRead(X_DIR_PIN))) toggle_stop_x = 1; else toggle_stop_x = 0; } } else { if (limit_y >= 18000) { if (!(digitalRead(Y_DIR_PIN))) toggle_stop_y = 1; else toggle_stop_y = 0; } } } void center_position_check(char xy) { if (xy == 'x') { if (limit_x == 12500) { toggle_stop_x = 1; center_x = false; } } else { if (limit_y == 11500) { toggle_stop_y = 1; center_y = false; } } } /*void ToPoint_XY(unsigned long cer, long x, long y, bool xd, bool yd){ if (xd) digitalWrite(X_DIR_PIN, 1); else digitalWrite(X_DIR_PIN, 0); if (yd) digitalWrite(Y_DIR_PIN, 1); else digitalWrite(Y_DIR_PIN, 0); if (cer - per >= 100 && toggle_stop_x == 0) { per = cer; count_x++; if (toggle_x == true) { digitalWrite(X_STEP_PIN, 1); toggle_x = false; } else { digitalWrite(X_STEP_PIN, 0); toggle_x = true; } } //x_pwm if (count_x >= x) { toggle_stop_x = 1; } //x_dis if (cer - per2 >= 100 && toggle_stop_y == 0) { per2 = cer; count_y++; if (toggle_y == true) { digitalWrite(Y_STEP_PIN, 1); toggle_y = false; } else { digitalWrite(Y_STEP_PIN, 0); toggle_y = true; } } //y_pwm if (count_y >= y) { toggle_stop_y = 1; } //y_dis } void move_XY_stop(unsigned long cer) { if (cer - per >= 165) { per = cer; count_x++; if (digitalRead(X_MIN_PIN)) toggle_stop_x = true; else toggle_stop_x = false; if (toggle_stop_x) { if (toggle_x) { digitalWrite(X_STEP_PIN, 1); toggle_x = false; } else { digitalWrite(X_STEP_PIN, 0); toggle_x = true; } } } if (cer - per2 >= 200) { if (digitalRead(Y_MIN_PIN)) toggle_stop_y = true; else toggle_stop_y = false; per2 = cer; count_y++; if (toggle_stop_y) { if (toggle_y) { digitalWrite(Y_STEP_PIN, 1); toggle_y = false; } else { digitalWrite(Y_STEP_PIN, 0); toggle_y = true; } } } }
bd2bfbcd33ce71432105daf5f6a664697761b266
916a61acf18417f2edafbbd5ac4e8a0da7e45f83
/MediaReader.hpp
5c293927e3a76c7cdf788a68505ec02b742c6040
[]
no_license
jnhwkim/videoNet
3861ad6ff3c19b917512cf577dd5c945fad15a27
ee75a846f32065de7c20d54c52647f5599b2ebcc
refs/heads/master
2020-05-27T07:07:35.431699
2015-06-03T08:35:08
2015-06-03T08:35:08
33,770,832
0
0
null
null
null
null
UTF-8
C++
false
false
823
hpp
#ifndef MEDIA_READER_H_ #define MEDIA_READER_H_ #include "opencv2/opencv.hpp" #include "SubtitleReader.hpp" #define DEFAULT_SUBTITLE_EXT "smi" enum DetectorType { TYPE_SIFT, }; class MediaReader { private: string _filename; SubtitleReader* _subtitleReader; cv::VideoCapture _cap; public: ~MediaReader(); MediaReader(const cv::string& filename); cv::VideoCapture& operator>>(cv::Mat& image); void get_frame(int idx, cv::Mat& image); const Subtitle& get_subtitle(int idx) const; int get_subtitle_count() const; const string& get_file_extension(); const string get_subtitles(); void kmean_descriptor(DetectorType TYPE, int K, int samples_per_frame, cv::Mat& centroids); static void good_matches(cv::Mat& descriptors, cv::Mat& centroids, cv::vector<cv::DMatch>& good_matches); }; #endif /* MEDIA_READER_H_ */
841103f7bb66b111a549aa34f90af6145cd7fec1
1449d0e1ff6342d46417f48f3d288e42b6c3a236
/src/hxworm/HxWormAtlasReg.cpp
bb3bdad3cb633abb83d2f77be07569caa4a99f4c
[]
no_license
fjug/ZIBAmiraLocal
493c49d4c8360dcdae9271d892f5f280554cd894
c40519411f0b5f4052ea34d2d9e084dffcd0dd5c
refs/heads/master
2016-09-02T05:43:30.664770
2014-02-07T17:51:00
2014-02-07T17:51:00
16,622,545
1
1
null
null
null
null
UTF-8
C++
false
false
46,957
cpp
//////////////////////////////////////////////////////////////// // // Do not use CVS keywords because they cause merge conflicts and make branching unnecessarily hard. // // // Trims vectors in a SurfaceVectorField so that all surfaces generated by Displaces along the vectors are intersection-free // // ///////////////////////////////////////////////////////////////// #define _USE_MATH_DEFINES #include <math.h> #include <hxcore/HxData.h> #include <hxcore/HxWorkArea.h> #include <hxcore/HxMessage.h> #include <hxcore/HxObjectPool.h> #include <hxcore/HxController.h> #include <hxsurfacepath/SurfaceNode.h> #include <hxarith/HxChannelWorks.h> #include <mclib/McDMatrix.h> #include <graphmatching/GraphMatching.h> #include <hxlines/HxLineSet.h> #include <hxworm/WormHelpers.h> #include <hxactiveshape/HxDisplayActiveShape.h> #ifdef _OPENMP #include <omp.h> #endif #include <hxworm/HxWormAtlasReg.h> HX_INIT_CLASS(HxWormAtlasReg, HxCompModule); /// constructor of surface displacement calculation HxWormAtlasReg::HxWormAtlasReg (void) : HxCompModule(HxSurface::getClassTypeId()), portTargetSurface(this,"targetNuclei",HxSurface::getClassTypeId()), portGraphMatching(this,"graphMatchingParams",4), portSpatialDistParams(this,"spatialDistance",2), portColorParams(this,"color",3), portTargetCostParams(this,"targetCost",2), portIncentiveToMatch(this,"incentiveToMatch",1), portShapeParams(this,"shape",2), portBinaryParams(this,"binaryPotentials",2), portGraphMatchingSubproblems(this,"graphMatchingSubproblems",4), portInit(this,"startingPoint",2), portGroupingParams(this,"groupingParams",4), portBestGroupTrafoParams(this,"bestGroupTrafoParams",8), portRotInvariance(this,"rotInvariance",1), portActiveMatchingIterations(this,"activeMatchingIterations",3), portActiveMatchingTrafo(this,"portActiveMatchingTrafo",3), portActiveMatchingModes(this,"portActiveMatchingModes",3), portNorm(this,"norm",2), portDoIt(this, "doIt") { portData.addType(HxActiveShape::getClassTypeId()); // portInit: pair of corresponding points: patch- or vertex-id on atlas, corresponding patch- or vertex-id on target portInit.setLabel(0, "atlas start idx"); portInit.setValue(0, 0); portInit.setLabel(1, "target start idx"); portInit.setValue(1, 0); portInit.hide(); portGraphMatching.setLabel(MAXITER, "maxIter"); portGraphMatching.setValue(MAXITER, 5000); portGraphMatching.setLabel(MAXGAP, "maxGap"); portGraphMatching.setValue(MAXGAP, 1E-5); portGraphMatching.setLabel(LOCALNEIGHS, "localNeighs"); portGraphMatching.setValue(LOCALNEIGHS, 3); portGraphMatching.setLabel(MAXNUMNEIGHS, "numNeighs"); portGraphMatching.setValue(MAXNUMNEIGHS, 3); portSpatialDistParams.setLabel(SPATIALDISTWEIGHT, "spatialDistanceWeight"); portSpatialDistParams.setValue(SPATIALDISTWEIGHT, 0); portSpatialDistParams.setLabel(MAXDISTMATCHED, "maxDistConsidered"); portSpatialDistParams.setValue(MAXDISTMATCHED, 30); portColorParams.setLabel(COLORDISTWEIGHT, "colorDistanceWeight"); portColorParams.setValue(COLORDISTWEIGHT, 0); portColorParams.setLabel(MAXCOLDISTMATCHED, "maxColDistConsidered"); portColorParams.setValue(MAXCOLDISTMATCHED, 3); portColorParams.setLabel(MINCOL, "minColConsidered"); portColorParams.setValue(MINCOL, -1); portTargetCostParams.setLabel(TARGETCOSTWEIGHT, "targetCostWeight"); portTargetCostParams.setValue(TARGETCOSTWEIGHT, 0); portTargetCostParams.setLabel(MAXTARGETCOSTCONSIDERED, "maxTargetCostConsidered"); portTargetCostParams.setValue(MAXTARGETCOSTCONSIDERED, 1000000); portIncentiveToMatch.setLabel(INCENTIVETOMATCH, "incentiveToMatch"); portIncentiveToMatch.setValue(INCENTIVETOMATCH, 150); portShapeParams.setLabel(SHAPEDISTWEIGHT, "shapeDistanceWeight"); portShapeParams.setValue(SHAPEDISTWEIGHT, 0); portShapeParams.setLabel(MAXSHAPEDISTMATCHED, "maxShapeDistConsidered"); portShapeParams.setValue(MAXSHAPEDISTMATCHED, 25); portBinaryParams.setLabel(DIFFSPATIALDISTWEIGHT, "diffSpatialDistanceWeight"); portBinaryParams.setValue(DIFFSPATIALDISTWEIGHT, 1); portBinaryParams.setLabel(ANGLEDIFFERENCEWEIGHT, "angleDifferenceWeight"); portBinaryParams.setValue(ANGLEDIFFERENCEWEIGHT, 1000); portGraphMatchingSubproblems.setLabel(0, "linear"); portGraphMatchingSubproblems.setValue(0, 0); portGraphMatchingSubproblems.setLabel(1, "maxFlow"); portGraphMatchingSubproblems.setValue(1, 0); portGraphMatchingSubproblems.setLabel(2, "local"); portGraphMatchingSubproblems.setValue(2, 1); portGraphMatchingSubproblems.setLabel(3, "tree"); portGraphMatchingSubproblems.setValue(3, 1); portActiveMatchingIterations.setLabel(0, "trafo"); portActiveMatchingIterations.setValue(0,3); portActiveMatchingIterations.setLabel(1, "modes"); portActiveMatchingIterations.setValue(1,3); portActiveMatchingIterations.setLabel(2, "cycles"); portActiveMatchingIterations.setValue(2,3); portActiveMatchingTrafo.setLabel(0, "rigid"); portActiveMatchingTrafo.setLabel(1, "scaled"); portActiveMatchingTrafo.setLabel(2, "affine"); portActiveMatchingTrafo.setValue(2); portActiveMatchingModes.setLabel(0, "start"); portActiveMatchingModes.setValue(0,5); portActiveMatchingModes.setLabel(1, "step"); portActiveMatchingModes.setValue(1,5); portActiveMatchingModes.setLabel(2, "stop"); portActiveMatchingModes.setValue(2,15); // portGroupingParams: max neigh dist (rel to wormLength); numGroups; minGroupSize; portGroupingParams.setLabel(0, "max neigh dist atlas"); portGroupingParams.setValue(0, 50); portGroupingParams.setLabel(1, "max neigh dist target"); portGroupingParams.setValue(1, 50); portGroupingParams.setLabel(2, "numGroups"); portGroupingParams.setValue(2, 10); portGroupingParams.setLabel(3, "minGroupSize"); portGroupingParams.setValue(3, 5); portGroupingParams.hide(); // portBestGroupTrafoParams: numTrafos, numAngles, 3x offset (symmetric), 3x offsetSampling portBestGroupTrafoParams.setLabel(0, "numTrafos"); portBestGroupTrafoParams.setValue(0, 10); portBestGroupTrafoParams.setLabel(1, "numAngles"); portBestGroupTrafoParams.setValue(1, 12); portBestGroupTrafoParams.setLabel(2, "offset xyz (rel to wormLength"); portBestGroupTrafoParams.setValue(2, 0.1); portBestGroupTrafoParams.setValue(3, 0.1); portBestGroupTrafoParams.setValue(4, 0.1); portBestGroupTrafoParams.setLabel(5, "offset sampling xyz"); portBestGroupTrafoParams.setValue(5, 10); portBestGroupTrafoParams.setValue(6, 10); portBestGroupTrafoParams.setValue(7, 10); portBestGroupTrafoParams.hide(); portRotInvariance.setLabel(0, "maxRotConsidered"); portRotInvariance.setValue(0, 0.3); portNorm.setLabel(0,"L1"); portNorm.setLabel(1,"L2"); portNorm.setValue(0); } /// destructor of surface displacement calculation HxWormAtlasReg::~HxWormAtlasReg (void) { } /// update: handles any changes of the user interface void HxWormAtlasReg::update (void) { // no need to recompute distance matrix etc in case portNorm changes -- or?? if (portData.source() && portData.isNew() ) { int nA=-1; if ( portData.source()->isOfType(HxSurface::getClassTypeId()) ) { HxSurface *atlasSurf = dynamic_cast<HxSurface *>(portData.source()); mAtlasCenterPoints = WormHelpers::extractPatchCenterPoints(atlasSurf); nA = mAtlasCenterPoints.size(); mAtlasColors = extractPatchColors(atlasSurf); portActiveMatchingIterations.hide(); portActiveMatchingTrafo.hide(); portActiveMatchingModes.hide(); } else if (portData.source()->isOfType(HxActiveShape::getClassTypeId())) { HxActiveShape *activeWorm = dynamic_cast<HxActiveShape *>(portData.source()); //mAtlasCenterPoints.resize(nA); //for ( int a=0; a<nA; a++ ) { // mAtlasCenterPoints[a].setValue(activeWorm->getPc().mMean[a*3+0],activeWorm->getPc().mMean[a*3+1],activeWorm->getPc().mMean[a*3+2]); //} activeWorm->createDisplay()->getTransformedPoints(mAtlasCenterPoints); nA = mAtlasCenterPoints.size(); mAtlasColors.resize(nA); mAtlasColors.fill(SbColor(0,0,0)); portActiveMatchingIterations.show(); portActiveMatchingTrafo.show(); portActiveMatchingModes.show(); } McHandle<HxSurface> dummyAtlasVertexSurf = new HxSurface(nA,0,0,1); dummyAtlasVertexSurf->points=mAtlasCenterPoints; McVec3f dvAxis, lrAxis; McVec3d extMin,extMax; WormHelpers::getWormCoordSystem(dummyAtlasVertexSurf,mAtlasCenter,mAtlasBodyAxis,dvAxis,lrAxis,extMin,extMax); mInvCovMatrices.resize(nA); mInvCovMatrices.fill(McMat3f::identity()); mInvCovDiffMatrices.resize(nA); for (int a=0; a<nA; a++) { mInvCovDiffMatrices[a].resize(nA); mInvCovDiffMatrices[a].fill(McMat3f::identity()); } mInvCovShapeMatrices.resize(nA); mInvCovShapeMatrices.fill(McMat3f::identity()); mMeanShapeVecs.resize(nA); mMeanShapeVecs.fill(McVec3f(0)); if ( portData.source()->isOfType(HxActiveShape::getClassTypeId()) ) { HxActiveShape *activeWorm = dynamic_cast<HxActiveShape *>(portData.source()); // fill cov. matrices of each v const McActiveComponents& pc = activeWorm->getPc(); int nT=pc.mData.size(); int nC=pc.mMean.size(); McDArray< McDArray <float> > coordsUT(nT); McDArray<float> filling(nC); coordsUT.fill(filling); for (int t=0; t<nT; t++) { pc.setWeights(coordsUT[t],pc.mData[t]); } McDArray< McDArray <float> > coords(nT); coords.fill(filling); //transform coords: SbMatrix trafo; activeWorm->getTransformRounded(trafo); #pragma omp parallel for for (int a=0; a<nA; a++) { for (int t=0; t<nT; t++) { trafo.multVecMatrix(*reinterpret_cast<SbVec3f*>(&(coordsUT[t][3*a])),*reinterpret_cast<SbVec3f*>(&(coords[t][3*a]))); } } McDArray< float > mean(nC); for (int c=0; c<nC; c++) { mean[c]=0; for (int t=0; t<nT; t++) { mean[c]+=coords[t][c]; } mean[c]/=nT; } #pragma omp parallel for for (int a=0; a<nA; a++) { McMat3f cov(0.); for (int d1=0; d1<3; d1++) { int idx1 = a*3+d1; for (int d2=0; d2<3; d2++) { int idx2 = a*3+d2; for (int t=0; t<nT; t++) { cov[d1][d2]+=(mean[idx1]-coords[t][idx1])*(mean[idx2]-coords[t][idx2]); } } } cov= cov/nT; mInvCovMatrices[a] = cov.inverse(); } // fill diff cov. matrices of each v-w // compute mean diff: McDArray< McDArray< McVec3f > > meanDiff(nA); meanDiff.fill( McDArray<McVec3f>(nA) ); #pragma omp parallel for for (int a=0; a<nA; a++) { for (int b=0; b<nA; b++) { meanDiff[a][b].setValue(0,0,0); for (int t=0; t<nT; t++) { for (int d=0; d<3; d++) { meanDiff[a][b][d]+= coords[t][a*3+d]-coords[t][b*3+d]; } } meanDiff[a][b]/=nT; } } #pragma omp parallel for for (int a=0; a<nA; a++) { for (int b=0; b<nA; b++) { McMat3f cov(0.); if (a==b) { mInvCovDiffMatrices[a][b]=cov; continue; } for (int d1=0; d1<3; d1++) { for (int d2=0; d2<3; d2++) { for (int t=0; t<nT; t++) { // d:=difference vector t,b - t,a. meanDiff[a][b] - d: d1st component * d2nd component. McVec3f diff (coords[t][a*3+0]-coords[t][b*3+0], coords[t][a*3+1]-coords[t][b*3+1], coords[t][a*3+2]-coords[t][b*3+2]); cov[d1][d2]+= (meanDiff[a][b][d1] - diff[d1] ) * (meanDiff[a][b][d2] - diff[d2] ); } } } cov= cov/nT; mInvCovDiffMatrices[a][b] = cov.inverse(); } } mAtlasProximityMatrix = computeAtlasProximityMatrix(); // fill individual nucleus shape means and cov. matrices //mInvCovShapeMatrices HxParamBundle* trainingRadiiBundle = activeWorm->parameters.bundle("TrainingRadii"); if (trainingRadiiBundle) { int nNuclei = trainingRadiiBundle->nBundles(); if (nA!=nNuclei) { theMsg->printf("warning: as has training radii but not the correct number. aborting."); return; } McDArray< McDArray<float> > trainingRadii(nNuclei); // for each nucleus, for (int n=0; n<nNuclei; n++) { // collect all radii McString trainingRadiiNString; McDArray< McString > trainingRadiiNStringList; trainingRadiiBundle->bundle(n)->print(trainingRadiiNString); char token = ' '; trainingRadiiNString.explode(token, trainingRadiiNStringList); trainingRadii[n].resize(0); for (int s=0; s<trainingRadiiNStringList.size(); s++) { McString testString = trainingRadiiNStringList[s]; char testChar = testString.first(); if (!testChar) continue; bool isFloat; float radius = trainingRadiiNStringList[s].toFloat(isFloat); if (isFloat) { trainingRadii[n].append(radius); } } } for (int n=0; n<nNuclei; n++) { mMeanShapeVecs[n]=McVec3f(0); int numTrainingRadii = trainingRadii[n].size()/3; for (int t=0; t<numTrainingRadii; t++) { mMeanShapeVecs[n].x+=trainingRadii[n][3*t+0]; mMeanShapeVecs[n].y+=trainingRadii[n][3*t+1]; mMeanShapeVecs[n].z+=trainingRadii[n][3*t+2]; } mMeanShapeVecs[n]/=numTrainingRadii; } #pragma omp parallel for for (int a=0; a<nA; a++) { int numTrainingRadii = trainingRadii[a].size()/3; McMat3f cov(0.); for (int d1=0; d1<3; d1++) { for (int d2=0; d2<3; d2++) { for (int t=0; t<numTrainingRadii; t++) { cov[d1][d2]+=(mMeanShapeVecs[a][d1]-trainingRadii[a][3*t+d1])*(mMeanShapeVecs[a][d2]-trainingRadii[a][3*t+d2]); } } } cov= cov/nT; mInvCovShapeMatrices[a] = cov.inverse(); } } } else if ( portData.source()->isOfType(HxSurface::getClassTypeId()) ) { //mInvCovMatrices are already set to identity(), see above. //diff cov. matrices: set to identity() above. fine for getLengthDiffAB; compute neigh proximity by euclidean distances mAtlasProximityMatrix = computeDistanceMatrix(mAtlasCenterPoints); } mAtlasProximitiesSorted.resize(mAtlasProximityMatrix.size()); for (int i=0; i<nA; i++) { mAtlasProximitiesSorted[i].resize(mAtlasProximityMatrix[i].size()); for (int j=0; j<mAtlasProximityMatrix[i].size(); j++) { mAtlasProximitiesSorted[i][j].dist = mAtlasProximityMatrix[i][j]; mAtlasProximitiesSorted[i][j].idx = j; } mAtlasProximitiesSorted[i].sort(WormHelpers::compareDistToIdx); } } HxSurface *targetSurf = dynamic_cast<HxSurface *>(portTargetSurface.source()); if (targetSurf && portTargetSurface.isNew()) { mTargetCenterPoints = WormHelpers::extractPatchCenterPoints(targetSurf); // mTargetDistMatrix = computeDistanceMatrix(mTargetCenterPoints); mTargetCenter.setValue(0,0,0); for (int i=0; i<mTargetCenterPoints.size(); i++) { mTargetCenter += mTargetCenterPoints[i]; } mTargetCenter/=(float)(mTargetCenterPoints.size()); mTargetColors = extractPatchColors(targetSurf); mTargetRadii = extractPatchRadii(targetSurf); } if ( portData.source() && ( portGraphMatching.isNew() || portColorParams.isNew() || portData.isNew() ) ) { int nA=mAtlasCenterPoints.size(); int maxNumNeighbors= (int)(portGraphMatching.getValue(MAXNUMNEIGHS)+0.5); mAtlasNeighs.resize(mAtlasProximityMatrix.size()); for (int i=0; i<nA; i++) { mAtlasNeighs[i].resize(maxNumNeighbors); int k=0; for (int j=1; j<nA && k<maxNumNeighbors; j++) { if (considerAtlasIdx(mAtlasProximitiesSorted[i][j].idx)) { mAtlasNeighs[i][k]=mAtlasProximitiesSorted[i][j].idx; k++; } } mAtlasNeighs[i].sort(mcStandardCompare); } } } /// the computational part of this module void HxWormAtlasReg::compute (void) { if (! portDoIt.wasHit()) return; // get connected surface // HxSurface *atlasSurf = dynamic_cast<HxSurface *>(portData.source()); HxSurface *targetSurf = dynamic_cast<HxSurface *>(portTargetSurface.source()); HxActiveShape *activeWorm = dynamic_cast<HxActiveShape *>(portData.source());//NULL in case it is a HxSurface. int maxIter = (int)(portGraphMatching.getValue(MAXITER)+0.5); float maxGap = portGraphMatching.getValue(MAXGAP); // surfaceVectorField must be connected to continue if (!targetSurf) { theMsg->printf("missing input: "); if (!targetSurf) theMsg->printf("missing input: targetSurf"); return; } theWorkArea->startWorking("computing GraphMatching..."); // compute patch (or point) correspondences: // computeCorrespondingNuclei(atlasSurf, targetSurf); int nA=mAtlasCenterPoints.size(); int numCycles = 1; int numTrafoIterations =1; int numModeIterations = 0; int trafoType=0; int numModesStart=0; int numModesStep=1; int numModesStop=0; if (portData.source()->isOfType(HxActiveShape::getClassTypeId())) { numTrafoIterations = portActiveMatchingIterations.getValue(0); numModeIterations = portActiveMatchingIterations.getValue(1); numCycles = portActiveMatchingIterations.getValue(2); trafoType = portActiveMatchingTrafo.getValue(); numModesStart = portActiveMatchingModes.getValue(0); numModesStep = portActiveMatchingModes.getValue(1); numModesStop = portActiveMatchingModes.getValue(2); } int* atlasAssignments; float* w; SbMatrix trafo; SbMatrix trafoInverse; float z; for (int numModes = numModesStart; numModes<=numModesStop; numModes=(numModes==numModesStop)?(numModes+1):std::min(numModes+numModesStep,numModesStop) ) { for (int cycle=0; cycle<numCycles; cycle++) { for (int trafoIter=0; trafoIter<numTrafoIterations; trafoIter++) { theMsg->printf("numModes %d/%d, cycle %d/%d, trafo iteration %d/%d",numModes, numModesStop, cycle, numCycles, trafoIter, numTrafoIterations); GraphMatching* m = setupGraphMatching(); int localNeighs = (int)(portGraphMatching.getValue(LOCALNEIGHS)+0.5); if (portGraphMatchingSubproblems.getValue(0)) m->AddLinearSubproblem(); if (portGraphMatchingSubproblems.getValue(1)) m->AddMaxflowSubproblem(); if (portGraphMatchingSubproblems.getValue(2)) m->AddLocalSubproblems(localNeighs); if (portGraphMatchingSubproblems.getValue(3)) m->AddTreeSubproblems(); z=m->SolveDD(maxIter, maxGap); atlasAssignments = m->GetSolution();// of size atlasSurf->patches.size(); w = m->GetWeights(); if ( !( portData.source()->isOfType(HxActiveShape::getClassTypeId()) ) ) break; // project activeWorm onto target: trafo and/or modes! // update trafo: activeWorm->getTransformRounded(trafo); trafoInverse = trafo.inverse(); McDArray<McVec3f> displ(nA); displ.fill(McVec3f(0,0,0)); #pragma omp parallel for for (int a=0; a<nA; a++){ if (atlasAssignments[a]<0) continue; trafoInverse.multDirMatrix(*reinterpret_cast<SbVec3f*>(&(mTargetCenterPoints[atlasAssignments[a]]-mAtlasCenterPoints[a])), *reinterpret_cast<SbVec3f*>(&(displ[a]))); } McDArray<float> dummyW(0); dummyW.append(nA, w); activeWorm->updateTransformation(displ, dummyW, trafoType); activeWorm->touch(HxData::NEW_DATA); activeWorm->fire(); activeWorm->createDisplay()->getTransformedPoints(mAtlasCenterPoints); // update view: theController->render(); int debugCorrect=0; int unmatched=0; for (int i=0; i<nA; i++) { if (i==atlasAssignments[i]) debugCorrect++; if (atlasAssignments[i]<0) unmatched++; } theMsg->printf("unmatched %d of %d",unmatched,nA); theMsg->printf("correct in case of corresponding patch numbers: %d",debugCorrect); } for (int modeIter=0; modeIter<numModeIterations; modeIter++) { theMsg->printf("numModes %d/%d, cycle %d/%d, mode iteration %d/%d",numModes, numModesStop,cycle, numCycles, modeIter, numModeIterations); GraphMatching* m = setupGraphMatching(); int localNeighs = (int)(portGraphMatching.getValue(LOCALNEIGHS)+0.5); if (portGraphMatchingSubproblems.getValue(0)) m->AddLinearSubproblem(); if (portGraphMatchingSubproblems.getValue(1)) m->AddMaxflowSubproblem(); if (portGraphMatchingSubproblems.getValue(2)) m->AddLocalSubproblems(localNeighs); if (portGraphMatchingSubproblems.getValue(3)) m->AddTreeSubproblems(); float z=m->SolveDD(maxIter, maxGap); atlasAssignments = m->GetSolution();// of size atlasSurf->patches.size(); w = m->GetWeights(); // update modes: activeWorm->getTransformRounded(trafo); trafoInverse = trafo.inverse(); McDArray<float> displacements(3*nA); McDArray<float> weights(3*nA); displacements.fill(0); weights.fill(0); McDArray<McVec3f> displ(nA); displ.fill(McVec3f(0,0,0)); #pragma omp parallel for for (int a=0; a<nA; a++){ if (atlasAssignments[a]<0) continue; trafoInverse.multDirMatrix(*reinterpret_cast<SbVec3f*>(&(mTargetCenterPoints[atlasAssignments[a]]-mAtlasCenterPoints[a])), *reinterpret_cast<SbVec3f*>(&(displ[a]))); weights[3*a]=w[a]; weights[3*a+1]=w[a]; weights[3*a+2]=w[a]; } int nCoords=3*nA; memcpy(displacements.dataPtr(), displ.dataPtr(), nCoords*sizeof(float)); activeWorm->computeShapeWeights(displacements, weights, numModes); activeWorm->touch(HxData::NEW_DATA); activeWorm->fire(); activeWorm->createDisplay()->getTransformedPoints(mAtlasCenterPoints); // update view: theController->render(); // debug output: int debugCorrect=0; int unmatched=0; for (int i=0; i<nA; i++) { if (i==atlasAssignments[i]) debugCorrect++; if (atlasAssignments[i]<0) unmatched++; } theMsg->printf("unmatched %d of %d",unmatched,nA); theMsg->printf("correct in case of corresponding patch numbers: %d",debugCorrect); } } } // prepare visualization of resulting matching: HxLineSet* result = dynamic_cast<HxLineSet *>(getResult()); if (result) { result->clear(); } else { result=new HxLineSet(); } McDArray<McVec3f> points(0); points.appendArray(mAtlasCenterPoints); points.appendArray(mTargetCenterPoints); result->addPoints(points,points.size()); for (int i=0; i<nA; i++) { if (atlasAssignments[i]>-1) { int line[2] = {i, nA+atlasAssignments[i]}; result->addLine(2,line); } } theMsg->printf("z: %f",z); int unmatched=0; int debugCorrect=0; for (int i=0; i<nA; i++) { // theMsg->printf("atlas %d --> target %d",i,atlasAssignments[i]); if (i==atlasAssignments[i]) debugCorrect++; if (atlasAssignments[i]<0) { unmatched++; } } // adjust mAtlasCenterPoints in result linesets: HxLineSet* atlasNeighLineset = dynamic_cast<HxLineSet *>(getResult(1)); HxLineSet* assignmentLineset = dynamic_cast<HxLineSet *>(getResult(3)); for (int i=0; i<nA; i++) { atlasNeighLineset->points[i]=mAtlasCenterPoints[i]; assignmentLineset->points[i]=mAtlasCenterPoints[i]; } /* for (int i=0; i<nA; i++) { theMsg->printf("atlas %d --> target %d weight %f",i,atlasAssignments[i],w[i]); }*/ theMsg->printf("unmatched %d of %d",unmatched,nA); theMsg->printf("correct in case of corresponding patch numbers: %d",debugCorrect); setResult(result); theWorkArea->stopWorking(); } GraphMatching* HxWormAtlasReg::setupGraphMatching() { HxLineSet* atlasNeighLineset = dynamic_cast<HxLineSet *>(getResult(1)); HxLineSet* targetNeighLineset = dynamic_cast<HxLineSet *>(getResult(2)); HxLineSet* assignmentLineset = dynamic_cast<HxLineSet *>(getResult(3)); bool verbose=true; if (verbose) { //prepare debug linesets: atlas, target, atlas->target if (atlasNeighLineset) { atlasNeighLineset->clear(); } else { atlasNeighLineset=new HxLineSet(); atlasNeighLineset->setLabel("AtlasNeighLineset"); } if (targetNeighLineset) { targetNeighLineset->clear(); } else { targetNeighLineset=new HxLineSet(); targetNeighLineset->setLabel("TargetNeighLineset"); } if (assignmentLineset) { assignmentLineset->clear(); } else { assignmentLineset=new HxLineSet(); assignmentLineset->setLabel("AssignmentLineset"); } setResult(1,atlasNeighLineset); setResult(2,targetNeighLineset); setResult(3,assignmentLineset); int nA=mAtlasCenterPoints.size(); int nT=mTargetCenterPoints.size(); atlasNeighLineset->addPoints(mAtlasCenterPoints,nA); targetNeighLineset->addPoints(mTargetCenterPoints,nT); McDArray<McVec3f> assignmentLinesetPoints(0); assignmentLinesetPoints.append(nA,mAtlasCenterPoints); assignmentLinesetPoints.append(nT,mTargetCenterPoints); assignmentLineset->addPoints(assignmentLinesetPoints,nA+nT); } // ToDo: tune/learn... //unary weights: float lSpatialDist=portSpatialDistParams.getValue(SPATIALDISTWEIGHT); float lShapeDist=portShapeParams.getValue(SHAPEDISTWEIGHT); float lTargetCost=portTargetCostParams.getValue(TARGETCOSTWEIGHT); float lIncentive=portIncentiveToMatch.getValue(INCENTIVETOMATCH); float lColor = portColorParams.getValue(COLORDISTWEIGHT); //binary weights: float lDiffSpatialDist=portBinaryParams.getValue(DIFFSPATIALDISTWEIGHT); float lAngleDiff=portBinaryParams.getValue(ANGLEDIFFERENCEWEIGHT); int nA=mAtlasCenterPoints.size(); int nT=mTargetCenterPoints.size(); McDArray<Assignment> assignments(0); McDArray<Edge> edges(0); #pragma omp parallel for for (int atlasIdx=0; atlasIdx<nA; atlasIdx++) { if (!considerAtlasIdx(atlasIdx)) continue; for (int targetIdx=0; targetIdx<nT; targetIdx++) { if (!considerTargetIdx(targetIdx)) continue; if (!considerAssignment(atlasIdx,targetIdx)) continue; McVec2f spatialDistanceAtAngle = getSpatialDistance(atlasIdx,targetIdx); float spatialDistance = spatialDistanceAtAngle[0]; float angle = spatialDistanceAtAngle[1]; float colorDistance = getColorDistance(atlasIdx,targetIdx); float shapeDistance = getShapeDistance(atlasIdx,targetIdx); float targetCost = getTargetCost(targetIdx); float incentiveToMatch = getIncentiveToMatch(atlasIdx); float cost = lSpatialDist*spatialDistance+lShapeDist*shapeDistance+lTargetCost*targetCost+lIncentive*incentiveToMatch; Assignment assignat; assignat.i0=atlasIdx; assignat.i1=targetIdx; assignat.cost=cost; assignat.angle=angle; #pragma omp critical { assignments.append(assignat); if (verbose) { // add line in lineset atlas->target int line[2] = {atlasIdx, nA+targetIdx}; assignmentLineset->addLine(2,line); } } } } int numAssignments = assignments.size(); // #pragma omp parallel for for (int a=0; a<numAssignments; a++) { for (int b=a+1; b<numAssignments; b++) { int atlasIdx0=assignments[a].i0; int atlasIdx1=assignments[b].i0; if (!areNeighborsInAtlas(atlasIdx0,atlasIdx1)) { continue; } int targetIdx0=assignments[a].i1; int targetIdx1=assignments[b].i1; float diffSpatialDistance=getDifferenceOfSpatialDistances(assignments[a],assignments[b]); float angleDifference=(assignments[a].angle-assignments[b].angle)*(assignments[a].angle-assignments[b].angle); float cost = lDiffSpatialDist*diffSpatialDistance + lAngleDiff*angleDifference; Edge e; e.a=a; e.b=b; e.cost=cost; // #pragma omp critical { edges.append(e); if (verbose) { // add line in atlas neighbor graph int lineA[2] = {atlasIdx0, atlasIdx1}; atlasNeighLineset->addLine(2,lineA); // add line in target neighbor graph int lineT[2] = {targetIdx0, targetIdx1}; targetNeighLineset->addLine(2,lineT); } } } } int numEdges = edges.size(); GraphMatching* m = new GraphMatching(nA,nT,numAssignments,numEdges); // fill in assignments: for (int a=0; a<numAssignments; a++) { m->AddAssignment(assignments[a].i0, assignments[a].i1, assignments[a].cost); } for (int e=0; e<numEdges; e++) { m->AddEdge(edges[e].a, edges[e].b, edges[e].cost); } m->ConstructNeighbors(0); m->options.verbose=1; return m; } McVec2f HxWormAtlasReg::getSpatialDistance(int atlasIdx,int targetIdx) { float maxAngleBetweenMatchedNuclei = portRotInvariance.getValue(0); if (maxAngleBetweenMatchedNuclei > 0 ) { McVec3f relAtlasPoint = mAtlasCenterPoints[atlasIdx]-mAtlasCenter; McVec3f relTargetPoint = mTargetCenterPoints[targetIdx]-mAtlasCenter; // angle between (atlasPoint-mAtlasCenter) and (targetPoint-mAtlasCenter) around mAtlasBodyAxis: // subtract body axis part McVec3f orthoAtlasPoint = relAtlasPoint - mAtlasBodyAxis.dot(relAtlasPoint)*mAtlasBodyAxis; McVec3f orthoTargetPoint = relTargetPoint - mAtlasBodyAxis.dot(relTargetPoint)*mAtlasBodyAxis; // normalize orthoAtlasPoint.normalize(); orthoTargetPoint.normalize(); float absAngle = std::acos(orthoAtlasPoint.dot(orthoTargetPoint)); float restrictedAbsAngle = (absAngle>0)?(std::min(maxAngleBetweenMatchedNuclei,absAngle)):(std::max(-maxAngleBetweenMatchedNuclei,absAngle)); McVec3f dummyDir = mAtlasBodyAxis.cross(orthoTargetPoint); float sign = orthoAtlasPoint.dot(dummyDir)>0?1:-1;// want to rotate target onto atlas // left or right? (sign of angle) float angle=restrictedAbsAngle*sign; McRotation rot(mAtlasBodyAxis,angle); // debug: check1 is correct (=orthoAtlasPoint) /* McVec3f check1, check2; rot.multVec(orthoTargetPoint, check1); McRotation checkRot2(mAtlasBodyAxis,-angle); checkRot2.multVec(orthoTargetPoint, check2);*/ McVec3f rotatedRelTargetPoint; rot.multVec(relTargetPoint,rotatedRelTargetPoint); McVec3f rotatedTargetPoint = rotatedRelTargetPoint + mAtlasCenter; McVec3f offset = rotatedTargetPoint- mAtlasCenterPoints[atlasIdx]; return McVec2f(getLengthA(offset, atlasIdx),angle); } McVec3f offset(mTargetCenterPoints[targetIdx]-mAtlasCenterPoints[atlasIdx]); return McVec2f(getLengthA(offset, atlasIdx),0); } McDArray<SbColor> HxWormAtlasReg::extractPatchColors(HxSurface * surf) { int nP = surf->patches.size(); McDArray<SbColor> colArray(nP); colArray.fill(SbColor(0,0,0)); for (int p=0; p<nP; p++) { HxParamBundle* bundle1 = surf->parameters.materials()->bundle(p+1); if (!bundle1) continue; bundle1->findColor(&(colArray[p])[0]); } return colArray; } McDArray<McVec3f> HxWormAtlasReg::extractPatchRadii(HxSurface * surf) { int nP = surf->patches.size(); McDArray<McVec3f> radii(nP); radii.fill(McVec3f(0,0,0)); for (int p=0; p<nP; p++) { HxParamBundle* bundle1 = surf->parameters.materials()->bundle(p+1); if (!bundle1) continue; double values[3]; HxParameter* radiiParam = bundle1->find("Radii"); if (!radiiParam) continue; radiiParam->getReal(values); radii[p].x=values[0]; radii[p].y=values[1]; radii[p].z=values[2]; } return radii; } float HxWormAtlasReg::getColorDistance(int atlasIdx,int targetIdx) { return (mAtlasColors[atlasIdx]-mTargetColors[targetIdx]).length(); } float HxWormAtlasReg::getDifferenceOfSpatialDistances(Assignment a, Assignment b) { int atlasIdx0=a.i0; int atlasIdx1=b.i0; int targetIdx0=a.i1; int targetIdx1=b.i1; float angle0=a.angle; float angle1=b.angle; McVec3f atlasDiff= mAtlasCenterPoints[atlasIdx1]-mAtlasCenterPoints[atlasIdx0]; McVec3f targetDiff= mTargetCenterPoints[targetIdx1]-mTargetCenterPoints[targetIdx0]; // todo: what is the correct distribution assuming no correlation / correlation between a0, a1? float maxAngleBetweenMatchedNuclei = portRotInvariance.getValue(0); if (maxAngleBetweenMatchedNuclei > 0 ) { // target diff: // rotate target points around atlas body axis by their angles McVec3f relTargetPoint0 = mTargetCenterPoints[targetIdx0]-mAtlasCenter; McRotation rot0(mAtlasBodyAxis,angle0); McVec3f rotatedRelTargetPoint0; rot0.multVec(relTargetPoint0,rotatedRelTargetPoint0); McVec3f rotatedTargetPoint0 = rotatedRelTargetPoint0 + mAtlasCenter; McVec3f relTargetPoint1 = mTargetCenterPoints[targetIdx1]-mAtlasCenter; McRotation rot1(mAtlasBodyAxis,angle1); McVec3f rotatedRelTargetPoint1; rot1.multVec(relTargetPoint1,rotatedRelTargetPoint1); McVec3f rotatedTargetPoint1 = rotatedRelTargetPoint1 + mAtlasCenter; targetDiff= rotatedTargetPoint1-rotatedTargetPoint0; } McVec3f offset = atlasDiff-targetDiff; return getLengthDiffAB(offset, atlasIdx0, atlasIdx1); } float HxWormAtlasReg::getShapeDistance(int atlasIdx,int targetIdx) { //ToDo: dist of nuclei radii. makes sense if atlas nuclei have shapes other than spheres. McVec3f meanRadii = mMeanShapeVecs[atlasIdx]; McMat3f invShapeCov = mInvCovShapeMatrices[atlasIdx]; McVec3f targetRadii = mTargetRadii[targetIdx]; McVec3f offset = targetRadii-meanRadii; McVec3f dummy; invShapeCov.multMatrixVec(offset,dummy); float ret = offset.dot(dummy); int norm = portNorm.getValue(); if (norm==L1) { return std::sqrt(ret); } else if (norm==L2) { return ret; } } float HxWormAtlasReg::getTargetCost(int targetIdx) { HxSurface *targetSurf = dynamic_cast<HxSurface *>(portTargetSurface.source()); //get "Fit" parameter. if not there, return 0. HxParamBundle* materials = targetSurf->parameters.materials(); HxParamBundle* myMaterial = materials->bundle(targetIdx+1); if (myMaterial) { HxParameter* myFit = myMaterial->find("Fit"); if (myFit) { return -1 * myFit->getReal(); } } return 0; } float HxWormAtlasReg::getIncentiveToMatch(int atlasIdx) { //toDo: depend on atlasIdx? return -1; } bool HxWormAtlasReg::areNeighborsInAtlas(int atlasIdx0,int atlasIdx1) { if (atlasIdx0 == atlasIdx1) return false; if (mAtlasNeighs[atlasIdx0].findSorted(atlasIdx1,mcStandardCompare)>-1 || mAtlasNeighs[atlasIdx1].findSorted(atlasIdx0,mcStandardCompare)>-1) { return true; } else { return false; } } bool HxWormAtlasReg::isConnected(GraphType* graph) { return false; } void HxWormAtlasReg::computeBestTrafos(McDArray<McVec3f> &atlasGroupPoints, McVec3f atlasGroupAxis, float atlasWormLength, McDArray<McVec3f> &targetGroupPoints, McVec3f targetGroupAxis, float targetWormLength, int numTrafos, int numAngles, float* offsetRange, int* offsetSampling, McDArray<TrafoType> &resultTrafos, McDArray<float>& resultTrafoResiduals) { TrafoType startTrafo = computeStartTrafo(atlasGroupPoints, atlasGroupAxis, atlasWormLength, targetGroupPoints, targetGroupAxis, targetWormLength); //scale, match center of mass, and align axes // align axes' directions; scale by ratio of worm lengths // translation and rotation around axis (4 params): initial transforms = discrete sampling of 4-dim space (exhaustive search), ICP for best x initial transforms // result: set of candidate transformations for each atlas group. each one has cost, namely residual vertex distance to target. resultTrafos.resize(0); resultTrafos.append(startTrafo); } McDArray<McDArray<float>> HxWormAtlasReg::computeDistanceMatrix(McDArray<McVec3f> &centerPoints) { int numPoints = centerPoints.size(); McDArray<McDArray<float>> distMatrix(numPoints); // init with 0 McDArray<float> filling(numPoints); filling.fill(0); distMatrix.fill(filling); McVec3f* coords = centerPoints.dataPtr(); #pragma omp parallel for for (int i=0; i<numPoints; i++) { McVec3f point1 = coords[i]; for (int j=0; j<i; j++) { //compute distance McVec3f point2 = coords[j]; distMatrix[i][j]=getLengthA(point2-point1, i); distMatrix[j][i]=getLengthA(point1-point2, j); } } return distMatrix; } McDArray<McDArray<float>> HxWormAtlasReg::computeAtlasProximityMatrix() { int numPoints = mInvCovDiffMatrices.size(); McDArray<McDArray<float>> distMatrix(numPoints); // init with 0 McDArray<float> filling(numPoints); filling.fill(0); distMatrix.fill(filling); #pragma omp parallel for for (int a=0; a<numPoints; a++) { for (int b=0; b<a; b++) { //compute distance float proximity = 1/std::sqrt(mInvCovDiffMatrices[a][b].det()); distMatrix[a][b]=proximity; distMatrix[b][a]=proximity; } } return distMatrix; } HxWormAtlasReg::TrafoType HxWormAtlasReg::computeStartTrafo(McDArray<McVec3f> &atlasGroupPoints, McVec3f atlasGroupAxis, float atlasWormLength, McDArray<McVec3f> &targetGroupPoints, McVec3f targetGroupAxis, float targetWormLength) { float s= targetWormLength/atlasWormLength; SbVec3f scale(s,s,s); SbRotation rot(atlasGroupAxis,targetGroupAxis); McVec3f atlasGroupCenter(0); for (int i=0; i<atlasGroupPoints.size(); i++) { atlasGroupCenter += atlasGroupPoints[i]; } atlasGroupCenter /= atlasGroupPoints.size(); McVec3f targetGroupCenter(0); for (int i=0; i<targetGroupPoints.size(); i++) { targetGroupCenter += targetGroupPoints[i]; } targetGroupCenter /= targetGroupPoints.size(); McVec3f offset = targetGroupCenter-atlasGroupCenter; TrafoType startTrafo; startTrafo.makeIdentity(); startTrafo.setTransform(offset,rot,scale,SbRotation(0,0,0,0),atlasGroupCenter); return startTrafo; } HxWormAtlasReg::GraphType* HxWormAtlasReg::buildTrafoGraph(McDArray<McDArray<TrafoType>> bestGroupTrafos) { GraphType* trafoGraph; return trafoGraph; } McVec3f HxWormAtlasReg::computeGroupAxis(McDArray<int> group, McDArray<McVec3f>& centerPoints, std::vector<float> &d_vec) { McVec3f groupAxis(0); //find direction of maximum ascent //given: samples (x,y,z)->d //model: d=ax + by + cz + o //lse with 4 unknowns (a) and more equations: X*a = d -> overdetermined system // a= (Xt X)^-1 Xt d // Use double precision for this computation int dim=4; int numPoints=group.size(); McDMatrix<double> X(numPoints,dim); X.fill(1); McVec3f* coords = centerPoints.dataPtr(); // Setup lhs matrix for (int i=0; i<numPoints; i++){ int pIdx = group[i]; for (int j=0; j<dim-1; j++) { X(i,j) = coords[pIdx][j]; } } McDMatrix<double> A(dim,dim); McDMatrix<double> Xt = X; Xt.transpose(); A = Xt*X; double* dbb = (double*) mcmalloc(dim*sizeof(double)); memset(dbb, 0, dim*sizeof(double)); // Setup rhs vector for (int i=0; i<dim; i++) { for (int k=0; k<numPoints; k++){ int pIdx = group[k]; dbb[i] += Xt(i,k) * d_vec[pIdx]; } } int ret = A.solveLRdecomp(&dbb,1); for (int i=0; i<dim-1; i++) { groupAxis[i]=dbb[i]; } return groupAxis; } McDArray<McVec3f> HxWormAtlasReg::extractGroupPoints(McDArray<int> group, McDArray<McVec3f> &centerPoints) { McVec3f* coords = centerPoints.dataPtr(); McDArray<McVec3f> groupPoints(group.size()); for (int i=0; i<group.size(); i++){ groupPoints[i]=coords[group[i]]; } return groupPoints; } HxWormAtlasReg::GraphType* HxWormAtlasReg::buildWormGraph(McDArray< McDArray<float> > & distMatrix, float maxNeighDist) { int numPoints=distMatrix.size(); int edgeCount=0; typedef std::pair<int, int> Edge; const int maxNumEdges = numPoints*numPoints; Edge* edges = new Edge[maxNumEdges]; int* weight = new int[maxNumEdges]; for (int i=0; i<numPoints; i++) { for (int j=0; j<i; j++) { float dist = distMatrix[i][j]; if (dist<maxNeighDist) { //add edge i-j edges[edgeCount]=Edge(i,j); weight[edgeCount]=dist; edgeCount++; //add edge j-i edges[edgeCount]=Edge(j,i); weight[edgeCount]=dist; edgeCount++; } } } GraphType* wormGraph = new GraphType(numPoints); typedef graph_traits < GraphType >::edge_descriptor edge_descriptor; property_map<GraphType, edge_weight_t>::type weightmap = get(edge_weight, *wormGraph); for (int j = 0; j < edgeCount; ++j) { edge_descriptor e; bool inserted; tie(e, inserted) = add_edge(edges[j].first, edges[j].second, *wormGraph); weightmap[e] = weight[j]; } return wormGraph; } std::vector<float>* HxWormAtlasReg::computeWormDistanceMap(int startIdx, GraphType* wormGraph) { typedef graph_traits < GraphType >::vertex_descriptor vertex_descriptor; int numNodes = num_vertices(*wormGraph); std::vector<vertex_descriptor> p_vec(numNodes); std::vector<float>* d_vec = new std::vector<float>(numNodes); vertex_descriptor s = vertex(startIdx, *wormGraph); property_map<GraphType, vertex_index_t>::type indexmap = get(vertex_index, *wormGraph); property_map<GraphType, edge_weight_t>::type weightmap = get(edge_weight, *wormGraph); dijkstra_shortest_paths(*wormGraph, s, &p_vec[0], &(*d_vec)[0], weightmap, indexmap, std::less<float>(), closed_plus<float>(), (std::numeric_limits<float>::max)(), 0, default_dijkstra_visitor()); return d_vec; } float HxWormAtlasReg::computeWormLength(std::vector<float> &d_vec) { int numNodes = d_vec.size(); float wormLength = 0; for (int i=0; i<numNodes; i++) { float length = d_vec[i]; if (length>wormLength){ wormLength=length; } } return wormLength; }; McDArray<McDArray<int>> HxWormAtlasReg::groupNuclei(std::vector<float> &d_vec, float distThresh) { int numGroups = portGroupingParams.getValue(2); McDArray<McDArray<int>> groups(numGroups); McDArray<int> filling(0); groups.fill(filling); int numNodes = d_vec.size(); for (int i=0; i<numNodes; i++) { float dist = d_vec[i]; int groupIdx = std::min((int)(dist/distThresh), numGroups-1); groups[groupIdx].append(i); } // start vertex a0, or rather start set aCurr=aDone={a0} // compute distance to aDone for all vertices in {all}\aDone // aNext = set of vertices in {all}\aDone with distance below group distance thresh and at least the closest 5; if closest five above thresh, reduce thresh for next time // aDone u= aNext; loop until aDone==all // beware! does not work properly if start vertex is not at end of worm. // should work on graph built before for assessing worm length! //need distance map! return groups; } McDArray<McDArray<float>> HxWormAtlasReg::computeCorrespondingNuclei(HxSurface * atlasSurf, HxSurface * targetSurf) { // check if atlas/target is given as center points or as patches: unusedPoints?centerPoints:patches // if patches, extract centers. McDArray<McVec3f> atlasCenterPoints = WormHelpers::extractPatchCenterPoints(atlasSurf); McDArray<McVec3f> targetCenterPoints = WormHelpers::extractPatchCenterPoints(targetSurf); // compute nucleus distance matrix: 2d array, numVertices x numVertices, for atlas (and target) McDArray<McDArray<float>> atlasDistMatrix = computeDistanceMatrix(atlasCenterPoints); McDArray<McDArray<float>> targetDistMatrix = computeDistanceMatrix(targetCenterPoints); int atlasStartIdx = portInit.getValue(0); int targetStartIdx = portInit.getValue(1); // compute worm length: assume init vertex to be at one end; // graph; connect each vertex to all others within distance thresh (max distance of what are to be considered "neighbors"); float atlasMaxNeighDist = portGroupingParams.getValue(0); GraphType* atlasWormGraph = buildWormGraph(atlasDistMatrix,atlasMaxNeighDist); std::vector<float>* atlasDistVec = computeWormDistanceMap(atlasStartIdx, atlasWormGraph); // longest shortest path ends at other end and gives worm length! (apart from slight inaccuracies due to worm bending, which causes path to not run through center of worm) float atlasWormLength = computeWormLength(*atlasDistVec); // group atlas vertices: int numGroups = portGroupingParams.getValue(2); //max neigh dist; numGroups; minGroupSize; float atlasDistThresh = atlasWormLength/numGroups; McDArray<McDArray<int>> atlasGroups = groupNuclei(*atlasDistVec, atlasDistThresh); // group target vertices: same procedure; should end up with same number of groups float targetMaxNeighDist = portGroupingParams.getValue(1); GraphType* targetWormGraph = buildWormGraph(targetDistMatrix,targetMaxNeighDist); std::vector<float>* targetDistVec = computeWormDistanceMap(targetStartIdx, targetWormGraph); // longest shortest path ends at other end and gives worm length! (apart from slight inaccuracies due to worm bending, which causes path to not run through center of worm) float targetWormLength = computeWormLength(*targetDistVec); float targetDistThresh = targetWormLength/numGroups; McDArray<McDArray<int>> targetGroups = groupNuclei(*targetDistVec, targetDistThresh); // todo: debug output! length, groups int numTrafos = portBestGroupTrafoParams.getValue(0); int numAngles = portBestGroupTrafoParams.getValue(1); float offset[3]; offset[0] = portBestGroupTrafoParams.getValue(2); offset[1] = portBestGroupTrafoParams.getValue(3); offset[2] = portBestGroupTrafoParams.getValue(4); int offsetSampling[3]; offsetSampling[0] = portBestGroupTrafoParams.getValue(5); offsetSampling[1] = portBestGroupTrafoParams.getValue(6); offsetSampling[2] = portBestGroupTrafoParams.getValue(7); // for each pair of corresponding groups, McDArray<McDArray<TrafoType>> bestGroupTrafos(numGroups); McDArray<McDArray<float>> bestGroupTrafoResiduals(numGroups); for (int g=0; g<numGroups; g++) { McDArray<McVec3f> atlasGroupPoints = extractGroupPoints(atlasGroups[g],atlasCenterPoints); McVec3f atlasGroupAxis = computeGroupAxis(atlasGroups[g],atlasCenterPoints,*atlasDistVec); McDArray<McVec3f> targetGroupPoints = extractGroupPoints(targetGroups[g],targetCenterPoints); McVec3f targetGroupAxis = computeGroupAxis(targetGroups[g],targetCenterPoints,*targetDistVec); computeBestTrafos(atlasGroupPoints, atlasGroupAxis, atlasWormLength, targetGroupPoints, targetGroupAxis, targetWormLength, numTrafos, numAngles, offset, offsetSampling, bestGroupTrafos[g], bestGroupTrafoResiduals[g]); HxSurface* dummy = new HxSurface(atlasGroupPoints.size(),0,0,1); dummy->points=atlasGroupPoints; theObjectPool->addObject(dummy); dummy->setTransform(bestGroupTrafos[g][0]); HxSurface* dummy2 = new HxSurface(targetGroupPoints.size(),0,0,1); dummy2->points=targetGroupPoints; theObjectPool->addObject(dummy2); } return atlasDistMatrix; // build graph from candidate group transformations: connect trafos in neighboring groups only if difference Tnext*Tcurr^-1 is "small" (simplest: 5 smallest angle differences) GraphType* trafoGraph = buildTrafoGraph(bestGroupTrafos); // Dijkstra -> cheapest sequence of trafos computeBestTrafoSequence(trafoGraph); // correspondences as in evaluation!? (dist thresh instead of center check)?? // output: for each targetSurf patch/point, corresponding atlasSurf patch/point (or -1 if no corresp found) // rather output probabilities? for each targetSurf patch/point, for each atlasSurf patch/point, probability of corresp int dimAtlas = atlasCenterPoints.size(); int dimTarget = targetCenterPoints.size(); McDArray<McDArray<float>> correspMatrix(dimTarget); McDArray<float> filling(dimAtlas); filling.fill(0); correspMatrix.fill(filling); return correspMatrix; } int HxWormAtlasReg::parse(Tcl_Interp* t, int argc, char **argv) { char *cmd = argv[1]; if (CMD("getCovMatrix")) { if (argc != 3) { theMsg->printf("Usage: getCovMatrix <atlasIdx>"); return TCL_OK; } int atlasIdx = atoi(argv[2]); if (atlasIdx>-1 && atlasIdx<mInvCovMatrices.size() ) { McMat3f cov = mInvCovMatrices[atlasIdx].inverse(); for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) Tcl_VaAppendElement(t,"%g",cov[i][j]); } } else return HxCompModule::parse(t, argc, argv); return TCL_OK; }
9288e8d7a8fe2815dbf117a5b26c8ce7ca82ac84
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/xtp/Samples/UserInterface/GUI_Office11/chicdial.h
e68d697711e89ba62e7af20599545bb911b35b7d
[]
no_license
UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559378
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
UTF-8
C++
false
false
2,470
h
// chicdial.h : header file // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // [email protected] // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CCSDialog dialog class CCSDialog : public CDialog { // Construction public: CCSDialog(); CCSDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); CCSDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL); // Implementation protected: virtual const DWORD* GetHelpIDs() = 0; // Generated message map functions //{{AFX_MSG(CCSDialog) virtual BOOL OnInitDialog(); //}}AFX_MSG afx_msg LRESULT OnHelp(WPARAM, LPARAM lParam); afx_msg LRESULT OnHelpContextMenu(WPARAM, LPARAM lParam); DECLARE_MESSAGE_MAP() }; class CCSPropertyPage : public CPropertyPage { // Construction public: CCSPropertyPage(UINT nIDTemplate, UINT nIDCaption = 0); CCSPropertyPage(LPCTSTR lpszTemplateName, UINT nIDCaption = 0); // Implementation protected: virtual const DWORD* GetHelpIDs() = 0; // Generated message map functions //{{AFX_MSG(CCSPropertyPage) //}}AFX_MSG afx_msg LRESULT OnHelp(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnHelpContextMenu(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; class CCSPropertySheet : public CPropertySheet { // Construction public: CCSPropertySheet(UINT nIDCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0); CCSPropertySheet(LPCTSTR pszCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0); // Implementation protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Generated message map functions //{{AFX_MSG(CCSPropertySheet) //}}AFX_MSG afx_msg LRESULT OnHelp(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnHelpContextMenu(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() };
fe9fc87950dd6085c9023bc2053339dd29d64c9b
9adf3fc740a0b85d40a50fd1f0689b08d7809778
/release.ino
a8d744703fc2196eca8f2c981a8ffcbfbc40448f
[]
no_license
lopesdosreis/Arduino-Mega-NFC-Ethernet-Shield
38de9cb3c2249528aae25662963179ab135f401e
2390bea14b3b5a675e3dacfd121ff65c8a8d5219
refs/heads/master
2021-01-09T06:49:39.243031
2015-09-05T11:58:49
2015-09-05T11:58:49
81,091,864
1
0
null
2017-02-06T13:51:11
2017-02-06T13:51:11
null
UTF-8
C++
false
false
7,567
ino
/* // Materials Arduino Mega 2560 Rev3 ITEAD PN532 NFC Module Arduino Ethernet Shield R3 Cat5e Ethernet Patch Cable (15 Feet) - RJ45 Computer Networking Cord 50 PCS White/Red/Blue/Yellow LED Electronics 5mm - 10 units Veewon 3pcs Set Flexible 30cm Multicolored 40 Pin Male to Male,Male to Female,Female to Female Breadboard Jumper Wires Ribbon Cable (30cm) // LED STATUS 40 true Blue 41 false Red modified Thursday 23 July 2015 modified Thursday 31 July 2015 by Tuva Ergun */ #include <SPI.h> #include <HttpClient.h> #include <Ethernet.h> #include <EthernetClient.h> #include <PN532_SPI.h> #include <PN532.h> #include <NfcAdapter.h> #define DEBUG // debug modunu açmak için define aktif edilmeli // Internet byte mac[] = { 0xFF, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF }; char server[] = "arduino.tuva.me"; const int kNetworkTimeout = 30*700; const int kNetworkDelay = 800; /////////////////////// String inString = ""; String stringTwo = ""; // string to hold input String stringUrl = "/ping/EF3136F282CCC00C960F0F20F620BA15/"; // string to hold input String readString = "", readString1 = ""; int x=0; char lf=10; /////////////////////// // NDEF nfc PN532_SPI pn532spi(SPI, 46); NfcAdapter nfc = NfcAdapter(pn532spi); void setup() { #ifdef DEBUG Serial.begin(115200); // sadece serial debug da gosterilir Serial.println("------[ BOOT START ]-----"); #endif pinMode(40, OUTPUT); pinMode(41, OUTPUT); while (Ethernet.begin(mac) != 1){ #ifdef DEBUG Serial.println("-> Error getting IP address via DHCP, trying again..."); // sadece serial debug da gosterilir #endif Ethernet.begin(mac); delay(500); } delay(2000); #ifdef DEBUG Serial.println("======[ TUVA ]====="); Serial.println("------[ anfc v0.3 ]-----"); Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); Serial.print("IP Address : "); Serial.println(Ethernet.localIP()); Serial.print("Subnet Mask : "); Serial.println(Ethernet.subnetMask()); Serial.print("Default Gateway IP: "); Serial.println(Ethernet.gatewayIP()); Serial.print("DNS Server IP : "); Serial.println(Ethernet.dnsServerIP()); Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); #endif } void loop(){ nfc.begin(); if (nfc.tagPresent()){ NfcTag tag = nfc.read(); stringTwo = tag.getUidString(); stringTwo.replace(" ", ":"); // D0:1E:75:11 #ifdef DEBUG Serial.print("-> UID: ");Serial.println(tag.getUidString()); // sadece serial debug da gosterilir Serial.print("-> UID Format: ");Serial.println(stringTwo); // sadece serial debug da gosterilir #endif if (stringTwo){ ethernetGET(); } // kart okuma başarılı ise bi sure işlemlerın tamamlanması için beklıyor. delay(200); } // nfc read döngusu delay(200); } void ethernetGET(){ inString = stringUrl + stringTwo; // ethernet baslıyor int err =0; EthernetClient c; HttpClient http(c); String newData; char buffer[80]; newData=inString; newData.toCharArray(buffer, 80); #ifdef DEBUG Serial.println(buffer); #endif err = http.get(server, buffer); if (err == 0) { #ifdef DEBUG Serial.println("Started Request ok"); #endif err = http.responseStatusCode(); if (err >= 0) { #ifdef DEBUG Serial.print("Got status code: "); Serial.println(err); #endif // Usually you'd check that the response code is 200 or a // similar "success" code (200-299) before carrying on, // but we'll print out whatever response we get err = http.skipResponseHeaders(); if (err >= 0) { int bodyLen = http.contentLength(); #ifdef DEBUG Serial.print("Content length is: "); Serial.println(bodyLen); Serial.println(); Serial.println("Body returned follows:"); #endif // Now we've got to the body, so we can print it out unsigned long timeoutStart = millis(); char c; // Whilst we haven't timed out & haven't reached the end of the body while ( (http.connected() || http.available()) && ((millis() - timeoutStart) < kNetworkTimeout) ) { if (http.available()) { c = http.read(); if (c != '\n') { readString += c; } bodyLen--; // We read something, reset the timeout counter timeoutStart = millis(); } else { // We haven't got any data, so let's pause to allow some to // arrive delay(kNetworkDelay); } } // gelen cevaplar if (readString != "") { #ifdef DEBUG Serial.println("- - - - - - - - - - - - - - [ GELEN CEVAP ] - - - - - - - - - - - - - - - - - - - -"); Serial.println(); Serial.println(); Serial.print("Current data row : " ); Serial.println(readString); Serial.println(); Serial.println(); #endif readString.replace('[', ' '); if (readString.indexOf("true") > 0) { #ifdef DEBUG Serial.println("- - [ True deger ] - - -"); #endif digitalWrite(40, 225); delay(800); digitalWrite(40, 0); } if (readString.indexOf("false") > 0) { #ifdef DEBUG Serial.println("- - [ False deger ] - - -"); #endif digitalWrite(41, 225); delay(800); digitalWrite(41, 0); } #ifdef DEBUG Serial.println(); Serial.println(); Serial.println("- - - - - - - - - - - - - - [ GELEN CEVAP ] - - - - - - - - - - - - - - - - - - - -"); #endif } readString1 = ""; readString = ""; //gelen cevaplar } else { #ifdef DEBUG Serial.print("Failed to skip response headers: "); Serial.println(err); #endif } } else { #ifdef DEBUG Serial.print("Getting response failed: "); Serial.println(err); #endif } } else { #ifdef DEBUG Serial.print("Connect failed: "); Serial.println(err); #endif } http.stop(); delay(100); // Connect closed inString = ""; }
6822a5009233f7f4d90256c19789f9584826d5c9
10d82ee86e6187a4d7f132401d711714c53f8828
/src/scripts/src/GossipScripts/Gossip_Stormwind.cpp
c7d50659ae117b89d919c62ba790437c6147b221
[]
no_license
al3xc1985/HearthStone-Emu
315ffcebe6dbc396874c17378a68c26ac980cb47
8880fdda56f1ef1a0ae7b0efb9ac22b891334654
refs/heads/master
2021-03-21T19:57:10.950613
2011-10-24T13:52:23
2011-10-24T13:52:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,501
cpp
/* * Moon++ Scripts for Ascent MMORPG Server * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "Setup.h" // Archmage Malin #define GOSSIP_ARCHMAGE_MALIN "Can you send me to Theramore? I have an urgent message for Lady Jaina from Highlord Bolvar." class ArchmageMalin_Gossip : public GossipScript { public: void GossipHello(ObjectPointer pObject, PlayerPointer plr, bool AutoSend) { GossipMenu *Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 11469, plr); if(plr->GetQuestLogForEntry(11223)) Menu->AddItem( 0, GOSSIP_ARCHMAGE_MALIN, 1); if(AutoSend) Menu->SendTo(plr); } void GossipSelectOption(ObjectPointer pObject, PlayerPointer plr, uint32 Id, uint32 IntId, const char * Code) { CreaturePointer pCreature = (pObject->GetTypeId()==TYPEID_UNIT)?(TO_CREATURE(pObject)):NULLCREATURE; if(pObject->GetTypeId()!=TYPEID_UNIT) return; switch(IntId) { case 1: { plr->Gossip_Complete(); pCreature->CastSpell(plr, dbcSpell.LookupEntry(42711), true); }break; } } void Destroy() { delete this; } }; //This is when you talk to Thargold Ironwing...He will fly you through Stormwind Harbor to check it out. /*class SCRIPT_DECL SWHarborFlyAround : public GossipScript { public: void GossipHello(Object * pObject, Player* Plr, bool AutoSend); void GossipSelectOption(Object * pObject, Player* Plr, uint32 Id, uint32 IntId, const char * Code); void GossipEnd(Object * pObject, Player* Plr); void Destroy() { delete this; } }; void SWHarborFlyAround::GossipHello(Object * pObject, Player* Plr, bool AutoSend) { GossipMenu *Menu; //objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 13454, plr); Menu->AddItem( 0, "Yes, please.", 1 ); Menu->AddItem( 0, "No, thank you.", 2 ); if(AutoSend) //Menu->SendTo(Plr); } void SWHarborFlyAround::GossipSelectOption(Object * pObject, Player* Plr, uint32 Id, uint32 IntId, const char * Code) { Creature * pCreature = (pObject->GetTypeId()==TYPEID_UNIT)?((Creature*)pObject):NULL; if(pCreature==NULL) return; switch(IntId) { case 1:{ TaxiPath * taxipath = sTaxiMgr.GetTaxiPath(1041); Plr->DismissActivePet(); Plr->TaxiStart(taxipath, 25679, 0); }break; case 2: {Plr->Gossip_Complete();} break; } } void SWHarborFlyAround::GossipEnd(Object * pObject, Player* Plr) { //GossipScript::GossipEnd(pObject, Plr); }*/ void SetupStormwindGossip(ScriptMgr * mgr) { GossipScript * ArchmageMalinGossip = (GossipScript*) new ArchmageMalin_Gossip; mgr->register_gossip_script(2708, ArchmageMalinGossip); // Archmage Malin //GossipScript * SWHARFLY = (GossipScript*) new SWHarborFlyAround(); //mgr->register_gossip_script(29154, SWHARFLY); }
80943c437262f64b756afc7bc5e7d312bf52c9f3
a867ea2056ae2953870f6ca92c1e9b8e0cc5c10c
/NonOffOpenFOAM/FoamCases/ppWall/2.6/p
1d5baeb6e3339665486e6b3d6526c9a71160422a
[]
no_license
enrsanqui/OpenFOAM
ca9948b29e5753a302d9d119ca26e89ea0ef969b
32fdcf986f00e518c303058fa30ac66293782904
refs/heads/master
2021-01-02T23:10:15.612823
2017-08-29T18:44:55
2017-08-29T18:44:55
99,481,219
0
0
null
null
null
null
UTF-8
C++
false
false
6,096
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1612+ | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "2.6"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 400 ( 1.18989e-09 1.32815e-09 1.1333e-09 1.21216e-09 1.06872e-09 1.11012e-09 1.00163e-09 1.01312e-09 9.3086e-10 9.19129e-10 8.57713e-10 8.26937e-10 7.83288e-10 7.35578e-10 7.08465e-10 6.44225e-10 6.34346e-10 5.53681e-10 5.6649e-10 5.34186e-10 1.18557e-09 1.32373e-09 1.13297e-09 1.21207e-09 1.06873e-09 1.1101e-09 1.00164e-09 1.01311e-09 9.30865e-10 9.19125e-10 8.57715e-10 8.26937e-10 7.83286e-10 7.3558e-10 7.08461e-10 6.44227e-10 6.34297e-10 5.53714e-10 5.63543e-10 5.31068e-10 1.18313e-09 1.32059e-09 1.13257e-09 1.21206e-09 1.06867e-09 1.11014e-09 1.00161e-09 1.01313e-09 9.30848e-10 9.19137e-10 8.57707e-10 8.2694e-10 7.83287e-10 7.35575e-10 7.08468e-10 6.44211e-10 6.34276e-10 5.53682e-10 5.61222e-10 5.28922e-10 1.18236e-09 1.31912e-09 1.13218e-09 1.21207e-09 1.06861e-09 1.11018e-09 1.00158e-09 1.01316e-09 9.30828e-10 9.19151e-10 8.57699e-10 8.26944e-10 7.83288e-10 7.3557e-10 7.08478e-10 6.44193e-10 6.34268e-10 5.53602e-10 5.59892e-10 5.27826e-10 1.1826e-09 1.31882e-09 1.13182e-09 1.21208e-09 1.06857e-09 1.11021e-09 1.00155e-09 1.01318e-09 9.30812e-10 9.19163e-10 8.57692e-10 8.26947e-10 7.83289e-10 7.35566e-10 7.08486e-10 6.44179e-10 6.34263e-10 5.53499e-10 5.59334e-10 5.27446e-10 1.18351e-09 1.31929e-09 1.13146e-09 1.21208e-09 1.06853e-09 1.11024e-09 1.00153e-09 1.0132e-09 9.30799e-10 9.19171e-10 8.57686e-10 8.26949e-10 7.83289e-10 7.35562e-10 7.08493e-10 6.44168e-10 6.34261e-10 5.53384e-10 5.59393e-10 5.27625e-10 1.18488e-09 1.32031e-09 1.13109e-09 1.21208e-09 1.06849e-09 1.11026e-09 1.00151e-09 1.01321e-09 9.3079e-10 9.19178e-10 8.57682e-10 8.26951e-10 7.8329e-10 7.35559e-10 7.08498e-10 6.4416e-10 6.34262e-10 5.53265e-10 5.59969e-10 5.28267e-10 1.1865e-09 1.32163e-09 1.13071e-09 1.21207e-09 1.06847e-09 1.11027e-09 1.0015e-09 1.01322e-09 9.30782e-10 9.19183e-10 8.57679e-10 8.26952e-10 7.83291e-10 7.35557e-10 7.08503e-10 6.44154e-10 6.34265e-10 5.53154e-10 5.60939e-10 5.29245e-10 1.18813e-09 1.32303e-09 1.13032e-09 1.21206e-09 1.06845e-09 1.11028e-09 1.00149e-09 1.01323e-09 9.30777e-10 9.19187e-10 8.57677e-10 8.26953e-10 7.83291e-10 7.35555e-10 7.08506e-10 6.4415e-10 6.34269e-10 5.53058e-10 5.62154e-10 5.30407e-10 1.18957e-09 1.32427e-09 1.12991e-09 1.21203e-09 1.06843e-09 1.11029e-09 1.00149e-09 1.01323e-09 9.30775e-10 9.19188e-10 8.57676e-10 8.26953e-10 7.83292e-10 7.35554e-10 7.08508e-10 6.44149e-10 6.34271e-10 5.52983e-10 5.63454e-10 5.31596e-10 1.19064e-09 1.32518e-09 1.12951e-09 1.21199e-09 1.06842e-09 1.11029e-09 1.00149e-09 1.01323e-09 9.30776e-10 9.19188e-10 8.57676e-10 8.26953e-10 7.83292e-10 7.35554e-10 7.08509e-10 6.4415e-10 6.3427e-10 5.52934e-10 5.64681e-10 5.32661e-10 1.19121e-09 1.32562e-09 1.1291e-09 1.21194e-09 1.06842e-09 1.11028e-09 1.00149e-09 1.01322e-09 9.30779e-10 9.19185e-10 8.57678e-10 8.26952e-10 7.83292e-10 7.35555e-10 7.08509e-10 6.44154e-10 6.34263e-10 5.52911e-10 5.65691e-10 5.33463e-10 1.19117e-09 1.3255e-09 1.12871e-09 1.21187e-09 1.06842e-09 1.11027e-09 1.0015e-09 1.01322e-09 9.30785e-10 9.19181e-10 8.57681e-10 8.26951e-10 7.83292e-10 7.35556e-10 7.08507e-10 6.44159e-10 6.34251e-10 5.52913e-10 5.66363e-10 5.33891e-10 1.19052e-09 1.32481e-09 1.12835e-09 1.21179e-09 1.06843e-09 1.11025e-09 1.00152e-09 1.01321e-09 9.30793e-10 9.19175e-10 8.57684e-10 8.26949e-10 7.83292e-10 7.35558e-10 7.08504e-10 6.44166e-10 6.34232e-10 5.52937e-10 5.66609e-10 5.33867e-10 1.18929e-09 1.3236e-09 1.12802e-09 1.2117e-09 1.06845e-09 1.11023e-09 1.00154e-09 1.01319e-09 9.30804e-10 9.19168e-10 8.57689e-10 8.26947e-10 7.83292e-10 7.35561e-10 7.08499e-10 6.44175e-10 6.34205e-10 5.52978e-10 5.66381e-10 5.33351e-10 1.18758e-09 1.32198e-09 1.12773e-09 1.21161e-09 1.06847e-09 1.1102e-09 1.00156e-09 1.01317e-09 9.30817e-10 9.19158e-10 8.57695e-10 8.26944e-10 7.83292e-10 7.35564e-10 7.08493e-10 6.44185e-10 6.34172e-10 5.5303e-10 5.65692e-10 5.32361e-10 1.18555e-09 1.32014e-09 1.12751e-09 1.2115e-09 1.06851e-09 1.11016e-09 1.00158e-09 1.01315e-09 9.30833e-10 9.19147e-10 8.57702e-10 8.26941e-10 7.83291e-10 7.35568e-10 7.08485e-10 6.44196e-10 6.34131e-10 5.53089e-10 5.64598e-10 5.30947e-10 1.18349e-09 1.31842e-09 1.12735e-09 1.21139e-09 1.06855e-09 1.11012e-09 1.00162e-09 1.01313e-09 9.30854e-10 9.19133e-10 8.57711e-10 8.26937e-10 7.83291e-10 7.35574e-10 7.08475e-10 6.44209e-10 6.34082e-10 5.53149e-10 5.63225e-10 5.29224e-10 1.1819e-09 1.31714e-09 1.12724e-09 1.21128e-09 1.06859e-09 1.11008e-09 1.00165e-09 1.0131e-09 9.30871e-10 9.1912e-10 8.57719e-10 8.26933e-10 7.8329e-10 7.35578e-10 7.08466e-10 6.44219e-10 6.34032e-10 5.53202e-10 5.61665e-10 5.27366e-10 1.18161e-09 1.31658e-09 1.12709e-09 1.21126e-09 1.06856e-09 1.11009e-09 1.00164e-09 1.01311e-09 9.30865e-10 9.19125e-10 8.57716e-10 8.26934e-10 7.83291e-10 7.35576e-10 7.08469e-10 6.44209e-10 6.34004e-10 5.53222e-10 5.60202e-10 5.25934e-10 ) ; boundaryField { top { type zeroGradient; } bottom { type zeroGradient; } inlet { type fixedValue; value uniform 0; } outlet { type fixedValue; value uniform 0; } frontAndBack { type empty; } } // ************************************************************************* //
5b30f9330e920d001393da6f16d6be48f3492411
0342be286ad1d4056a33a07ac33c3336aa067856
/addons/tm_tmf_loadouts/loadouts/generic_paramilitary_tigerstripe_m16.hpp
0b3682464a6e609503bd7b537780adc1f140c6a6
[]
no_license
ChrisyBGaming/1tac_misc
45e0618c8d607722cbeef9d34dcf666f45461481
a1b78df1f1aa6d5f41408c1e32e9435fea373727
refs/heads/master
2020-03-14T03:29:53.336012
2018-04-23T09:25:40
2018-04-23T09:25:40
131,421,310
0
0
null
2018-04-28T15:28:24
2018-04-28T15:28:24
null
UTF-8
C++
false
false
11,126
hpp
/* assignGear specific macros */ // originally by Fingers // ???? tooltip = "Author: Bear\n\nSuitable for 1985-now, great on Tanoa."; class baseMan {// Weaponless baseclass displayName = "Unarmed"; // All randomized. uniform[] = {"rhsgref_uniform_tigerstripe"}; vest[] = {}; backpack[] = {}; headgear[] = {"usm_bdu_boonie_tgrstp"}; goggles[] = {}; hmd[] = {}; // Leave empty to remove all. "Default" > leave original item. // All randomized primaryWeapon[] = {}; scope[] = {}; bipod[] = {}; attachment[] = {}; silencer[] = {}; // Leave empty to remove all. "Default" for primaryWeapon > leave original weapon. // Only *Weapons[] arrays are randomized secondaryWeapon[] = {}; secondaryAttachments[] = {}; sidearmWeapon[] = {}; sidearmAttachments[] = {}; // Leave empty to remove all. "Default" for secondaryWeapon or sidearmWeapon > leave original weapon. // These are added to the uniform or vest magazines[] = {}; items[] = {}; // These are added directly into their respective slots linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch" }; // These are put into the backpack backpackItems[] = {}; // This is executed after unit init is complete. argument: _this = _unit. code = ""; // These are acre item radios that will be added during the ACRE init. ACRE radios added via any other system will be erased. radios[] = {}; }; class r : baseMan { displayName = "Rifleman"; headgear[] = {"usm_bdu_boonie_tgrstp"}; vest[] = {"V_TacVest_oli"}; backpack[] = {}; primaryWeapon[] = {"mbg_m16a2"}; scope[] = {}; attachment[] = {}; magazines[] = { LIST_9("30Rnd_556x45_Stanag"), "rhs_mag_m67", "rhs_mag_an_m8hc" }; items[] = { LIST_3("ACE_fieldDressing"), "ACE_morphine" }; }; class g : r { displayName = "Grenadier"; primaryWeapon[] = {"rhs_weap_m16a4_carryhandle_M203"}; magazines[] += { LIST_4("rhs_mag_M441_HE"), LIST_2("rhs_mag_m714_White") }; }; class car : r { displayName = "Carabinier"; primaryWeapon[] = {"mbg_m16a2"}; }; class m : car { displayName = "Medic"; backpack[] = {"usm_pack_m5_medic"}; backpackItems[] = { LIST_15("ACE_fieldDressing"), LIST_10("ACE_morphine"), LIST_6("ACE_epinephrine"), LIST_2("ACE_bloodIV"), LIST_2("rhs_mag_an_m8hc") }; }; class smg : r { displayName = "Submachinegunner"; primaryWeapon[] = {"CUP_smg_MP5A5"}; magazines[] = { LIST_6("CUP_30Rnd_9x19_MP5"), "rhs_mag_m67", "rhs_mag_an_m8hc" }; }; class ftl : r { displayName = "Fireteam Leader"; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; }; class sl : ftl { displayName = "Squad Leader"; backpack[] = {"usm_pack_st138_prc77"}; items[] += {"ACE_Maptools"}; }; class co : sl { displayName = "Platoon Leader"; sidearmWeapon[] = {"rhsusf_weap_m9"}; backPack[] = {"usm_pack_st138_prc77"}; magazines[] = { LIST_7("30Rnd_556x45_Stanag"), LIST_2("30Rnd_556x45_Stanag_Tracer_Red"), "rhs_mag_m67", LIST_2("rhs_mag_an_m8hc") }; backpackItems[] = {}; }; class fac : co { displayName = "Forward Air Controller"; backPack[] = {"usm_pack_alice_prc77"}; backpackItems[] = {}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; items[] = { LIST_3("ACE_fieldDressing"), "ACE_morphine", "ACE_Maptools" }; }; class ar : r { displayName = "Automatic Rifleman"; backpack[] = {"B_Carryall_oli"}; primaryWeapon[] = {"hlc_lmg_m60"}; bipod[] = {}; magazines[] = { LIST_4("hlc_100Rnd_762x51_M_M60E4"), "rhs_mag_m67", "rhs_mag_an_m8hc" }; }; class aar : r { displayName = "Assistant Automatic Rifleman"; backpack[] = {"usm_pack_762x51_ammobelts"}; backpackItems[] = { LIST_3("hlc_100Rnd_762x51_M_M60E4") }; linkedItems[] += {"Binocular"}; }; class rat : car { displayName = "Rifleman (AT)"; secondaryWeapon[] = {"rhs_weap_m72a7"}; }; class dm : r { displayName = "Designated Marksman"; primaryWeapon[] = {"hlc_rifle_M21"}; scope[] = {"hlc_optic_artel_m14"}; bipod[] = {}; magazines[] = { LIST_8("hlc_20Rnd_762x51_B_M14"), "rhs_mag_m67", "rhs_mag_an_m8hc" }; }; class mmgg : ar { displayName = "MMG Gunner"; backpack[] = {"B_Carryall_oli"}; primaryWeapon[] = {"hlc_lmg_m60"}; scope[] = {}; magazines[] = { LIST_6("hlc_100Rnd_762x51_M_M60E4"), "rhs_mag_m67", "rhs_mag_an_m8hc" }; }; class mmgac : r { displayName = "MMG Ammo Carrier"; backpack[] = {"usm_pack_762x51_ammobelts"}; backpackItems[] = { LIST_3("hlc_100Rnd_762x51_M_M60E4") }; }; class mmgag : aar { displayName = "MMG Assistant Gunner"; backpack[] = {"usm_pack_762x51_ammobelts"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; backpackItems[] = { LIST_3("hlc_100Rnd_762x51_M_M60E4") }; }; class hmgg : car { displayName = "HMG Gunner"; backPack[] = {"RHS_M2_Gun_Bag"}; }; class hmgac : r { displayName = "HMG Ammo Carrier"; backPack[] = {"RHS_M2_Gun_Bag"}; }; class hmgag : car { displayName = "HMG Assistant Gunner"; backPack[] = {"RHS_M2_Tripod_Bag"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; }; class matg : car { displayName = "MAT Gunner"; backpack[] = {"B_Carryall_oli"}; secondaryWeapon[] = {"CUP_launch_M47"}; backpackItems[] += {"CUP_Dragon_EP1_M"}; }; class matac : r { displayName = "MAT Ammo Carrier"; backpack[] = {"B_Carryall_oli"}; backpackItems[] += {"CUP_Dragon_EP1_M"}; }; class matag : car { displayName = "MAT Assistant Gunner"; backpack[] = {"B_Carryall_oli"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; backpackItems[] += {"CUP_Dragon_EP1_M"}; }; class hatg : car { displayName = "HAT Gunner"; secondaryWeapon[] = {"rhs_weap_fgm148"}; backpack[] = {"B_Carryall_oli"}; backpackItems[] = { "rhs_fgm148_magazine_AT" }; }; class hatac : r { displayName = "HAT Ammo Carrier"; backpack[] = {"B_Carryall_oli"}; backpackItems[] = { "rhs_fgm148_magazine_AT" }; }; class hatag : car { displayName = "HAT Assistant Gunner"; backpack[] = {"B_Carryall_oli"}; backpackItems[] = { "rhs_fgm148_magazine_AT" }; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; }; class mtrg : car { displayName = "Mortar Gunner"; backPack[] = {"B_Mortar_01_weapon_F"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch" }; }; class mtrac : r { displayName = "Mortar Ammo Carrier"; backPack[] = {"B_Mortar_01_weapon_F"}; }; class mtrag : car { displayName = "Mortar Assistant Gunner"; backPack[] = {"B_Mortar_01_support_F"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; }; class samg : car { displayName = "AA Missile Specialist"; backpack[] = {"B_Carryall_oli"}; secondaryWeapon[] = {"rhs_weap_fim92"}; magazines[] += { "rhs_fim92_mag" }; }; class samag : car { displayName = "AA Assistant Missile Specialist"; backpack[] = {"B_Carryall_oli"}; linkedItems[] = { "ItemMap", "ItemCompass", "ItemWatch", "Binocular" }; backpackItems[] = { "rhs_fim92_mag" }; }; class sn : r { displayName = "Sniper"; uniform[] = {"CUP_U_B_USMC_Ghillie_WDL"}; headgear[] = {}; goggles[] = {"default"}; primaryWeapon[] = {"hlc_rifle_M21"}; scope[] = {"hlc_optic_artel_m14"}; bipod[] = {}; sidearmWeapon[] = {"rhsusf_weap_m9"}; magazines[] = { LIST_8("hlc_20Rnd_762x51_mk316_M14"), LIST_2("rhs_mag_m67"), LIST_4("rhsusf_mag_15Rnd_9x19_FMJ") }; backpack[] = {}; items[] += {"ACE_Kestrel4500", "ACE_microDAGR"}; }; class sp : r { displayName = "Spotter"; linkedItems[] += {"ACE_Vector"}; items[] += {"ACE_Kestrel4500", "ACE_microDAGR"}; }; class vc : smg { displayName = "Vehicle Commander"; headgear[] = {"usm_helmet_cvc"}; linkedItems[] += {"Binocular"}; }; class vd : smg { displayName = "Vehicle Driver"; backpack[] = {"B_Carryall_oli"}; backpackItems[] = {"ToolKit"}; headgear[] = {"usm_helmet_cvc"}; }; class vg : vd { displayName = "Vehicle Gunner"; backpack[] = {}; backpackItems[] = {}; }; class pp : smg { displayName = "Helicopter Pilot"; uniform[] = {"CUP_U_B_USMC_PilotOverall"}; vest[] = {"CUP_V_B_PilotVest"}; backpack[] = {"rhsusf_falconii"}; headgear[] = {"CUP_H_BAF_Helmet_Pilot"}; goggles[] = {}; linkedItems[] += {"ItemGPS"}; items[] += {"ACE_DAGR"}; }; class pcc : smg { displayName = "Helicopter Crew Chief"; uniform[] = {"CUP_U_B_USMC_PilotOverall"}; vest[] = {"CUP_V_B_PilotVest"}; backpack[] = {"rhsusf_falconii"}; headgear[] = {"CUP_H_BAF_Helmet_Pilot"}; goggles[] = {}; linkedItems[] += {"ItemGPS"}; magazines[] += { LIST_2("rhs_mag_m715_Green") }; }; class pc : pcc { displayName = "Helicopter Crew"; backpack[] = {}; backpackItems[] = {}; }; class jp : baseMan { displayName = "Jet pilot"; uniform[] = {"CUP_U_B_USMC_PilotOverall"}; backpack[] = {"rhsusf_assault_eagleaiii_ucp"}; headgear[] = {"RHS_jetpilot_usaf"}; goggles[] = {"default"}; sidearmWeapon[] = {"rhsusf_weap_m9"}; magazines[] = { LIST_4("rhsusf_mag_15Rnd_9x19_FMJ") }; items[] = { LIST_3("ACE_fieldDressing"), "ACE_morphine" }; linkedItems[] = {"ItemMap","ItemGPS","ItemCompass","ItemWatch"}; }; class eng : car { displayName = "Combat Engineer (Explosives)"; backpack[] = {"B_Carryall_oli"}; magazines[] += { LIST_4("ClaymoreDirectionalMine_Remote_Mag") }; backpackItems[] = { "MineDetector", "ToolKit", LIST_2("DemoCharge_Remote_Mag"), LIST_2("SLAMDirectionalMine_Wire_Mag") }; items[] += {"ACE_M26_Clacker","ACE_DefusalKit"}; }; class engm : car { displayName = "Combat Engineer (Mines)"; items[] += { LIST_2("APERSBoundingMine_Range_Mag"), LIST_2("APERSTripMine_Wire_Mag"), "ACE_M26_Clacker", "ACE_DefusalKit" }; backpackItems[] = { "MineDetector", "ToolKit", "ATMine_Range_Mag" }; }; class UAV : car { displayName = "UAV Operator"; backpack[] = {"B_rhsusf_B_BACKPACK"}; linkedItems[] += {"B_UavTerminal"}; };
ce2a736645ea0710c97110acfbde03d772bd0355
f1ed26ec9331474259b11f39b1f60933118bbad4
/DataStructures&Algorithms/SortMethods.h
7449198d98180ed732d97a80714f1dd3e0f2b70f
[]
no_license
Alexandergape/CPP_REVIEW
93bad9aaff6c8f93e9627cc1f92510ea50f732dd
8bc3f27fe4a53188ca1250f04228663f77d4f2db
refs/heads/master
2023-01-07T21:21:47.792546
2020-11-05T21:02:09
2020-11-05T21:02:09
287,578,590
0
0
null
null
null
null
UTF-8
C++
false
false
5,169
h
// // Created by Alexander P on 20/09/10. // #ifndef FIRST_STEPS_WITH_C___SORTMETHODS_H #define FIRST_STEPS_WITH_C___SORTMETHODS_H #include "SortMethods.h" #include "vector" using namespace std; template<typename E> void QuickSort(vector<E> &elements, int first, int last) { int i = first, j = last, posPiv = (int) (first + last) / 2; E pivot, aux; do { while (elements.at(i) < pivot)i++; while (elements.at(j) > pivot)j--; if (i <= j) { aux = elements.at(i); elements.at(i) = elements.at(j); elements.at(j) = aux; i++, j--; } } while (i <= j); if (first < j) QuickSort(elements, first, j); if (i < last) QuickSort(elements, i, last); } template<typename E> void mergeSort(vector<E> &array, int low, int high) { if (high <= low) return; int mid = (low + high) / 2; mergeSort(array, low, mid); mergeSort(array, mid + 1, high); merge(array, low, mid, high); } template<typename E> static void merge(vector<E> &array, int low, int mid, int high) { // Creating temporary subarrays auto *leftArray = new vector<E>(mid - low + 1); auto *rightArray = new vector<E>(high - mid); // Copying our subarrays into temporaries for (int i = 0; i < leftArray->size(); i++) leftArray->at(i) = array.at(low + 1); for (int i = 0; i < rightArray->size(); i++) rightArray->at(i) = array.at(mid + i + 1); // Iterators containing current index of temp subarrays int leftIndex = 0; int rightIndex = 0; // Copying from leftArray and rightArray back into array for (int i = low; i < high + 1; i++) { // If there are still uncopied elements in R and L, copy minimum of the two if (leftIndex < leftArray->size() && rightIndex < rightArray->size()) { if (leftArray->at(leftIndex) < rightArray->at(rightIndex)) { array.at(i) = leftArray->at(leftIndex); leftIndex++; } else { array.at(i) = rightArray->at(rightIndex); rightIndex++; } } else if (leftIndex < leftArray->size()) { // If all elements have been copied from rightArray, copy rest of leftArray array.at(i) = leftArray->at(leftIndex); leftIndex++; } else if (rightIndex < rightArray->size()) { // If all elements have been copied from leftArray, copy rest of rightArray array.at(i) = rightArray->at(rightIndex); rightIndex++; } } } template<typename E> void BubbleSort(vector<E> &elements) { bool flag; E *aux; for (int i = 0; i < elements.size() - 1; ++i) { flag = false; for (int j = 0; j < elements.size() - 1; ++j) if (elements.at(j) > elements.at(j + 1)) { flag = true; aux = elements.at(j); elements.at(j) = elements.at(j + 1); elements.at(j + 1) = aux; } } } template<typename E> void ShellSort(vector<E> &elements) { int k, aux, j, jump = int(elements.size()) / 2;; while (jump > 0) { for (int i = jump; i < int(elements.size()); i++) { j = i - jump; while (j >= 0) { k = j + jump; if (elements[j] < elements[k]) j = -1; else { aux = elements[j]; elements[j] = elements[k]; elements[k] = aux; j -= jump; } } } jump /= 2; } } template<typename E> static void HeapSort(vector<E> &elements) { int n = elements.size(); // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(elements, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end E *temp = elements[0]; elements[0] = elements[i]; elements[i] = *temp; // call max heapify on the reduced heap heapify(elements, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap template<typename E> static void heapify(vector<E> &elements, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && elements[l] > elements[largest]) largest = l; // If right child is larger than largest so far if (r < n && elements[r] > elements[largest]) largest = r; // If largest is not root if (largest != i) { E *swap = elements[i]; elements[i] = elements[largest]; elements[largest] = *swap; // Recursively heapify the affected sub-tree heapify(elements, n, largest); } } #endif //FIRST_STEPS_WITH_C___SORTMETHODS_H
96b2b5fa4df57771053ffdc031c8c675c7881ac0
6680f8d317de48876d4176d443bfd580ec7a5aef
/Header/MockPackageDataRenderingAdapter.h
1d373df661bfe6ed1474479ae686eb40cc846f0d
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
2,795
h
#pragma once #include "IPackageDataRenderingAdapter.h" MOCK_BASE_CLASS(MockPackageDataRenderingAdapter, IPackageDataRenderingAdapter) { MOCK_NON_CONST_METHOD(SetVolumeViewingType, 1, void(misVolumeViewingTypes volumeViewingType)); MOCK_NON_CONST_METHOD(ShowPackage, 7, void(std::shared_ptr<ISimpleDataPackage>, const misVisualizationSetting&, const misSegmentationSetting&, double minOpacity, bool resetZoom, misCursorType pWidgetType, std::map<misPlaneEnum, bool> pPlaneVisible)); MOCK_NON_CONST_METHOD(ShowVolume, 1, void(std::shared_ptr<IVolumeDataDependency> volumeProp)); MOCK_NON_CONST_METHOD(UpdateColormap, 1, void(std::shared_ptr<IVolumeDataDependency> volumeProp)); MOCK_NON_CONST_METHOD(ShowVolumes, 1, int(VolumeDataDependencyListTypes NewVolumeDataDependencies)); MOCK_NON_CONST_METHOD(Reset, 0, void()); MOCK_NON_CONST_METHOD(UpdateRepresentationTransforms, 2, void(std::shared_ptr<IVolumeRenderer> , std::shared_ptr<ISimpleDataPackage> ), update_1); MOCK_NON_CONST_METHOD(UpdateRepresentationTransforms, 0, void(void), update_2); MOCK_NON_CONST_METHOD(ReleaseImageResources, 0, void()); MOCK_NON_CONST_METHOD(SetWidgetType, 1, void(misCursorType pWidgetType)); MOCK_NON_CONST_METHOD(GetViewer, 0, std::shared_ptr<IVolumeRenderer>()); MOCK_NON_CONST_METHOD(SetCSCorrelationManager, 1, void(std::shared_ptr< ICoordinateSystemCorrelationManager<std::string> > val)); MOCK_NON_CONST_METHOD(SetSceneReferenceCoordinateSystem, 2, void(const std::string& , std::shared_ptr<ISimpleDataPackage> )); MOCK_NON_CONST_METHOD(SetDentalSpecialViewsEnable, 2, void(std::shared_ptr<IVolumeRenderer> viewer, bool enabled)); MOCK_NON_CONST_METHOD(SetPanoramicCoordinateConverter, 2, void(std::shared_ptr<const IPanoramicCoordinatesConverter> , std::shared_ptr<IVolumeRenderer> )); MOCK_NON_CONST_METHOD(ShowSegmentedObjects, 3, int(const misSegmentationSetting&, ImageContainedPolydataDependencyListTypes, double minOpacity)); MOCK_NON_CONST_METHOD(ShowPlan, 1, void(std::shared_ptr< parcast::IPackagePlanRel> rel)); MOCK_NON_CONST_METHOD(ShowPlans, 2, int(std::shared_ptr<IVolumeRenderer> viewer, std::shared_ptr<PlanDataListDependencyTypedef> rels)); MOCK_NON_CONST_METHOD(SetVisiblityOfColorMap, 2, void(misPlaneEnum planeIndex, bool val)); MOCK_NON_CONST_METHOD(SetColorMapTransFuncID, 2, void(misPlaneEnum planeIndex, std::shared_ptr<TransFuncIntensity> val)); MOCK_NON_CONST_METHOD(SetColorValueToTexture, 2, void(misPlaneEnum , misDoubleColorStruct ), SetColorValue_1); MOCK_NON_CONST_METHOD(SetOpacityValueToTexture, 2, void(misPlaneEnum planeIndex, float opacityValue), SetColorValue_2); MOCK_NON_CONST_METHOD(UpdatePosition, 1, void(parcast::Point<double, 3> position)); MOCK_NON_CONST_METHOD(SetVisibilityOfSegmentedImage, 2, void (misUID , bool )); };
45e287bd2d6fb12cdec254a36661fd2b8b8aa49e
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGLF/NUCLEX/Nuclei/NucleiPbPb/macros_pp13TeV/SystematicsTPC.cc
7ec2f257521e46d83c2189e88198324cb03fb811
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C++
false
false
11,280
cc
#include "src/Common.h" #include "src/Utils.h" using namespace utils; #include "src/Plotting.h" #include <map> #include <array> #include <vector> #include <string> #include <sstream> #include <limits.h> using std::array; using std::vector; using std::string; using std::to_string; #include <Riostream.h> #include <TFile.h> #include <TH1D.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TList.h> #include <TCanvas.h> #include <TMath.h> #include <TLegend.h> float zTest(const float mu0, const float sig0, const float mu1, const float sig1) { const float sigma = sqrt(sig0 * sig0 + sig1 * sig1); if (sigma < FLT_MIN * 10.f) return FLT_MAX; else return (mu0 - mu1) / std::abs(sig1-sig0); } void SystematicsTPC() { TFile input_file(kSpectraOutput.data()); TFile countsyst_file(kSignalOutput.data()); TFile shiftsyst_file(kSignalOutput.data()); TFile matsyst_file(kMaterialOutput.data()); //TFile secsyst_tpc_file(kSecondariesTPCoutput.data()); TFile output_file(kSystematicsOutputTPC.data(),"recreate"); int n_centralities = kCentLength; TAxis* centAxis = (TAxis*)input_file.Get("centrality"); const double pt_bin_limits[16] = {0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.4,1.6,1.8,2.0,2.2,2.6,3.0,3.4,3.8};//,4.4}; const int n_pt_bins = 15; vector<TH1F*> references_tpc(n_centralities,nullptr); vector<TH1F*> cutsyst_tpc(n_centralities,nullptr); vector<TH1F*> matsyst_tpc(n_centralities,nullptr); vector<TH1F*> abssyst_tpc(n_centralities,nullptr); vector<TH1F*> countsyst_tpc(n_centralities,nullptr); vector<TH1F*> shiftsyst_tpc(n_centralities,nullptr); vector<TH1F*> totsyst_tpc(n_centralities,nullptr); for (int iC = 0; iC < n_centralities; ++iC) { TDirectory* cent_dir = output_file.mkdir(to_string(iC).data()); for (int iS = 0; iS < 2; ++iS) { TDirectory* species_dir = cent_dir->mkdir(kNames[iS].data()); string basepath = kFilterListNames + "/" + kNames[iS] + "/TPCspectra" + to_string(iC); TH1F* references_tpc_tmp = (TH1F*)input_file.Get(basepath.data()); Requires(references_tpc_tmp,"Missing reference"); references_tpc[iC] = (TH1F*) references_tpc_tmp->Rebin(n_pt_bins,Form("TPCspectra_%d",iC),pt_bin_limits); auto ptAxis = references_tpc[iC]->GetXaxis(); string count_sys_path = kFilterListNames + "/" + kNames[iS] + "/Systematic/hWidenRangeSystTPC" + kLetter[iS] + to_string(iC); TH1F* countsyst_tpc_tmp = (TH1F*)countsyst_file.Get(count_sys_path.data()); Requires(countsyst_tpc_tmp,"Missing systematic"); species_dir->cd(); countsyst_tpc_tmp->Write("count_tpc_tmp"); references_tpc_tmp->Write("references_tpc_tmp"); references_tpc[iC]->Write(); countsyst_tpc[iC] = (TH1F*)countsyst_tpc_tmp->Rebin(n_pt_bins,Form("countsyst_tpc_%d",iC),pt_bin_limits); string shift_sys_path = kFilterListNames + "/" + kNames[iS] + "/Systematic/hShiftRangeSystTPC" + kLetter[iS] + to_string(iC); TH1F* shiftsyst_tpc_tmp = (TH1F*)shiftsyst_file.Get(shift_sys_path.data()); Requires(shiftsyst_tpc_tmp,"Missing systematic"); shiftsyst_tpc_tmp->Write("shiftsyst_tpc_tmp"); shiftsyst_tpc[iC] = (TH1F*)shiftsyst_tpc_tmp->Rebin(n_pt_bins,Form("shiftsyst_tpc_%d",iC),pt_bin_limits); string mat_sys_path = Form("deuterons%ctpc",kLetter[iS]); TH1F* matsyst_tmp = (TH1F*)matsyst_file.Get(mat_sys_path.data()); Requires(matsyst_tmp,"Missing matsysttpc"); matsyst_tmp->Write("matsyst_tpc_tmp"); matsyst_tpc[iC] = (TH1F*)matsyst_tmp->Rebin(n_pt_bins,Form("hMatSyst_%d",iC),pt_bin_limits); cutsyst_tpc[iC] = (TH1F*)countsyst_tpc[iC]->Clone(("cutsyst_tpc" + to_string(iC)).data()); cutsyst_tpc[iC]->Reset(); abssyst_tpc[iC] = (TH1F*)countsyst_tpc[iC]->Clone(("abssyst_tpc" + to_string(iC)).data()); abssyst_tpc[iC]->Reset(); totsyst_tpc[iC] = (TH1F*)countsyst_tpc[iC]->Clone(("totsyst_tpc" + to_string(iC)).data()); totsyst_tpc[iC]->Reset(); for (auto& syst : kCutNames) { basepath = kFilterListNames + syst.first.data() + "%i/" + kNames[iS] + "/TPCspectra" + to_string(iC); TDirectory* cut_dir = species_dir->mkdir(syst.first.data()); vector<TH1F*> variations(syst.second.size(),nullptr); vector<TH1F*> sigmas(syst.second.size(),nullptr); for (size_t iV = 0; iV < syst.second.size(); ++iV) { TH1F* variations_tmp = (TH1F*)input_file.Get(Form(basepath.data(),iV)); if (!variations_tmp) { cout << basepath.data() << " is missing." << endl; return; } variations[iV] = (TH1F*)variations_tmp->Rebin(n_pt_bins,Form("variation_%zu",iV),pt_bin_limits); variations[iV]->SetName(("cut" + to_string(iV)).data()); plotting::SetHistStyle(variations[iV],iV); sigmas[iV] = (TH1F*)variations[iV]->Clone(("sigma" + to_string(iV)).data()); sigmas[iV]->Reset(); sigmas[iV]->SetDrawOption("e"); } vector<float> rms(ptAxis->GetNbins(),0.f); for (int iB = 1; iB <= ptAxis->GetNbins(); ++iB) { if (ptAxis->GetBinCenter(iB) < kPtRange[0] || ptAxis->GetBinCenter(iB) > kPtRange[1]) continue; if (ptAxis->GetBinCenter(iB) > kTPCmaxPt) continue; abssyst_tpc[iC]->SetBinContent(iB,kAbsSyst[iS]); const float m0 = references_tpc[iC]->GetBinContent(iB); const float s0 = references_tpc[iC]->GetBinError(iB); vector<float> values{m0}; vector<float> weigths{s0}; for (size_t iV = 0; iV < syst.second.size(); ++iV) { const float m1 = variations[iV]->GetBinContent(iB); const float s1 = variations[iV]->GetBinError(iB); const float z = zTest(m0,s0,m1,s1); sigmas[iV]->SetBinContent(iB,z); if (z < 1. && kUseBarlow) { variations[iV]->SetBinContent(iB,0.f); variations[iV]->SetBinError(iB,0.f); } else { values.push_back(m1); weigths.push_back(s1); } } rms[iB - 1] = TMath::RMS(values.begin(),values.end()) / m0; cutsyst_tpc[iC]->SetBinContent(iB, cutsyst_tpc[iC]->GetBinContent(iB) + rms[iB-1] * rms[iB-1]); } cut_dir->cd(); TCanvas cv_variations("cv_variations","cv_variations"); cv_variations.cd(); references_tpc[iC]->Draw(); for (auto& var : variations) var->Draw("same"); cv_variations.Write(); TCanvas cv_ratios("cv_ratios","cv_ratios"); cv_ratios.DrawFrame(0.01,0.01,6.41,1.99,";#it{p}_{T} (GeV/#it{c});Ratio"); for (auto& var : variations) { var->Divide(references_tpc[iC]); var->Draw("same"); } cv_ratios.Write(); TCanvas cv_sigmas("cv_sigmas","cv_sigmas"); cv_sigmas.DrawFrame(0.01,-5.,6.41,5.,";#it{p}_{T} (GeV/#it{c});n#sigma"); for (auto& var : sigmas) { var->Draw("pesame"); } cv_sigmas.Write(); TH1F* h_rms = (TH1F*)references_tpc[iC]->Clone("rms"); h_rms->GetYaxis()->SetTitle("RMS"); h_rms->Reset(); for (int iB = 1; iB <= ptAxis->GetNbins(); ++iB) { if (ptAxis->GetBinCenter(iB) < kPtRange[0] || ptAxis->GetBinCenter(iB) > kPtRange[1]) continue; if (ptAxis->GetBinCenter(iB) > kTPCmaxPt) continue; h_rms->SetBinContent(iB,rms[iB-1]); } h_rms->Write(); } for (int iB = 1; iB <= cutsyst_tpc[iC]->GetNbinsX(); ++iB) { if (ptAxis->GetBinCenter(iB) > kTPCmaxPt) continue; cutsyst_tpc[iC]->SetBinContent(iB,sqrt(cutsyst_tpc[iC]->GetBinContent(iB))); } if (kSmoothSystematics) { cutsyst_tpc[iC]->GetXaxis()->SetRange(cutsyst_tpc[iC]->FindBin(kPtRange[0]+0.01),cutsyst_tpc[iC]->FindBin(kTPCmaxPt-0.01)); countsyst_tpc[iC]->GetXaxis()->SetRange(countsyst_tpc[iC]->FindBin(kPtRange[0]+0.01),countsyst_tpc[iC]->FindBin(kTPCmaxPt-0.01)); shiftsyst_tpc[iC]->GetXaxis()->SetRange(shiftsyst_tpc[iC]->FindBin(kPtRange[0]+0.01),shiftsyst_tpc[iC]->FindBin(kTPCmaxPt-0.01)); matsyst_tpc[iC]->GetXaxis()->SetRange(matsyst_tpc[iC]->FindBin(kPtRange[0]+0.01),matsyst_tpc[iC]->FindBin(kTPCmaxPt-0.01)); cutsyst_tpc[iC]->Smooth(1,"R"); countsyst_tpc[iC]->Smooth(1,"R"); shiftsyst_tpc[iC]->Smooth(1,"R"); matsyst_tpc[iC]->Smooth(1,"R"); } for (int iB = 1; iB <= cutsyst_tpc[iC]->GetNbinsX(); ++iB) { if (ptAxis->GetBinCenter(iB) < kPtRange[0] || ptAxis->GetBinCenter(iB) > kPtRange[1]) continue; if (ptAxis->GetBinCenter(iB) > kTPCmaxPt){ cutsyst_tpc[iC]->SetBinContent(iB,0.); matsyst_tpc[iC]->SetBinContent(iB,0.); abssyst_tpc[iC]->SetBinContent(iB,0.); countsyst_tpc[iC]->SetBinContent(iB,0.); shiftsyst_tpc[iC]->SetBinContent(iB,0.); totsyst_tpc[iC]->SetBinContent(iB,0.); } else{ float tot = sqrt( cutsyst_tpc[iC]->GetBinContent(iB) * cutsyst_tpc[iC]->GetBinContent(iB) + matsyst_tpc[iC]->GetBinContent(iB) * matsyst_tpc[iC]->GetBinContent(iB) + abssyst_tpc[iC]->GetBinContent(iB) * abssyst_tpc[iC]->GetBinContent(iB) + countsyst_tpc[iC]->GetBinContent(iB) * countsyst_tpc[iC]->GetBinContent(iB)+ shiftsyst_tpc[iC]->GetBinContent(iB) * shiftsyst_tpc[iC]->GetBinContent(iB) ); totsyst_tpc[iC]->SetBinContent(iB,tot); } } TCanvas summary("summary","Summary"); summary.DrawFrame(0.3,0.,1.3,0.2,";#it{p}_{T} (GeV/#it{c}); Systematics uncertainties"); TLegend leg (0.6,0.56,0.89,0.84); leg.SetBorderSize(0); cutsyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[0]); cutsyst_tpc[iC]->Draw("same"); leg.AddEntry(cutsyst_tpc[iC],"PID and cuts","l"); countsyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[1]); countsyst_tpc[iC]->Draw("same"); leg.AddEntry(countsyst_tpc[iC],"Range broadening","l"); shiftsyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[5]); shiftsyst_tpc[iC]->Draw("same"); leg.AddEntry(shiftsyst_tpc[iC],"Range shifting","l"); matsyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[2]); matsyst_tpc[iC]->Draw("same"); leg.AddEntry(matsyst_tpc[iC],"Material budget","l"); abssyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[3]); abssyst_tpc[iC]->Draw("same"); leg.AddEntry(abssyst_tpc[iC],"Hadronic interaction","l"); totsyst_tpc[iC]->SetLineColor(plotting::kHighContrastColors[4]); totsyst_tpc[iC]->Draw("same"); leg.AddEntry(totsyst_tpc[iC],"Total","l"); totsyst_tpc[iC]->SetLineWidth(2); totsyst_tpc[iC]->Draw("same"); leg.Draw(); species_dir->cd(); cutsyst_tpc[iC]->Write("cutsyst_tpc"); countsyst_tpc[iC]->Write("countsyst_tpc"); shiftsyst_tpc[iC]->Write("shiftsyst_tpc"); abssyst_tpc[iC]->Write("abssyst_tpc"); matsyst_tpc[iC]->Write("matsyst_tpc"); totsyst_tpc[iC]->Write("totsyst_tpc"); summary.Write(); } } output_file.Close(); }
864cee7cb88bcd235ebd224a18215d6a8ae4f95e
ef4b9d960357e5b4e25321f1af1624dcf2fc2a72
/ankit/DesignPatterns/Prototype/Prototype.cpp
7fd0a3f2c7893fe4540099b3984c64e7b6c0e120
[ "Unlicense" ]
permissive
pombredanne/MI
03a7670f15306a14b217730120004b5523afb28a
64861911390d1d60bd5a8c2e2021bba042380bd6
refs/heads/master
2021-01-22T07:47:43.066490
2016-08-17T05:29:25
2016-08-17T05:29:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,810
cpp
/** * Implementation of Prototype Method **/ #include <iostream> #include <map> #include <string> using namespace std; enum RECORD_TYPE_en { CAR, BIKE, PERSON }; /** * Record is the base Prototype */ class Record { public : Record() {} virtual ~Record() {} virtual Record* clone()=0; virtual void print()=0; }; /** * CarRecord is a Concrete Prototype */ class CarRecord : public Record { private: string m_carName; int m_ID; public: CarRecord(string carName, int ID) : Record() , m_carName(carName) ,m_ID(ID) { } CarRecord(const CarRecord& carRecord) : Record(carRecord)//call the base default copy constructor { m_carName = carRecord.m_carName; m_ID = carRecord.m_ID; } ~CarRecord() {} Record* clone() { return new CarRecord(*this); } void print() { cout << "Car Record" << endl << "Name : " << m_carName << endl << "Number: " << m_ID << endl << endl; } }; /** * BikeRecord is the Concrete Prototype */ class BikeRecord : public Record { private : string m_bikeName; int m_ID; public : BikeRecord(string bikeName, int ID) : Record() , m_bikeName(bikeName) , m_ID(ID) { } BikeRecord(const BikeRecord& bikeRecord) : Record(bikeRecord) { m_bikeName = bikeRecord.m_bikeName; m_ID = bikeRecord.m_ID; } ~BikeRecord() {} Record* clone() { return new BikeRecord(*this); } void print() { cout << "Bike Record" << endl << "Name : " << m_bikeName << endl << "Number: " << m_ID << endl << endl; } }; /** * PersonRecord is the Concrete Prototype */ class PersonRecord : public Record { private : string m_personName; int m_age; public : PersonRecord(string personName, int age) : Record() , m_personName(personName) , m_age(age) { } PersonRecord(const PersonRecord& personRecord) : Record(personRecord) { m_personName = personRecord.m_personName; m_age = personRecord.m_age; } ~PersonRecord() {} Record* clone() { return new PersonRecord(*this); } void print() { cout << "Person Record" << endl << "Name : " << m_personName << endl << "Age : " << m_age << endl << endl ; } }; /** * RecordFactory is the client */ class RecordFactory { private : map<RECORD_TYPE_en, Record* > m_recordReference; public : RecordFactory() { m_recordReference[CAR] = new CarRecord("Ferrari", 5050); m_recordReference[BIKE] = new BikeRecord("Yamaha", 2525); m_recordReference[PERSON] = new PersonRecord("Tom", 25); } ~RecordFactory() { delete m_recordReference[CAR]; delete m_recordReference[BIKE]; delete m_recordReference[PERSON]; } Record* createRecord(RECORD_TYPE_en enType) { return m_recordReference[enType]->clone(); } }; int main() { RecordFactory* poRecordFactory = new RecordFactory(); Record* poRecord; poRecord = poRecordFactory->createRecord(CAR); poRecord->print(); delete poRecord; poRecord = poRecordFactory->createRecord(BIKE); poRecord->print(); delete poRecord; poRecord = poRecordFactory->createRecord(PERSON); poRecord->print(); delete poRecord; delete poRecordFactory; return 0; }
247757073cf2dbbc27fc52c127cdbd89db664519
d55d52747adfb7e8944abac10076a99553ad5f8b
/dijkstra.cpp
ba463b622539ec621079d1aaaccd839e516ea6f1
[]
no_license
akevli/FlightPaths
1fd181dd24fbaa0594d95c05870d2b99e4337889
8cef2a8e832fcdf37f923c7da944727e24255caf
refs/heads/master
2023-02-12T19:19:33.204465
2021-01-10T20:39:50
2021-01-10T20:39:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,712
cpp
#include "dijkstra.h" #include <map> #include <iostream> vector<Vertex> Dijkstra::DijkstraSSSP(Graph& graph, Vertex s, Vertex d) { // Initialize variables unordered_map<Vertex, double> distances; unordered_map<Vertex, Vertex> previous; priority_queue<pair<Vertex, double>, vector<pair<Vertex, double>>, Compare> pq; unordered_map<Vertex, bool> visited; for (Vertex v : graph.getVertices()) { distances[v] = 20090; previous[v] = NULL; visited[v] = false; } distances[s] = 0; pq.push(make_pair(s, 0)); // Perform Dijkstra's Algorithm pair<Vertex, double> curr = pq.top(); while (!pq.empty() && curr.first != d) { curr = pq.top(); curr.second = distances[curr.first]; for (Vertex adj : graph.getAdjacent(curr.first)) { if (visited[adj]) { continue; } Edge edge = graph.getEdge(curr.first, adj); double newDistance = edge.getWeight() + distances[curr.first]; if (newDistance < distances[adj]) { pq.push(make_pair(adj, newDistance)); distances[adj] = newDistance; previous[adj] = curr.first; } } pq.pop(); visited[curr.first] = true; } Vertex current = d; vector<Vertex> path; path.insert(path.begin(), d); bool pathExists = true; while (current != NULL && current != s) { path.insert(path.begin(), previous[current]); current = previous[current]; if (current == NULL) { pathExists = false; } } if (!pathExists) { path.clear(); } return path; }
5d46f830e48e3f71d3ce3fa5ce2c01b09493618e
b6f20766a880e04cc5d764aeade1fadab74df0bd
/cop2200-intro-to-c/_reference/lib/hw5_1.h
04be8e4607895573060c32d8f829de50ec4f6dfa
[ "MIT" ]
permissive
chrisbcarl/FAU-Computer-Science
0cf53b5c8bcc3e8b9f0defcbf24469460b8ce19e
98e247bda17bad97a285c01bf2b36af07d9f4239
refs/heads/master
2021-05-11T03:01:22.475340
2019-06-30T23:22:12
2019-06-30T23:22:12
117,902,425
0
0
null
null
null
null
UTF-8
C++
false
false
7,974
h
/******************************************************************************* Name: Christopher Carl Z#: Z23146703 Course: Introduction to C (COP2200, 2016R) Professor: Dr. Feng-Hao Liu Due Date: 16.07.13 Due Time: 23:59 Total Points: 100 Assignment 5: Pointers Description: In this assignment, you are going to turn in a single cpp file. Your goal is to compute modular exponentiation as we will explain below. Then you are going to practice how to design a function that needs to output \two" things. Task 1: You need to design a function that takes in inputs three integers a, e, and n. The function returns an integer which is supposed to be (a^e mod n). Basically, ae is a to the power of e, and \mod" means the modulo operation. Recall in the midterm exam, the operation is %, i.e. a mod b can be written as a%b in C/C++ code. The outcome is the remainder of a divided by b. One nice property about modulo computation is the following: (a + b) mod n = (a mod n) + (b mod n) = ((a mod n) + (b mod n)) mod n; (a * b) mod n = ((a mod n) * (b mod n)) mod n: This property allows you to compute a^e mod n precisely without worrying about over ow. You should note that if you first compute ae directly as an integer, then it is very likely that the result will be larger than what an int can represent. This is typically called as the problem of over ow. On the other hand, if you always apply mod n after one multiplication, then you can bring the number back to the range of [0; n]. This avoids the problem of over ow. Task 2: We want to design a function that takes inputs of 5 integers, a, x, b, y, n, and the function computes a^x mod n and by mod n. However, as we discussed in the class, a function cannot return two integers. To achieve the same effect, we need to apply the technique of pointers we learned in the class. So the task becomes: design a function a function that takes inputs of 5 integers, a, x, b, y, n, and two integer pointers out1 and out2. The function returns void, but needs to write ax to the place that out1 points to and similarly by to the place that out2 points to. This has the same e ect as returning two outputs. Task 3: In the main function, the program asks the user to cin 5 numbers a, x, b, y, n. Then the program calls the function in Task2 to gure out the answer of ax and by. Then it prints the answers. You can design whatever interface you like as long as it gets the spirit! A sample interface looks like the following. *Give me 5 numbers for a, x, b, y, n. *2 2 3 3 5 (This line is input by the user.) *The answers are 4 and 2. LOG: 16.07.06, 16:25 - START 16.07.06, 16:35 - pseudocode phinished 16.07.06, 16:53 - 1st compile 16.07.06, 18:15 - going down the recursive rabbit hole 16.07.06, 19:42 - trying to be clever but really just wasting time 16.07.06, 20:25 - STOP 16.07.10, 18:25 - START 16.07.10, 18:35 - redoing some code 16.07.10, 19:21 - "submittable" with dummy variables 16.07.10, 20:00 - ~75th compile, works 16.07.10, 20:25 - ~100th compile, robust 16.07.10, 20:30 - documentation added 16.07.10, 20:30 - formatting for readability/80char rule 16.07.10, 20:30 - final edits BUG: FOUND: FIXED: DESCIRPTION: B0001 16.07.06,16:54 - BUG: All I get are 0's for the outs. | 16.07.06,16:59 Nothing wrong with inputs, I just put a | 16.07.06,16:59 0 for n, causing there to be no remainders. | 16.07.06,17:21 Stuck on the math of it all | 16.07.06,20:25 The math is unreliable. I need to be more | careful and plan it out better before | tackling this again. | 16.07.10,19:21 FIXED: | The problem is the size of the integer. | It's just not big enough to hold the | data due to overflow, so I need to | deal with this problem in a new way. *******************************************************************************/ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <iostream> #include <string> #include <cmath> int task1(int a, int e, int n); void task2(int a, int x, int b, int y, int n, int &out1, int &out2); void task2(int a, int x, int b, int y, int n, int* out1, int* out2); int main(int args, char* argv[]) { std::string user_response = "y"; while (user_response == "y" || user_response == "Y") { int a, x, b, y, n, out1, out2; int* ptr_out1 = &out1; int* ptr_out2 = &out2; char s[5] = ""; strcpy(s, "%"); printf("Give me 5 numbers for a, x, b, y, n: "); scanf("%d%d%d%d%d", &a, &x, &b, &y, &n); task2(a, x, b, y, n, out1, out2); task2(a, x, b, y, n, ptr_out1, ptr_out2); printf("a = %d, x = %d, b = %d, y = %d, n = %d\n", a, x, b, y, n); printf("For a^x = %d, b^y = %d\n", (int)pow(a, x), (int)pow(b, y)); printf("(%d^%d)%sn = %d; (%d^%d)%sn = %d;.\n", a, x, s, *ptr_out1, b, y, s, *ptr_out2); //printf("(%d^%d)%sn = %d; (%d^%d)%sn = %d;.\n", a, x, s, out1, b, y, s, out2); printf("\n\n"); //catches falling \n or other extraneous chars for a lil more robustness std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Operation completed." << std::endl << std::endl; std::cout << "Would you like to do another calculation? (Y or N): "; std::getline(std::cin, user_response); std::cout << std::endl << std::endl; } return 0; } //pseudocode: /* int func a() return a^e mod n //a^e mod n == for all e total += (a mod n) void func b(int a, x, b, y, n,) and two integer pointers out1 and out2. return two int pointers a^x mod n b^y mod n uses func a() func main() uses only func b() Give me 5 numbers for a, x, b, y, n. 2 2 3 3 5 (This line is input by the user.) The answers are 4 and 2. */ /* Name: task1 Precondition: VARS instantiated in higher function VARS: int a, | int x, | int n RETURNS: int Postcondition: VARS do not contain new data Description: Return (a^x)%n */ int task1(int a, int x, int n) { if (n < 1) return -1; if (a == 1) return a%n; int accumulator = 1; int i = 0; while (i < x) { accumulator *= a%n; i++; } return accumulator%n; } /* Name: task2 (overload 1) Precondition: VARS instantiated in higher function VARS: int a, | int x, | int b, | int y, | int n, | int &out1, | int &out2 RETURNS: void Postcondition: int &out1 contains new data | int &out2 contains new data Description: &out1 = (a^x)%n | &out2 = (b^y)%n */ void task2(int a, int x, int b, int y, int n, int &out1, int &out2) { //& is the address operator, meaning "modify the value" //since the addresses were passed formally, the values are modified out1 = task1(a, x, n); out2 = task1(b, y, n); } /* Name: task2 (overload 2) Precondition: VARS instantiated in higher function VARS: int a, | int x, | int b, | int y, | int n, | int* out1, | int* out2 RETURNS: void Postcondition: int* out1 contains new data | int* out2 contains new data Description: *out1 = (a^x)%n | *out2 = (b^y)%n */ void task2(int a, int x, int b, int y, int n, int* out1, int* out2) { //* is the dereference operator, meaning "modify the value" //since the pointers pointers have values of addresses, the values //are reached through dereferencing to modify the value. *out1 = task1(a, x, n); *out2 = task1(b, y, n); }
41f438c3d69319ea576039930e3b23d878d042c3
b51a16b9dd3d481f20f505ec520eac473db3fe56
/lanqiao/training/399.cc
8c6caf7685e87c4dfd11e2c78774098416fb2f99
[ "MIT" ]
permissive
xsthunder/acm
18b0d23c7456b1f57a9c68f94b8b6c0ce5580349
3c30f31c59030d70462b71ef28c5eee19c6eddd6
refs/heads/master
2021-06-03T23:52:27.140081
2019-05-25T05:38:49
2019-05-25T05:38:49
69,569,543
1
0
null
null
null
null
UTF-8
C++
false
false
945
cc
const bool TEST=1; #include<iostream> #include<cctype> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<map> #include<queue> #include<set> #include<cctype> #include<cstring> #include<utility> #include<cmath> #include<sstream> #include<stack> const int inf=0x7fffffff; #define IF if(TEST) #define FI if(!TEST) #define gts(s) fgets((s),sizeof(s),stdin) #define ALL(s) (s).begin(),(s).end() #define MK(a,b) make_pair((a),(b)) typedef long long int LL; typedef unsigned int U; typedef unsigned long long ULL; using namespace std; typedef pair<int,int> Point; template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ cout<<*(begin++); } printf("\n"); } int c(int k,int n ){ if(k==0||k==n)return 1; else { return c(k,n-1)+c(k-1,n-1); } } void sol(){ int k,n; cin>>k>>n; cout<<c(k,n); } int main() { sol(); return 0; } //399.cc //generated automatically at Fri Feb 10 20:55:07 2017 //by xsthunder
2a6ba82728426e887eae8417ac0a6b04a4c11808
fd2a096e840f28c010a0671c4ede48451b0412fe
/readandwritetofile.cpp
9415f27f45811a68515d26f1daeef3ef0f2225a7
[]
no_license
erikasan/cpp
09bf10e0e304357b6656516dc4547e0fa048560e
412557460a6a7457b15a8890c9d7fe47f9b2b731
refs/heads/master
2022-03-03T23:07:06.670183
2019-10-19T13:35:39
2019-10-19T13:35:39
205,342,215
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
#include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { ifstream infile; ofstream outfile; char *infilename; char *outfilename; infilename = argv[1]; outfilename = argv[2]; outfile.open(outfilename); outfile.close(); return 0; }
09f7de592a99dcff718727864ec5c2a2ecfa7a71
54c367a24a2f4617de12cef8a75d8196cfd4b84d
/src/spikes/spike_gpio_pins.cpp
6f6ed86acc9aa32dc8f60766e700d62fa444d98d
[]
no_license
bvujovic/Vehicle2
861c295c493862fd23864e2822c1027e1c40e377
465dc39d16d8b0d209893b1d28871b67323440ea
refs/heads/master
2022-12-02T03:41:59.285839
2020-07-29T05:28:18
2020-07-29T05:28:18
245,968,382
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
//* Testiranje GPIO pinova koji osim D0-D9 //* pinovi uspesno testirani sa digitalWrite: 1, 3, 10 //* detaljnija prica o pinovima na ESP-u: http://www.thesmarthomehookup.com/post-320/ //* i https://www.instructables.com/id/NodeMCU-ESP8266-Details-and-Pinout/ // #include <Arduino.h> // const int pin = D5; // void setup() // { // pinMode(pin, OUTPUT); // } // void loop() // { // digitalWrite(pin, true); // delay(1000); // digitalWrite(pin, false); // delay(1000); // }
b4e43345317e04bc69f9878992a7e482e51ccc34
f93ec09016e6ff520f5b4a72d2ceda9706c2bb24
/Header/Grid.cpp
3a137b925d7db8a5e1d0f7fead28ab28e0b5e89c
[]
no_license
wilson27561/Cell_Movement
b1c9667f48eabf2db33a8ddd18481d4fce8ed4b6
194db360a6b90c6e082009033e471ea655fc5ed5
refs/heads/master
2023-07-21T01:27:28.822875
2021-09-01T01:26:11
2021-09-01T01:26:11
365,968,812
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
// // Created by Wilson on 2021/5/17. // #include "Grid.h" int Grid::getRowIndx() const { return rowIndx; } void Grid::setRowIndx(int rowIndx) { Grid::rowIndx = rowIndx; } int Grid::getColIndx() const { return colIndx; } void Grid::setColIndx(int colIndx) { Grid::colIndx = colIndx; } int Grid::getSupply() const { return supply; } void Grid::setSupply(int supply) { Grid::supply = supply; } int Grid::getLayIndx() const { return layIndx; } void Grid::setLayIndx(int layIndx) { Grid::layIndx = layIndx; } Grid::~Grid() { } Grid::Grid() {}
02ddf280f5d4256bb00ba7870b375273500543dd
33da785d4c9f5d164952bf9240f32efb35f6e40d
/AudioManager.h
c33a566fffc57c1edfa146b1d20abb3141b57849
[]
no_license
truman0728/rambo2017
ee96af2920d32f7a3d67b8116abe67a80553cfe3
da73efaa1be97e88890736c269bfdfc0c984df96
refs/heads/master
2021-06-14T19:09:58.905964
2017-02-23T04:49:23
2017-02-23T04:49:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
416
h
#ifndef __AUDIOMANAGER_H__ #define __AUDIOMANAGER_H__ #include "cocos2d.h" #include <string> #include "AudioEngine.h" USING_NS_CC; using namespace std; //using namespace experimental; class AudioManager { public: AudioManager(); ~AudioManager(); static void playSound(string keysound); static int playSoundForever(string keysound); static void stopSoundForever(int keysound); }; #endif // __TANK_SOLDIER_H__
9f894d815d966796805d66ffdc7f8858d29f137f
6724bacab72c527a6c1933aca2214a0402ca329c
/apps/output_charm/gm_graph/graph500/splittable_mrg.hpp
df1ce6efc5bb22e0f08af5feeb73d1c2d82fc906
[]
no_license
alexfrolov/Green-Marl
ec08f0f509c35f22a3a0ff54b4f5fdaa784a8f72
a36f7d3ec1684b361e1dc2cc85c282cbd3717e8f
refs/heads/master
2021-01-22T14:39:25.182362
2017-03-26T03:31:03
2017-03-26T03:31:03
18,911,636
1
0
null
null
null
null
UTF-8
C++
false
false
4,692
hpp
/* Copyright (C) 2010 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #ifndef SPLITTABLE_MRG_H #define SPLITTABLE_MRG_H #include <stdint.h> #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "mod_arith.h" /* Multiple recursive generator from L'Ecuyer, P., Blouin, F., and */ /* Couture, R. 1993. A search for good multiple recursive random number */ /* generators. ACM Trans. Model. Comput. Simul. 3, 2 (Apr. 1993), 87-98. */ /* DOI= http://doi.acm.org/10.1145/169702.169698 -- particular generator */ /* used is from table 3, entry for m = 2^31 - 1, k = 5 (same generator */ /* is used in GNU Scientific Library). */ /* See notes at top of splittable_mrg.c for information on this */ /* implementation. */ typedef struct mrg_state { uint_fast32_t z1, z2, z3, z4, z5; } mrg_state; typedef struct mrg_transition_matrix { uint_fast32_t s, t, u, v, w; /* Cache for other parts of matrix (see mrg_update_cache function) */ uint_fast32_t a, b, c, d; } mrg_transition_matrix; // NGE: Contains transition matrix #include "mrg_transitions.cpp" /* r may alias st */ static void mrg_apply_transition(const mrg_transition_matrix* mat, const mrg_state* st, mrg_state* r) { uint_fast32_t o1 = mod_mac_y(mod_mul(mat->d, st->z1), mod_mac4(0, mat->s, st->z2, mat->a, st->z3, mat->b, st->z4, mat->c, st->z5)); uint_fast32_t o2 = mod_mac_y(mod_mac2(0, mat->c, st->z1, mat->w, st->z2), mod_mac3(0, mat->s, st->z3, mat->a, st->z4, mat->b, st->z5)); uint_fast32_t o3 = mod_mac_y(mod_mac3(0, mat->b, st->z1, mat->v, st->z2, mat->w, st->z3), mod_mac2(0, mat->s, st->z4, mat->a, st->z5)); uint_fast32_t o4 = mod_mac_y(mod_mac4(0, mat->a, st->z1, mat->u, st->z2, mat->v, st->z3, mat->w, st->z4), mod_mul(mat->s, st->z5)); uint_fast32_t o5 = mod_mac2(mod_mac3(0, mat->s, st->z1, mat->t, st->z2, mat->u, st->z3), mat->v, st->z4, mat->w, st->z5); r->z1 = o1; r->z2 = o2; r->z3 = o3; r->z4 = o4; r->z5 = o5; } static void mrg_step(const mrg_transition_matrix* mat, mrg_state* state) { mrg_apply_transition(mat, state, state); } static void mrg_orig_step(mrg_state* state) { /* Use original A, not fully optimized yet */ uint_fast32_t new_elt = mod_mac_y(mod_mul_x(state->z1), state->z5); state->z5 = state->z4; state->z4 = state->z3; state->z3 = state->z2; state->z2 = state->z1; state->z1 = new_elt; } static void mrg_skip(mrg_state* state, uint_least64_t exponent_high, uint_least64_t exponent_middle, uint_least64_t exponent_low) { /* fprintf(stderr, "skip(%016" PRIXLEAST64 "%016" PRIXLEAST64 "%016" PRIXLEAST64 ")\n", exponent_high, exponent_middle, exponent_low); */ int byte_index; for (byte_index = 0; exponent_low; ++byte_index, exponent_low >>= 8) { uint_least8_t val = (uint_least8_t)(exponent_low & 0xFF); if (val != 0) mrg_step(&mrg_skip_matrices[byte_index][val], state); } for (byte_index = 8; exponent_middle; ++byte_index, exponent_middle >>= 8) { uint_least8_t val = (uint_least8_t)(exponent_middle & 0xFF); if (val != 0) mrg_step(&mrg_skip_matrices[byte_index][val], state); } for (byte_index = 16; exponent_high; ++byte_index, exponent_high >>= 8) { uint_least8_t val = (uint_least8_t)(exponent_high & 0xFF); if (val != 0) mrg_step(&mrg_skip_matrices[byte_index][val], state); } } /* Returns integer value in [0, 2^31-1) using original transition matrix. */ static uint_fast32_t mrg_get_uint_orig(mrg_state* state) { mrg_orig_step(state); return state->z1; } /* Returns real value in [0, 1) using original transition matrix. */ static double mrg_get_double_orig(mrg_state* state) { return (double)mrg_get_uint_orig(state) * .000000000465661287524579692 /* (2^31 - 1)^(-1) */ + (double)mrg_get_uint_orig(state) * .0000000000000000002168404346990492787 /* (2^31 - 1)^(-2) */ ; } static void mrg_seed(mrg_state* st, const uint_fast32_t seed[5]) { st->z1 = seed[0]; st->z2 = seed[1]; st->z3 = seed[2]; st->z4 = seed[3]; st->z5 = seed[4]; } #endif /* SPLITTABLE_MRG_H */
0967e9ec70c9cbc050e221dba6a07e20fb6389cd
205a8492aa7c5d8f03a06483ca721e730b3911e7
/Engine/HeapManager.cpp
786578e494af3e11d10fd7721bd94a4304e6949f
[]
no_license
HitheshwarMittapelly/GameEngine
a14ceff683a4c137977731aea31c313a713e4305
f660de3e32e4668acf254a2c9d31acf41e605f9f
refs/heads/master
2021-03-29T00:23:58.013411
2020-03-17T07:49:02
2020-03-17T07:49:02
247,908,138
0
0
null
null
null
null
UTF-8
C++
false
false
8,011
cpp
#include "HeapManager.h" #include <cstdint> #include <assert.h> #include <iostream> #include "ConsolePrint.h" using namespace std; HeapManager* HeapManager::createHeapManager(void * i_pMemoryBlock, size_t size, unsigned int numOfdDescriptors) { static HeapManager Instance; Instance.heapMemory.startAddress = reinterpret_cast<uintptr_t>(i_pMemoryBlock); Instance.heapMemory.blockSize = size; Instance.sizeOfTotalMemory = size; Instance.numOfDescriptors = numOfdDescriptors; Instance.setUpDataAndDescriptorBlocks(); return &Instance; } FixedSizeAllocator * HeapManager::getFixedSizeAllocator(size_t size) { if (size <= FSA16.getSize()) return &FSA16; else if (size <= FSA32.getSize()) return &FSA32; else if (size <= FSA96.getSize()) return &FSA96; else return NULL; } void HeapManager::setUpDataAndDescriptorBlocks() { DEBUG_PRINT("Total bytes of memory %lu", sizeOfTotalMemory); sizeOfDescriptorsMemory = numOfDescriptors * sizeof(Descriptor); sizeOfDataMemory = sizeOfTotalMemory - sizeOfDescriptorsMemory; oneByte = reinterpret_cast<char *>(heapMemory.startAddress); oneByte += heapMemory.blockSize; oneByte -= sizeOfDescriptorsMemory; //provide start address and size for descriptor memory descriptorMemoryDescriptor.startAddress = reinterpret_cast<uintptr_t>(oneByte); descriptorMemoryDescriptor.blockSize = sizeOfDescriptorsMemory; //Create Fixed size allocators using the memory in data memory //size 16 FSA setup size_t size = 16; size_t blocks = 100; uintptr_t memory = (heapMemory.startAddress); FSA16.setupInfo(size, blocks, memory); char * oneByte = reinterpret_cast<char *>(memory); oneByte += (size * blocks); memory = reinterpret_cast<uintptr_t>(oneByte); //size 32 FSA setup size = 32; blocks = 200; FSA32.setupInfo(size, blocks, memory); oneByte = reinterpret_cast<char *>(memory); oneByte += (size * blocks); memory = reinterpret_cast<uintptr_t>(oneByte); //size 96 FSA setup size = 96; blocks = 400; FSA96.setupInfo(size, blocks, memory); oneByte = reinterpret_cast<char *>(memory); oneByte += (size * blocks); memory = reinterpret_cast<uintptr_t>(oneByte); //Provide the start address for data memory sizeOfDataMemory -= (size * blocks); heapMemory.startAddress =memory; dataMemoryDescriptor.startAddress = heapMemory.startAddress; dataMemoryDescriptor.blockSize = sizeOfDataMemory ; DEBUG_PRINT("Data Memory itself is at %p ", dataMemoryDescriptor); DEBUG_PRINT("data memory start address %p", dataMemoryDescriptor.startAddress); DEBUG_PRINT("data memory bytes %lu", dataMemoryDescriptor.blockSize); DEBUG_PRINT("Descriptor Memory itself is at %p ", descriptorMemoryDescriptor); DEBUG_PRINT("descriptor memory is at %p", descriptorMemoryDescriptor.startAddress); DEBUG_PRINT("Descriptor memory bytes %lu", descriptorMemoryDescriptor.blockSize); freeList.addDescriptor(&dataMemoryDescriptor); //Generate 2048 descriptors generateDescriptorBlocks(&descriptorMemoryDescriptor); } void HeapManager::generateDescriptorBlocks(Descriptor * descriptorMemoryBlock) { while (descriptorMemoryBlock->blockSize != 0) { oneByte = reinterpret_cast<char *>(descriptorMemoryBlock->startAddress); oneByte += descriptorMemoryBlock->blockSize; oneByte -= sizeof(Descriptor); Descriptor * nextDescriptorBlock = reinterpret_cast<Descriptor *>(oneByte); descriptorFreeList.addDescriptorBlock(nextDescriptorBlock); descriptorMemoryBlock->blockSize -= sizeof(Descriptor); } } void * HeapManager::alloc(size_t size) { Descriptor * freeListReturned; //get the free memory from free list freeListReturned = freeList.getFirstFit(size + guardSize); if (freeListReturned == nullptr) return nullptr; //Allocate memory for new descriptor Descriptor * addToAllocatedList = allocateForDescriptor(sizeof(Descriptor)); if (addToAllocatedList == NULL) return NULL; //iterate through the memory oneByte = reinterpret_cast<char *>(freeListReturned->startAddress); oneByte += freeListReturned->blockSize; oneByte -= (size + guardSize); //allocate start address and block size addToAllocatedList->startAddress = reinterpret_cast<uintptr_t>(oneByte); //Write guardbands oneByte += size; for (size_t i = 0; i < guardSize; i++) { *oneByte = guard; oneByte++; } addToAllocatedList->blockSize = (size + guardSize); freeListReturned->blockSize -= (size + guardSize); //add the new descriptors to the respective lists allocatedList.addDescriptor(addToAllocatedList); freeList.addDescriptor(freeListReturned); return reinterpret_cast<void *>(addToAllocatedList->startAddress); } void * HeapManager::alloc(size_t size, unsigned int alignment) { Descriptor * freeListReturned; //get the free memory from free list freeListReturned = freeList.getFirstFit(size + (size_t)alignment); if (freeListReturned == nullptr) return nullptr; //Allocate memory for new descriptor Descriptor * addToAllocatedList = allocateForDescriptor(sizeof(Descriptor)); //Descriptors run out of memory if (addToAllocatedList == NULL) return NULL; //iterate through the memory oneByte = reinterpret_cast<char *>(freeListReturned->startAddress); oneByte += freeListReturned->blockSize; oneByte -= (size); //Align to the given alignment size_t loopValue = 0; void * alignedAddress = reinterpret_cast<void *>(oneByte); while (!(reinterpret_cast<uintptr_t>(alignedAddress) & (alignment - 1)) == 0) { alignedAddress = (char*)alignedAddress - 1; loopValue = loopValue + (size_t)1; } //allocate start address and block size addToAllocatedList->startAddress = reinterpret_cast<uintptr_t>(alignedAddress); assert(((addToAllocatedList->startAddress) & (alignment - 1)) == 0); addToAllocatedList->blockSize = size + loopValue; freeListReturned->blockSize -= (size + loopValue); //add the new descriptors to the respective lists allocatedList.addDescriptor(addToAllocatedList); freeList.addDescriptor(freeListReturned); //showFreeBlocks(); return reinterpret_cast<void *>(addToAllocatedList->startAddress); } Descriptor * HeapManager::allocateForDescriptor(size_t size) { Descriptor * pReturnedFromList = descriptorFreeList.getNextFromList(); if (pReturnedFromList == nullptr) { DEBUG_PRINT("Descriptors run out of memory"); return NULL; } descriptorFreeList.deleteDescriptorBlock(pReturnedFromList); descriptorAllocatedList.addDescriptorBlock(pReturnedFromList); return pReturnedFromList; } bool HeapManager::free(void * i_ptr) { if (FSA16.contains(i_ptr)) return FSA16.free(i_ptr); else if (FSA32.contains(i_ptr)) return FSA32.free(i_ptr); else if (FSA96.contains(i_ptr)) return FSA96.free(i_ptr); Descriptor * freeingBlock = nullptr; freeingBlock = allocatedList.getDescriptorFromStartAddress(i_ptr); assert(freeingBlock); //delete from allocated list allocatedList.deleteDescriptor(freeingBlock); //add to free list freeList.addDescriptor(freeingBlock); return true; } bool HeapManager::isAllocated(void * i_ptr) { Descriptor * pReturn = nullptr; pReturn = allocatedList.getDescriptorFromStartAddress(i_ptr); if (pReturn) return true; else return false; } bool HeapManager::contains(void * i_ptr) { Descriptor * pReturn = nullptr; pReturn = allocatedList.getDescriptorFromStartAddress(i_ptr); if (!pReturn) { pReturn = freeList.getDescriptorFromStartAddress(i_ptr); if (!pReturn) return false; else return true; } else return true; } void HeapManager::destroy() { freeList.deleteList(); allocatedList.deleteList(); } void HeapManager::showFreeBlocks() { //1 is id for freelist freeList.displayList(1); } void HeapManager::ShowOutstandingAllocations() { //2 is id for allocated list allocatedList.displayList(2); } size_t HeapManager::getLargestFreeBlock() { return freeList.getLargestBlock(); } size_t HeapManager::getTotalFreeMemory() { return freeList.getTotalMemory(); } void HeapManager::collect() { freeList.joinConsecutiveBlocks(&descriptorFreeList, &descriptorAllocatedList); }
2ac024ba9403c0eaa902c185db724ff7c722b8d0
36184239a2d964ed5f587ad8e83f66355edb17aa
/.history/hw2/Counter_20211010064818.h
6fb939317d887449b4c204c280040e98d49c5dab
[]
no_license
xich4932/csci3010
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
refs/heads/master
2023-08-24T04:03:12.748713
2021-10-22T08:22:58
2021-10-22T08:22:58
415,140,207
0
0
null
null
null
null
UTF-8
C++
false
false
2,048
h
#ifndef COUNTER_h #define COUNTER_h #include<iostream> #include<vector> #include<map> //template <typename T> class Counter; template <typename T> class Counter { public: Counter(){}; Counter(std::vector<T> vals){ for(int i = 0; i < vals.size(); i++){ map_counter.insert({vals[i], 0}); } } int Count(){ int sum = 0; for(auto i = map_counter.begin(); i != map_counter.end(); i++){ sum += i->second; } return sum; } int Count(T key){ auto ans = map_counter.find(key); if(ans != map_counter.end()){ return ans->second; } return -1; // return -1; } void Remove(T key){ if(map_counter.find(key) == map_counter.end()){ ; }else{ map_counter.erase(key); } } void Increment(T key){ if(map_counter.find(key) == map_counter.end()){ ; }else{ map_counter[key] += 1; } } void Increment(T key, int n){ if(map_counter.find(key) == map_counter.end()){ ; }else{ map_counter[key] += n; } } void Decrement(T key){ if(map_counter.find(key) == map_counter.end()){ ; }else{ map_counter[key] --; } } void Decrement(T key, int n){ if(map_counter.find(key) == map_counter.end()){ ; }else{ map_counter[key] -= n; } } std::set<T> Keys(){ std:set<T> ans; for(auto i = map_counter.begin(); i != map_counter().end(); ++){ ans.insert(i->first); } return ans; } private: std::map<T, int> map_counter; }; #endif
4ddca8b346c4fd4f090438854cc3734df59f87a4
c13380cdaecc816e8f1f542485cd15262e056d6f
/src/qclavier.cpp
32bfe1dff867842aa0eeb111653715015521ec2a
[]
no_license
hanlinAumonde/projet-comput-Science
e6836db7aac8e3b5f94f9e03d32bba569ae7394a
d42aca53ad7b7841e3bea852cd9244dc1ff01084
refs/heads/main
2023-05-27T17:27:05.406676
2021-05-26T13:07:13
2021-05-26T13:07:13
371,037,555
0
0
null
null
null
null
UTF-8
C++
false
false
12,024
cpp
#include <cmath> #include "qclavier.h" QClavier::QClavier(QCalculateur &calculateur) : calculateur_{calculateur}, sizeButtonPolicy_{QSizePolicy::Minimum, QSizePolicy::Minimum} { setFixedWidth(700); sizeButtonPolicy_.setHorizontalStretch(0); sizeButtonPolicy_.setVerticalStretch(0); sizeButtonPolicy_.setHeightForWidth((new QPushButton())->sizePolicy().hasHeightForWidth()); mainLayout_ = new QVBoxLayout{}; QHBoxLayout *subLayout_1_ = new QHBoxLayout{}; QHBoxLayout *subLayout_2_ = new QHBoxLayout{}; QHBoxLayout *subLayout_3_ = new QHBoxLayout{}; QHBoxLayout *subLayout_4_ = new QHBoxLayout{}; subWidget_1_ = new QWidget{}; subWidget_2_ = new QWidget{}; subWidget_3_ = new QWidget{}; subWidget_4_ = new QWidget{}; mainLayout_->setSpacing(0); setLayout(mainLayout_); subWidget_1_->setLayout(subLayout_1_); subWidget_2_->setLayout(subLayout_2_); subWidget_3_->setLayout(subLayout_3_); subWidget_4_->setLayout(subLayout_4_); subLayout_1_->setContentsMargins(5, 5, 5, 5); subLayout_2_->setContentsMargins(5, 5, 5, 5); subLayout_3_->setContentsMargins(5, 5, 5, 5); subLayout_4_->setContentsMargins(5, 5, 5, 5); mainLayout_->addWidget(subWidget_4_); mainLayout_->addWidget(subWidget_3_); mainLayout_->addWidget(subWidget_2_); mainLayout_->addWidget(subWidget_1_); creerPileClavier(); creerSimpleClavier(); creerFonctionClavier(); creerEvaluationClavier(); creerCondtionClavier(); creerLogiqueClavier(); creerUserClavier(); } void QClavier::creerSimpleClavier() { QGridLayout *simpleLayout = new QGridLayout{}; simpleClavier_ = new QFrame{this}; simpleClavier_->setLayout(simpleLayout); simpleClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); simpleClavier_->setMidLineWidth(0); // simpleLayout->setSizeConstraint(QLayout::SetFixedSize); subWidget_1_->layout()->addWidget(simpleClavier_); for (size_t i = 0; i <= 9; i++) { creerButton(QString::number(i), SLOT(addTextClicked())); } creerButton(tr("["), SLOT(addTextClicked())); creerButton(tr("]"), SLOT(addTextClicked())); creerButton(tr("."), SLOT(addTextClicked())); creerButton(tr("__"), SLOT(addTextClicked())); creerButton(tr("DEL"), SLOT(deleteClicked())); creerButton(tr("+"), SLOT(autoOperatorClicked())); creerButton(tr("-"), SLOT(autoOperatorClicked())); creerButton(tr("*"), SLOT(autoOperatorClicked())); creerButton(tr("/"), SLOT(autoOperatorClicked())); creerButton(tr("ENTREE"), SLOT(enterClicked())); for (size_t i = 1; i <= 9; i++) { int rang = (i - 1) / 3; int colonne = (i - 1) % 3; simpleLayout->addWidget(keyboardMap_.at(QString::number(i)), rang, colonne); } simpleLayout->addWidget(keyboardMap_["0"], 3, 0); simpleLayout->addWidget(keyboardMap_["["], 3, 1); simpleLayout->addWidget(keyboardMap_["]"], 3, 2); simpleLayout->addWidget(keyboardMap_["__"], 0, 3); simpleLayout->addWidget(keyboardMap_["DEL"], 0, 4); simpleLayout->addWidget(keyboardMap_["+"], 1, 3); simpleLayout->addWidget(keyboardMap_["-"], 1, 4); simpleLayout->addWidget(keyboardMap_["*"], 2, 3); simpleLayout->addWidget(keyboardMap_["/"], 2, 4); simpleLayout->addWidget(keyboardMap_["."], 3, 3); simpleLayout->addWidget(keyboardMap_["ENTREE"], 3, 4); } void QClavier::creerPileClavier() { QGridLayout *pileLayout = new QGridLayout{}; pileClavier_ = new QFrame{this}; pileClavier_->setLayout(pileLayout); pileClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); pileClavier_->setMidLineWidth(0); subWidget_1_->layout()->addWidget(pileClavier_); // subLayout_1_->addWidget(pileClavier_); creerButton(tr("DUP"), SLOT(addTextClicked())); creerButton(tr("DROP"), SLOT(addTextClicked())); creerButton(tr("SWAP"), SLOT(addTextClicked())); creerButton(tr("CLEAR"), SLOT(addTextClicked())); creerButton(tr("UNDO"), SLOT(autoOperatorClicked())); creerButton(tr("REDO"), SLOT(autoOperatorClicked())); pileLayout->addWidget(keyboardMap_["DUP"], 0, 1); pileLayout->addWidget(keyboardMap_["DROP"], 1, 1); pileLayout->addWidget(keyboardMap_["SWAP"], 2, 1); pileLayout->addWidget(keyboardMap_["CLEAR"], 3, 1); keyboardMap_["UNDO"]->setSizePolicy(sizeButtonPolicy_); keyboardMap_["REDO"]->setSizePolicy(sizeButtonPolicy_); pileLayout->addWidget(keyboardMap_["UNDO"], 0, 0, 2, 1); pileLayout->addWidget(keyboardMap_["REDO"], 2, 0, 2, 1); } void QClavier::creerFonctionClavier() { QGridLayout *fonctionLayout = new QGridLayout{}; fonctionClavier_ = new QFrame{this}; QSizePolicy sp = fonctionClavier_->sizePolicy(); sp.setRetainSizeWhenHidden(true); fonctionClavier_->setSizePolicy(sp); fonctionClavier_->setLayout(fonctionLayout); fonctionClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); fonctionClavier_->setMidLineWidth(0); subWidget_2_->layout()->addWidget(fonctionClavier_); QStringList fonctionList = {"DIV", "MOD", "NUM", "DEN", "NEG", "SIN", "COS", "TAN", "IM", "ARCSIN", "ARCCOS", "ARCTAN", "SQRT", "POW", "EXP", "LN"}; for (auto &fonction : fonctionList) { creerButton(fonction, SLOT(addTextClicked())); } for (size_t i = 0; i < fonctionList.size() - 2; i++) { int range = i / 4; int colonne = i % 4; fonctionLayout->addWidget(keyboardMap_[fonctionList[i]], range, colonne); } keyboardMap_["EXP"]->setSizePolicy(sizeButtonPolicy_); keyboardMap_["LN"]->setSizePolicy(sizeButtonPolicy_); fonctionLayout->addWidget(keyboardMap_["POW"], 0, 4); fonctionLayout->addWidget(keyboardMap_["SQRT"], 0, 5); fonctionLayout->addWidget(keyboardMap_["EXP"], 1, 4, 2, 1); fonctionLayout->addWidget(keyboardMap_["LN"], 1, 5, 2, 1); } void QClavier::creerLogiqueClavier() { QGridLayout *logiqueLayout = new QGridLayout{}; logiqueClavier_ = new QFrame{this}; logiqueClavier_->setLayout(logiqueLayout); logiqueClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); logiqueClavier_->setMidLineWidth(0); subWidget_3_->layout()->addWidget(logiqueClavier_); QStringList logiqueList = {"==", "<", ">", "!=", "=<", ">=", "AND", "OR", "NOT"}; for (auto &logique : logiqueList) { creerButton(logique, SLOT(addTextClicked())); } for (size_t i = 0; i < logiqueList.size(); i++) { int range = i / 3; int colonne = i % 3; logiqueLayout->addWidget(keyboardMap_[logiqueList[i]], range, colonne); } } void QClavier::creerEvaluationClavier() { QGridLayout *evaluationLayout = new QGridLayout{}; evaluationClavier_ = new QFrame{this}; evaluationClavier_->setLayout(evaluationLayout); evaluationClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); evaluationClavier_->setMidLineWidth(0); subWidget_3_->layout()->addWidget(evaluationClavier_); QStringList evaluationList = {"EVAL", "STO", "FORGET"}; for (auto &evaluation : evaluationList) { creerButton(evaluation, SLOT(addTextClicked())); } for (size_t i = 0; i < evaluationList.size(); i++) { int range = i; int colonne = 0; evaluationLayout->addWidget(keyboardMap_[evaluationList[i]], range, colonne); } } void QClavier::creerCondtionClavier() { QGridLayout *conditionLayout = new QGridLayout{}; conditionClavier_ = new QFrame{this}; conditionClavier_->setLayout(conditionLayout); conditionClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); conditionClavier_->setMidLineWidth(0); subWidget_3_->layout()->addWidget(conditionClavier_); QStringList conditionList = {"IFT", "IFTE", "WHILE"}; for (auto &condtion : conditionList) { creerButton(condtion, SLOT(addTextClicked())); } for (size_t i = 0; i < conditionList.size(); i++) { int range = i; int colonne = 0; conditionLayout->addWidget(keyboardMap_[conditionList[i]], range, colonne); } } void QClavier::creerUserClavier() { variableLayout_ = new QGridLayout{}; userVariableClavier_ = new QFrame{this}; userVariableClavier_->setLayout(variableLayout_); userVariableClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); userVariableClavier_->setMidLineWidth(0); subWidget_4_->layout()->addWidget(userVariableClavier_); fonctionLayout_ = new QGridLayout{}; userFonctionClavier_ = new QFrame{this}; userFonctionClavier_->setLayout(fonctionLayout_); userFonctionClavier_->setFrameStyle(QFrame::Box | QFrame::Sunken); userFonctionClavier_->setMidLineWidth(0); subWidget_4_->layout()->addWidget(userFonctionClavier_); } void QClavier::updateUserClavier() { unsigned int maxColonne = 4; QLayoutItem *item; while ((item = variableLayout_->takeAt(0)) != nullptr) { delete item->widget(); delete item; } while ((item = fonctionLayout_->takeAt(0)) != nullptr) { delete item->widget(); delete item; } int currentVarible = 0, currentFonction = 0; for (auto itr = identifieurMap_->begin(); itr != identifieurMap_->end(); itr++) { QString buttonText = itr->second->affichage().mid(1, itr->second->affichage().length() - 2); QPushButton *button = new QPushButton(buttonText); connect(button, SIGNAL(clicked()), this, SLOT(evaluerVarEtProgramme())); if (itr->second->getLitterale()->getType() == TypeLitterale::PROGRAMME) { int range = currentFonction / maxColonne; int colonne = currentFonction % maxColonne; fonctionLayout_->addWidget(button, range, colonne); currentFonction++; } else { int range = currentVarible / maxColonne; int colonne = currentVarible % maxColonne; variableLayout_->addWidget(button, range, colonne); currentVarible++; } } } void QClavier::creerButton(const QString &text, const char *member) { keyboardMap_[text] = new QPushButton{text}; connect(keyboardMap_[text], SIGNAL(clicked()), this, member); } void QClavier::deleteClicked() { QLineEdit &commandeBar = calculateur_.getCommandBar(); QString text = commandeBar.text(); if (text != "") { commandeBar.setText(text.left(text.length() - 1)); } } void QClavier::autoOperatorClicked() { try { auto clickedButton = qobject_cast<QPushButton *>(sender()); calculerAutoOperateur(clickedButton->text()); } catch (const CalculateurException &e) { calculateur_.setMessage(e.what()); } } bool QClavier::calculerAutoOperateur(QString op) { QLineEdit &commandeBar = calculateur_.getCommandBar(); calculateur_.getControleur().traiterCommandBar(commandeBar.text() + " " + op); calculateur_.renderVuePile(); calculateur_.setMessage(""); commandeBar.clear(); return true; } void QClavier::evaluerVarEtProgramme() { try { auto clickedButton = qobject_cast<QPushButton *>(sender()); calculateur_.getControleur().traiterCommandBar("'" + clickedButton->text() + "'" + " EVAL"); calculateur_.renderVuePile(); calculateur_.setMessage(""); } catch (const CalculateurException &e) { calculateur_.setMessage(e.what()); } } void QClavier::addTextClicked() { auto clickedButton = qobject_cast<QPushButton *>(sender()); QLineEdit &commandBar = calculateur_.getCommandBar(); if (clickedButton->text() == "__") { commandBar.setText(commandBar.text() + " "); return; } commandBar.setText(commandBar.text() + clickedButton->text()); } void QClavier::enterClicked() { try { calculateur_.calculerAutoOperateur(); } catch (const CalculateurException &e) { calculateur_.setMessage(e.what()); } }
7c247ecd702c765c9557eddf04302f863efe579e
3fe2c64583f85a9fea45faee5e062f9fe656c6ae
/gui/MainFrm.cpp
a1bb7b57916f033c27694e8ca2ece45ea762276d
[]
no_license
manageryzy/cuda-graphic
33fcfcde74ebf0c038eae09f3899045234018dd4
0a0e6d9f77532f3555870f6a278151dbc5ae596c
refs/heads/master
2021-01-12T12:12:21.514499
2016-11-12T09:33:39
2016-11-12T09:33:39
72,357,961
0
0
null
null
null
null
UTF-8
C++
false
false
6,720
cpp
// This MFC Samples source code demonstrates using MFC Microsoft Office Fluent User Interface // (the "Fluent UI") and is provided only as referential material to supplement the // Microsoft Foundation Classes Reference and related electronic documentation // included with the MFC C++ library software. // License terms to copy, use or distribute the Fluent UI are available separately. // To learn more about our Fluent UI licensing program, please visit // http://go.microsoft.com/fwlink/?LinkId=238214. // // Copyright (C) Microsoft Corporation // All rights reserved. // MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "gui.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWndEx) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWndEx) ON_WM_CREATE() ON_WM_SETTINGCHANGE() ON_COMMAND(ID_BTN_UNDO, &CMainFrame::OnUndo) END_MESSAGE_MAP() // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWndEx::OnCreate(lpCreateStruct) == -1) return -1; BOOL bNameValid; m_wndRibbonBar.Create(this); m_wndRibbonBar.LoadFromResource(IDR_RIBBON); if (!m_wndStatusBar.Create(this)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } CString strTitlePane1; CString strTitlePane2; bNameValid = strTitlePane1.LoadString(IDS_STATUS_PANE1); ASSERT(bNameValid); bNameValid = strTitlePane2.LoadString(IDS_STATUS_PANE2); ASSERT(bNameValid); m_wndStatusBar.AddElement(new CMFCRibbonStatusBarPane(ID_STATUSBAR_PANE1, strTitlePane1, TRUE), strTitlePane1); m_wndStatusBar.AddExtendedElement(new CMFCRibbonStatusBarPane(ID_STATUSBAR_PANE2, strTitlePane2, TRUE), strTitlePane2); // enable Visual Studio 2005 style docking window behavior CDockingManager::SetDockingMode(DT_SMART); // enable Visual Studio 2005 style docking window auto-hide behavior EnableAutoHidePanes(CBRS_ALIGN_ANY); // Load menu item image (not placed on any standard toolbars): CMFCToolBar::AddToolBarForImageCollection(IDR_MENU_IMAGES, theApp.m_bHiColorIcons ? IDB_MENU_IMAGES_24 : 0); // create docking windows if (!CreateDockingWindows()) { TRACE0("Failed to create docking windows\n"); return -1; } // m_wndFileView.EnableDocking(CBRS_ALIGN_ANY); m_wndSceneView.EnableDocking(CBRS_ALIGN_ANY); // DockPane(&m_wndFileView); CDockablePane* pTabbedBar = NULL; // m_wndSceneView.AttachToTabWnd(&m_wndFileView, DM_SHOW, TRUE, &pTabbedBar); DockPane(&m_wndSceneView); m_wndOutput.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndOutput); m_wndProperties.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndProperties); // set the visual manager used to draw all user interface elements CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWndEx::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs cs.style = WS_OVERLAPPED | WS_CAPTION | FWS_ADDTOTITLE | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_MAXIMIZE | WS_SYSMENU; return TRUE; } BOOL CMainFrame::CreateDockingWindows() { BOOL bNameValid; // Create class view CString strClassView; bNameValid = strClassView.LoadString(IDS_SCENE_VIEW); ASSERT(bNameValid); if (!m_wndSceneView.Create(strClassView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_CLASSVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Class View window\n"); return FALSE; // failed to create } // Create file view CString strFileView; bNameValid = strFileView.LoadString(IDS_FILE_VIEW); ASSERT(bNameValid); //if (!m_wndFileView.Create(strFileView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_FILEVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI)) //{ // TRACE0("Failed to create File View window\n"); // return FALSE; // failed to create //} // Create output window CString strOutputWnd; bNameValid = strOutputWnd.LoadString(IDS_OUTPUT_WND); ASSERT(bNameValid); if (!m_wndOutput.Create(strOutputWnd, this, CRect(0, 0, 100, 100), TRUE, ID_VIEW_OUTPUTWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_BOTTOM | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Output window\n"); return FALSE; // failed to create } // Create properties window CString strPropertiesWnd; bNameValid = strPropertiesWnd.LoadString(IDS_PROPERTIES_WND); ASSERT(bNameValid); if (!m_wndProperties.Create(strPropertiesWnd, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_PROPERTIESWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_RIGHT | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Properties window\n"); return FALSE; // failed to create } SetDockingWindowIcons(theApp.m_bHiColorIcons); return TRUE; } void CMainFrame::SetDockingWindowIcons(BOOL bHiColorIcons) { //HICON hFileViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_FILE_VIEW_HC : IDI_FILE_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); //m_wndFileView.SetIcon(hFileViewIcon, FALSE); HICON hClassViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_CLASS_VIEW_HC : IDI_CLASS_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndSceneView.SetIcon(hClassViewIcon, FALSE); HICON hOutputBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_OUTPUT_WND_HC : IDI_OUTPUT_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndOutput.SetIcon(hOutputBarIcon, FALSE); HICON hPropertiesBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_PROPERTIES_WND_HC : IDI_PROPERTIES_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndProperties.SetIcon(hPropertiesBarIcon, FALSE); } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWndEx::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWndEx::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { CFrameWndEx::OnSettingChange(uFlags, lpszSection); m_wndOutput.UpdateFonts(); } void CMainFrame::OnUndo() { MessageBeep(0); // TODO: Add your command handler code here }
f0c8d08fff6063814c8f5fa4d48b10b130be8f7a
45a7aa9699b573bfe8d65ff7b981bd8ceca3482d
/nodo_t.cpp
605d8686e98f4cbc7dc69852aa5f4bc106ffe8ed
[]
no_license
abernalf/prct_aeda
46e8b51760aaac9d86652e0e1d8e9aa08cc4b7f4
37ee204a5f355ce91492c06e3f675face53b79e5
refs/heads/master
2023-04-03T09:20:53.363344
2016-02-25T16:01:19
2016-02-25T16:01:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include "nodo_t.hpp" #include <iostream> #include <cstdio> using namespace std; namespace AEDA { nodo_t::nodo_t() : next_(NULL) {} nodo_t::~nodo_t(void) {} void nodo_t::set_next(nodo_t* next) { next_ = next; } nodo_t* nodo_t::get_next(void) const { return next_; } void nodo_t::set_prev(nodo_t* prev){ prev_ = prev; } nodo_t* nodo_t::get_prev() const{ return prev_; } void nodo_t::insertar_intermedio(nodo_t* n,nodo_t* prev,nodo_t* next){ prev->set_next(n); next->set_prev(n); n->set_next(next); n->set_prev(prev); } }
a0cd7661d180b9d54a4a956436fe46a62b06a5b9
fc97cb15ae3008c9495fe8414ed2adc1d9e54d3e
/build-Mainwindow-Desktop_Qt_5_3_MinGW_32bit-Debug/debug/moc_hall.cpp
17fbe289f4b0bcce77afbf8946fe4acdb13d7c38
[]
no_license
Drakenhielm/Biobokningssystem
dd1ae92d24d1e1709390a9babfb9082ecd677337
facfed2c18678398366b4b00dc59ebc62b5b08de
refs/heads/master
2021-01-25T10:44:08.571269
2014-12-18T10:53:47
2014-12-18T10:53:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,147
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'hall.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Mainwindow/add_hall/hall.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #include <QtCore/QList> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'hall.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_hall_t { QByteArrayData data[13]; char stringdata[152]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_hall_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_hall_t qt_meta_stringdata_hall = { { QT_MOC_LITERAL(0, 0, 4), QT_MOC_LITERAL(1, 5, 7), QT_MOC_LITERAL(2, 13, 0), QT_MOC_LITERAL(3, 14, 4), QT_MOC_LITERAL(4, 19, 10), QT_MOC_LITERAL(5, 30, 11), QT_MOC_LITERAL(6, 42, 19), QT_MOC_LITERAL(7, 62, 5), QT_MOC_LITERAL(8, 68, 8), QT_MOC_LITERAL(9, 77, 6), QT_MOC_LITERAL(10, 84, 21), QT_MOC_LITERAL(11, 106, 20), QT_MOC_LITERAL(12, 127, 24) }, "hall\0addHall\0\0name\0screenSize\0soundSystem\0" "QList<QList<bool> >\0seats\0editHall\0" "hallID\0setLabelNumberOfSeats\0" "on_AddButton_clicked\0on_cancel_Button_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_hall[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: name, argc, parameters, tag, flags 1, 4, 39, 2, 0x06 /* Public */, 8, 5, 48, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 0, 59, 2, 0x08 /* Private */, 11, 0, 60, 2, 0x08 /* Private */, 12, 0, 61, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::QString, 0x80000000 | 6, 3, 4, 5, 7, QMetaType::Void, QMetaType::Int, QMetaType::QString, QMetaType::QString, QMetaType::QString, 0x80000000 | 6, 9, 3, 4, 5, 7, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void hall::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { hall *_t = static_cast<hall *>(_o); switch (_id) { case 0: _t->addHall((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QString(*)>(_a[3])),(*reinterpret_cast< const QList<QList<bool> >(*)>(_a[4]))); break; case 1: _t->editHall((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QString(*)>(_a[3])),(*reinterpret_cast< const QString(*)>(_a[4])),(*reinterpret_cast< const QList<QList<bool> >(*)>(_a[5]))); break; case 2: _t->setLabelNumberOfSeats(); break; case 3: _t->on_AddButton_clicked(); break; case 4: _t->on_cancel_Button_clicked(); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 3: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QList<QList<bool> > >(); break; } break; case 1: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 4: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QList<QList<bool> > >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (hall::*_t)(const QString & , const QString & , const QString & , const QList<QList<bool> > & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&hall::addHall)) { *result = 0; } } { typedef void (hall::*_t)(int , const QString & , const QString & , const QString & , const QList<QList<bool> > & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&hall::editHall)) { *result = 1; } } } } const QMetaObject hall::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_hall.data, qt_meta_data_hall, qt_static_metacall, 0, 0} }; const QMetaObject *hall::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *hall::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_hall.stringdata)) return static_cast<void*>(const_cast< hall*>(this)); return QDialog::qt_metacast(_clname); } int hall::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } return _id; } // SIGNAL 0 void hall::addHall(const QString & _t1, const QString & _t2, const QString & _t3, const QList<QList<bool> > & _t4) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void hall::editHall(int _t1, const QString & _t2, const QString & _t3, const QString & _t4, const QList<QList<bool> > & _t5) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)), const_cast<void*>(reinterpret_cast<const void*>(&_t5)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_END_MOC_NAMESPACE
6047415ea6f64535cad334200876087a8ccade66
b6c204fe2b878c1acbad669d7deb331022ba5fb2
/YuvLibrary/src/main/cpp/source/row_common.cc
d9efe01579d870b6f8d1467181dc9bbf5d2ef7d9
[]
no_license
erleizh/libyuv-for-android
ee3f58d7ab026399fd6c5954982aa1ce4a541560
242d3a418bed1d647ec3f60e6da8f600506cffd9
refs/heads/master
2021-09-22T22:30:52.106916
2018-09-18T03:20:04
2018-09-18T03:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
87,523
cc
/* * Copyright 2011 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "../include/libyuv/row.h" #include <string.h> // For memcpy and memset. #include "../include/libyuv/basic_types.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // llvm x86 is poor at ternary operator, so use branchless min/max. #define USE_BRANCHLESS 1 #if USE_BRANCHLESS static __inline int32 clamp0(int32 v) { return ((-(v) >> 31) & (v)); } static __inline int32 clamp255(int32 v) { return (((255 - (v)) >> 31) | (v)) & 255; } static __inline uint32 Clamp(int32 val) { int v = clamp0(val); return (uint32)(clamp255(v)); } static __inline uint32 Abs(int32 v) { int m = v >> 31; return (v + m) ^ m; } #else // USE_BRANCHLESS static __inline int32 clamp0(int32 v) { return (v < 0) ? 0 : v; } static __inline int32 clamp255(int32 v) { return (v > 255) ? 255 : v; } static __inline uint32 Clamp(int32 val) { int v = clamp0(val); return (uint32)(clamp255(v)); } static __inline uint32 Abs(int32 v) { return (v < 0) ? -v : v; } #endif // USE_BRANCHLESS #ifdef LIBYUV_LITTLE_ENDIAN #define WRITEWORD(p, v) *(uint32*)(p) = v #else static inline void WRITEWORD(uint8* p, uint32 v) { p[0] = (uint8)(v & 255); p[1] = (uint8)((v >> 8) & 255); p[2] = (uint8)((v >> 16) & 255); p[3] = (uint8)((v >> 24) & 255); } #endif void RGB24ToARGBRow_C(const uint8* src_rgb24, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_rgb24[0]; uint8 g = src_rgb24[1]; uint8 r = src_rgb24[2]; dst_argb[0] = b; dst_argb[1] = g; dst_argb[2] = r; dst_argb[3] = 255u; dst_argb += 4; src_rgb24 += 3; } } void RAWToARGBRow_C(const uint8* src_raw, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 r = src_raw[0]; uint8 g = src_raw[1]; uint8 b = src_raw[2]; dst_argb[0] = b; dst_argb[1] = g; dst_argb[2] = r; dst_argb[3] = 255u; dst_argb += 4; src_raw += 3; } } void RGB565ToARGBRow_C(const uint8* src_rgb565, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_rgb565[0] & 0x1f; uint8 g = (src_rgb565[0] >> 5) | ((src_rgb565[1] & 0x07) << 3); uint8 r = src_rgb565[1] >> 3; dst_argb[0] = (b << 3) | (b >> 2); dst_argb[1] = (g << 2) | (g >> 4); dst_argb[2] = (r << 3) | (r >> 2); dst_argb[3] = 255u; dst_argb += 4; src_rgb565 += 2; } } void ARGB1555ToARGBRow_C(const uint8* src_argb1555, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb1555[0] & 0x1f; uint8 g = (src_argb1555[0] >> 5) | ((src_argb1555[1] & 0x03) << 3); uint8 r = (src_argb1555[1] & 0x7c) >> 2; uint8 a = src_argb1555[1] >> 7; dst_argb[0] = (b << 3) | (b >> 2); dst_argb[1] = (g << 3) | (g >> 2); dst_argb[2] = (r << 3) | (r >> 2); dst_argb[3] = -a; dst_argb += 4; src_argb1555 += 2; } } void ARGB4444ToARGBRow_C(const uint8* src_argb4444, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb4444[0] & 0x0f; uint8 g = src_argb4444[0] >> 4; uint8 r = src_argb4444[1] & 0x0f; uint8 a = src_argb4444[1] >> 4; dst_argb[0] = (b << 4) | b; dst_argb[1] = (g << 4) | g; dst_argb[2] = (r << 4) | r; dst_argb[3] = (a << 4) | a; dst_argb += 4; src_argb4444 += 2; } } void ARGBToRGB24Row_C(const uint8* src_argb, uint8* dst_rgb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb[0]; uint8 g = src_argb[1]; uint8 r = src_argb[2]; dst_rgb[0] = b; dst_rgb[1] = g; dst_rgb[2] = r; dst_rgb += 3; src_argb += 4; } } void ARGBToRAWRow_C(const uint8* src_argb, uint8* dst_rgb, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb[0]; uint8 g = src_argb[1]; uint8 r = src_argb[2]; dst_rgb[0] = r; dst_rgb[1] = g; dst_rgb[2] = b; dst_rgb += 3; src_argb += 4; } } void ARGBToRGB565Row_C(const uint8* src_argb, uint8* dst_rgb, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_argb[0] >> 3; uint8 g0 = src_argb[1] >> 2; uint8 r0 = src_argb[2] >> 3; uint8 b1 = src_argb[4] >> 3; uint8 g1 = src_argb[5] >> 2; uint8 r1 = src_argb[6] >> 3; WRITEWORD(dst_rgb, b0 | (g0 << 5) | (r0 << 11) | (b1 << 16) | (g1 << 21) | (r1 << 27)); dst_rgb += 4; src_argb += 8; } if (width & 1) { uint8 b0 = src_argb[0] >> 3; uint8 g0 = src_argb[1] >> 2; uint8 r0 = src_argb[2] >> 3; *(uint16*)(dst_rgb) = b0 | (g0 << 5) | (r0 << 11); } } // dither4 is a row of 4 values from 4x4 dither matrix. // The 4x4 matrix contains values to increase RGB. When converting to // fewer bits (565) this provides an ordered dither. // The order in the 4x4 matrix in first byte is upper left. // The 4 values are passed as an int, then referenced as an array, so // endian will not affect order of the original matrix. But the dither4 // will containing the first pixel in the lower byte for little endian // or the upper byte for big endian. void ARGBToRGB565DitherRow_C(const uint8* src_argb, uint8* dst_rgb, const uint32 dither4, int width) { int x; for (x = 0; x < width - 1; x += 2) { int dither0 = ((const unsigned char*)(&dither4))[x & 3]; int dither1 = ((const unsigned char*)(&dither4))[(x + 1) & 3]; uint8 b0 = clamp255(src_argb[0] + dither0) >> 3; uint8 g0 = clamp255(src_argb[1] + dither0) >> 2; uint8 r0 = clamp255(src_argb[2] + dither0) >> 3; uint8 b1 = clamp255(src_argb[4] + dither1) >> 3; uint8 g1 = clamp255(src_argb[5] + dither1) >> 2; uint8 r1 = clamp255(src_argb[6] + dither1) >> 3; WRITEWORD(dst_rgb, b0 | (g0 << 5) | (r0 << 11) | (b1 << 16) | (g1 << 21) | (r1 << 27)); dst_rgb += 4; src_argb += 8; } if (width & 1) { int dither0 = ((const unsigned char*)(&dither4))[(width - 1) & 3]; uint8 b0 = clamp255(src_argb[0] + dither0) >> 3; uint8 g0 = clamp255(src_argb[1] + dither0) >> 2; uint8 r0 = clamp255(src_argb[2] + dither0) >> 3; *(uint16*)(dst_rgb) = b0 | (g0 << 5) | (r0 << 11); } } void ARGBToARGB1555Row_C(const uint8* src_argb, uint8* dst_rgb, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_argb[0] >> 3; uint8 g0 = src_argb[1] >> 3; uint8 r0 = src_argb[2] >> 3; uint8 a0 = src_argb[3] >> 7; uint8 b1 = src_argb[4] >> 3; uint8 g1 = src_argb[5] >> 3; uint8 r1 = src_argb[6] >> 3; uint8 a1 = src_argb[7] >> 7; *(uint32*)(dst_rgb) = b0 | (g0 << 5) | (r0 << 10) | (a0 << 15) | (b1 << 16) | (g1 << 21) | (r1 << 26) | (a1 << 31); dst_rgb += 4; src_argb += 8; } if (width & 1) { uint8 b0 = src_argb[0] >> 3; uint8 g0 = src_argb[1] >> 3; uint8 r0 = src_argb[2] >> 3; uint8 a0 = src_argb[3] >> 7; *(uint16*)(dst_rgb) = b0 | (g0 << 5) | (r0 << 10) | (a0 << 15); } } void ARGBToARGB4444Row_C(const uint8* src_argb, uint8* dst_rgb, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_argb[0] >> 4; uint8 g0 = src_argb[1] >> 4; uint8 r0 = src_argb[2] >> 4; uint8 a0 = src_argb[3] >> 4; uint8 b1 = src_argb[4] >> 4; uint8 g1 = src_argb[5] >> 4; uint8 r1 = src_argb[6] >> 4; uint8 a1 = src_argb[7] >> 4; *(uint32*)(dst_rgb) = b0 | (g0 << 4) | (r0 << 8) | (a0 << 12) | (b1 << 16) | (g1 << 20) | (r1 << 24) | (a1 << 28); dst_rgb += 4; src_argb += 8; } if (width & 1) { uint8 b0 = src_argb[0] >> 4; uint8 g0 = src_argb[1] >> 4; uint8 r0 = src_argb[2] >> 4; uint8 a0 = src_argb[3] >> 4; *(uint16*)(dst_rgb) = b0 | (g0 << 4) | (r0 << 8) | (a0 << 12); } } static __inline int RGBToY(uint8 r, uint8 g, uint8 b) { return (66 * r + 129 * g + 25 * b + 0x1080) >> 8; } static __inline int RGBToU(uint8 r, uint8 g, uint8 b) { return (112 * b - 74 * g - 38 * r + 0x8080) >> 8; } static __inline int RGBToV(uint8 r, uint8 g, uint8 b) { return (112 * r - 94 * g - 18 * b + 0x8080) >> 8; } #define MAKEROWY(NAME, R, G, B, BPP) \ void NAME ## ToYRow_C(const uint8* src_argb0, uint8* dst_y, int width) { \ int x; \ for (x = 0; x < width; ++x) { \ dst_y[0] = RGBToY(src_argb0[R], src_argb0[G], src_argb0[B]); \ src_argb0 += BPP; \ dst_y += 1; \ } \ } \ void NAME ## ToUVRow_C(const uint8* src_rgb0, int src_stride_rgb, \ uint8* dst_u, uint8* dst_v, int width) { \ const uint8* src_rgb1 = src_rgb0 + src_stride_rgb; \ int x; \ for (x = 0; x < width - 1; x += 2) { \ uint8 ab = (src_rgb0[B] + src_rgb0[B + BPP] + \ src_rgb1[B] + src_rgb1[B + BPP]) >> 2; \ uint8 ag = (src_rgb0[G] + src_rgb0[G + BPP] + \ src_rgb1[G] + src_rgb1[G + BPP]) >> 2; \ uint8 ar = (src_rgb0[R] + src_rgb0[R + BPP] + \ src_rgb1[R] + src_rgb1[R + BPP]) >> 2; \ dst_u[0] = RGBToU(ar, ag, ab); \ dst_v[0] = RGBToV(ar, ag, ab); \ src_rgb0 += BPP * 2; \ src_rgb1 += BPP * 2; \ dst_u += 1; \ dst_v += 1; \ } \ if (width & 1) { \ uint8 ab = (src_rgb0[B] + src_rgb1[B]) >> 1; \ uint8 ag = (src_rgb0[G] + src_rgb1[G]) >> 1; \ uint8 ar = (src_rgb0[R] + src_rgb1[R]) >> 1; \ dst_u[0] = RGBToU(ar, ag, ab); \ dst_v[0] = RGBToV(ar, ag, ab); \ } \ } MAKEROWY(ARGB, 2, 1, 0, 4) MAKEROWY(BGRA, 1, 2, 3, 4) MAKEROWY(ABGR, 0, 1, 2, 4) MAKEROWY(RGBA, 3, 2, 1, 4) MAKEROWY(RGB24, 2, 1, 0, 3) MAKEROWY(RAW, 0, 1, 2, 3) #undef MAKEROWY // JPeg uses a variation on BT.601-1 full range // y = 0.29900 * r + 0.58700 * g + 0.11400 * b // u = -0.16874 * r - 0.33126 * g + 0.50000 * b + center // v = 0.50000 * r - 0.41869 * g - 0.08131 * b + center // BT.601 Mpeg range uses: // b 0.1016 * 255 = 25.908 = 25 // g 0.5078 * 255 = 129.489 = 129 // r 0.2578 * 255 = 65.739 = 66 // JPeg 8 bit Y (not used): // b 0.11400 * 256 = 29.184 = 29 // g 0.58700 * 256 = 150.272 = 150 // r 0.29900 * 256 = 76.544 = 77 // JPeg 7 bit Y: // b 0.11400 * 128 = 14.592 = 15 // g 0.58700 * 128 = 75.136 = 75 // r 0.29900 * 128 = 38.272 = 38 // JPeg 8 bit U: // b 0.50000 * 255 = 127.5 = 127 // g -0.33126 * 255 = -84.4713 = -84 // r -0.16874 * 255 = -43.0287 = -43 // JPeg 8 bit V: // b -0.08131 * 255 = -20.73405 = -20 // g -0.41869 * 255 = -106.76595 = -107 // r 0.50000 * 255 = 127.5 = 127 static __inline int RGBToYJ(uint8 r, uint8 g, uint8 b) { return (38 * r + 75 * g + 15 * b + 64) >> 7; } static __inline int RGBToUJ(uint8 r, uint8 g, uint8 b) { return (127 * b - 84 * g - 43 * r + 0x8080) >> 8; } static __inline int RGBToVJ(uint8 r, uint8 g, uint8 b) { return (127 * r - 107 * g - 20 * b + 0x8080) >> 8; } #define AVGB(a, b) (((a) + (b) + 1) >> 1) #define MAKEROWYJ(NAME, R, G, B, BPP) \ void NAME ## ToYJRow_C(const uint8* src_argb0, uint8* dst_y, int width) { \ int x; \ for (x = 0; x < width; ++x) { \ dst_y[0] = RGBToYJ(src_argb0[R], src_argb0[G], src_argb0[B]); \ src_argb0 += BPP; \ dst_y += 1; \ } \ } \ void NAME ## ToUVJRow_C(const uint8* src_rgb0, int src_stride_rgb, \ uint8* dst_u, uint8* dst_v, int width) { \ const uint8* src_rgb1 = src_rgb0 + src_stride_rgb; \ int x; \ for (x = 0; x < width - 1; x += 2) { \ uint8 ab = AVGB(AVGB(src_rgb0[B], src_rgb1[B]), \ AVGB(src_rgb0[B + BPP], src_rgb1[B + BPP])); \ uint8 ag = AVGB(AVGB(src_rgb0[G], src_rgb1[G]), \ AVGB(src_rgb0[G + BPP], src_rgb1[G + BPP])); \ uint8 ar = AVGB(AVGB(src_rgb0[R], src_rgb1[R]), \ AVGB(src_rgb0[R + BPP], src_rgb1[R + BPP])); \ dst_u[0] = RGBToUJ(ar, ag, ab); \ dst_v[0] = RGBToVJ(ar, ag, ab); \ src_rgb0 += BPP * 2; \ src_rgb1 += BPP * 2; \ dst_u += 1; \ dst_v += 1; \ } \ if (width & 1) { \ uint8 ab = AVGB(src_rgb0[B], src_rgb1[B]); \ uint8 ag = AVGB(src_rgb0[G], src_rgb1[G]); \ uint8 ar = AVGB(src_rgb0[R], src_rgb1[R]); \ dst_u[0] = RGBToUJ(ar, ag, ab); \ dst_v[0] = RGBToVJ(ar, ag, ab); \ } \ } MAKEROWYJ(ARGB, 2, 1, 0, 4) #undef MAKEROWYJ void ARGBToUVJ422Row_C(const uint8* src_argb, uint8* dst_u, uint8* dst_v, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 ab = (src_argb[0] + src_argb[4]) >> 1; uint8 ag = (src_argb[1] + src_argb[5]) >> 1; uint8 ar = (src_argb[2] + src_argb[6]) >> 1; dst_u[0] = RGBToUJ(ar, ag, ab); dst_v[0] = RGBToVJ(ar, ag, ab); src_argb += 8; dst_u += 1; dst_v += 1; } if (width & 1) { uint8 ab = src_argb[0]; uint8 ag = src_argb[1]; uint8 ar = src_argb[2]; dst_u[0] = RGBToUJ(ar, ag, ab); dst_v[0] = RGBToVJ(ar, ag, ab); } } void RGB565ToYRow_C(const uint8* src_rgb565, uint8* dst_y, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_rgb565[0] & 0x1f; uint8 g = (src_rgb565[0] >> 5) | ((src_rgb565[1] & 0x07) << 3); uint8 r = src_rgb565[1] >> 3; b = (b << 3) | (b >> 2); g = (g << 2) | (g >> 4); r = (r << 3) | (r >> 2); dst_y[0] = RGBToY(r, g, b); src_rgb565 += 2; dst_y += 1; } } void ARGB1555ToYRow_C(const uint8* src_argb1555, uint8* dst_y, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb1555[0] & 0x1f; uint8 g = (src_argb1555[0] >> 5) | ((src_argb1555[1] & 0x03) << 3); uint8 r = (src_argb1555[1] & 0x7c) >> 2; b = (b << 3) | (b >> 2); g = (g << 3) | (g >> 2); r = (r << 3) | (r >> 2); dst_y[0] = RGBToY(r, g, b); src_argb1555 += 2; dst_y += 1; } } void ARGB4444ToYRow_C(const uint8* src_argb4444, uint8* dst_y, int width) { int x; for (x = 0; x < width; ++x) { uint8 b = src_argb4444[0] & 0x0f; uint8 g = src_argb4444[0] >> 4; uint8 r = src_argb4444[1] & 0x0f; b = (b << 4) | b; g = (g << 4) | g; r = (r << 4) | r; dst_y[0] = RGBToY(r, g, b); src_argb4444 += 2; dst_y += 1; } } void RGB565ToUVRow_C(const uint8* src_rgb565, int src_stride_rgb565, uint8* dst_u, uint8* dst_v, int width) { const uint8* next_rgb565 = src_rgb565 + src_stride_rgb565; int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_rgb565[0] & 0x1f; uint8 g0 = (src_rgb565[0] >> 5) | ((src_rgb565[1] & 0x07) << 3); uint8 r0 = src_rgb565[1] >> 3; uint8 b1 = src_rgb565[2] & 0x1f; uint8 g1 = (src_rgb565[2] >> 5) | ((src_rgb565[3] & 0x07) << 3); uint8 r1 = src_rgb565[3] >> 3; uint8 b2 = next_rgb565[0] & 0x1f; uint8 g2 = (next_rgb565[0] >> 5) | ((next_rgb565[1] & 0x07) << 3); uint8 r2 = next_rgb565[1] >> 3; uint8 b3 = next_rgb565[2] & 0x1f; uint8 g3 = (next_rgb565[2] >> 5) | ((next_rgb565[3] & 0x07) << 3); uint8 r3 = next_rgb565[3] >> 3; uint8 b = (b0 + b1 + b2 + b3); // 565 * 4 = 787. uint8 g = (g0 + g1 + g2 + g3); uint8 r = (r0 + r1 + r2 + r3); b = (b << 1) | (b >> 6); // 787 -> 888. r = (r << 1) | (r >> 6); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); src_rgb565 += 4; next_rgb565 += 4; dst_u += 1; dst_v += 1; } if (width & 1) { uint8 b0 = src_rgb565[0] & 0x1f; uint8 g0 = (src_rgb565[0] >> 5) | ((src_rgb565[1] & 0x07) << 3); uint8 r0 = src_rgb565[1] >> 3; uint8 b2 = next_rgb565[0] & 0x1f; uint8 g2 = (next_rgb565[0] >> 5) | ((next_rgb565[1] & 0x07) << 3); uint8 r2 = next_rgb565[1] >> 3; uint8 b = (b0 + b2); // 565 * 2 = 676. uint8 g = (g0 + g2); uint8 r = (r0 + r2); b = (b << 2) | (b >> 4); // 676 -> 888 g = (g << 1) | (g >> 6); r = (r << 2) | (r >> 4); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); } } void ARGB1555ToUVRow_C(const uint8* src_argb1555, int src_stride_argb1555, uint8* dst_u, uint8* dst_v, int width) { const uint8* next_argb1555 = src_argb1555 + src_stride_argb1555; int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_argb1555[0] & 0x1f; uint8 g0 = (src_argb1555[0] >> 5) | ((src_argb1555[1] & 0x03) << 3); uint8 r0 = (src_argb1555[1] & 0x7c) >> 2; uint8 b1 = src_argb1555[2] & 0x1f; uint8 g1 = (src_argb1555[2] >> 5) | ((src_argb1555[3] & 0x03) << 3); uint8 r1 = (src_argb1555[3] & 0x7c) >> 2; uint8 b2 = next_argb1555[0] & 0x1f; uint8 g2 = (next_argb1555[0] >> 5) | ((next_argb1555[1] & 0x03) << 3); uint8 r2 = (next_argb1555[1] & 0x7c) >> 2; uint8 b3 = next_argb1555[2] & 0x1f; uint8 g3 = (next_argb1555[2] >> 5) | ((next_argb1555[3] & 0x03) << 3); uint8 r3 = (next_argb1555[3] & 0x7c) >> 2; uint8 b = (b0 + b1 + b2 + b3); // 555 * 4 = 777. uint8 g = (g0 + g1 + g2 + g3); uint8 r = (r0 + r1 + r2 + r3); b = (b << 1) | (b >> 6); // 777 -> 888. g = (g << 1) | (g >> 6); r = (r << 1) | (r >> 6); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); src_argb1555 += 4; next_argb1555 += 4; dst_u += 1; dst_v += 1; } if (width & 1) { uint8 b0 = src_argb1555[0] & 0x1f; uint8 g0 = (src_argb1555[0] >> 5) | ((src_argb1555[1] & 0x03) << 3); uint8 r0 = (src_argb1555[1] & 0x7c) >> 2; uint8 b2 = next_argb1555[0] & 0x1f; uint8 g2 = (next_argb1555[0] >> 5) | ((next_argb1555[1] & 0x03) << 3); uint8 r2 = next_argb1555[1] >> 3; uint8 b = (b0 + b2); // 555 * 2 = 666. uint8 g = (g0 + g2); uint8 r = (r0 + r2); b = (b << 2) | (b >> 4); // 666 -> 888. g = (g << 2) | (g >> 4); r = (r << 2) | (r >> 4); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); } } void ARGB4444ToUVRow_C(const uint8* src_argb4444, int src_stride_argb4444, uint8* dst_u, uint8* dst_v, int width) { const uint8* next_argb4444 = src_argb4444 + src_stride_argb4444; int x; for (x = 0; x < width - 1; x += 2) { uint8 b0 = src_argb4444[0] & 0x0f; uint8 g0 = src_argb4444[0] >> 4; uint8 r0 = src_argb4444[1] & 0x0f; uint8 b1 = src_argb4444[2] & 0x0f; uint8 g1 = src_argb4444[2] >> 4; uint8 r1 = src_argb4444[3] & 0x0f; uint8 b2 = next_argb4444[0] & 0x0f; uint8 g2 = next_argb4444[0] >> 4; uint8 r2 = next_argb4444[1] & 0x0f; uint8 b3 = next_argb4444[2] & 0x0f; uint8 g3 = next_argb4444[2] >> 4; uint8 r3 = next_argb4444[3] & 0x0f; uint8 b = (b0 + b1 + b2 + b3); // 444 * 4 = 666. uint8 g = (g0 + g1 + g2 + g3); uint8 r = (r0 + r1 + r2 + r3); b = (b << 2) | (b >> 4); // 666 -> 888. g = (g << 2) | (g >> 4); r = (r << 2) | (r >> 4); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); src_argb4444 += 4; next_argb4444 += 4; dst_u += 1; dst_v += 1; } if (width & 1) { uint8 b0 = src_argb4444[0] & 0x0f; uint8 g0 = src_argb4444[0] >> 4; uint8 r0 = src_argb4444[1] & 0x0f; uint8 b2 = next_argb4444[0] & 0x0f; uint8 g2 = next_argb4444[0] >> 4; uint8 r2 = next_argb4444[1] & 0x0f; uint8 b = (b0 + b2); // 444 * 2 = 555. uint8 g = (g0 + g2); uint8 r = (r0 + r2); b = (b << 3) | (b >> 2); // 555 -> 888. g = (g << 3) | (g >> 2); r = (r << 3) | (r >> 2); dst_u[0] = RGBToU(r, g, b); dst_v[0] = RGBToV(r, g, b); } } void ARGBToUV444Row_C(const uint8* src_argb, uint8* dst_u, uint8* dst_v, int width) { int x; for (x = 0; x < width; ++x) { uint8 ab = src_argb[0]; uint8 ag = src_argb[1]; uint8 ar = src_argb[2]; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); src_argb += 4; dst_u += 1; dst_v += 1; } } void ARGBToUV422Row_C(const uint8* src_argb, uint8* dst_u, uint8* dst_v, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 ab = (src_argb[0] + src_argb[4]) >> 1; uint8 ag = (src_argb[1] + src_argb[5]) >> 1; uint8 ar = (src_argb[2] + src_argb[6]) >> 1; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); src_argb += 8; dst_u += 1; dst_v += 1; } if (width & 1) { uint8 ab = src_argb[0]; uint8 ag = src_argb[1]; uint8 ar = src_argb[2]; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); } } void ARGBToUV411Row_C(const uint8* src_argb, uint8* dst_u, uint8* dst_v, int width) { int x; for (x = 0; x < width - 3; x += 4) { uint8 ab = (src_argb[0] + src_argb[4] + src_argb[8] + src_argb[12]) >> 2; uint8 ag = (src_argb[1] + src_argb[5] + src_argb[9] + src_argb[13]) >> 2; uint8 ar = (src_argb[2] + src_argb[6] + src_argb[10] + src_argb[14]) >> 2; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); src_argb += 16; dst_u += 1; dst_v += 1; } if ((width & 3) == 3) { uint8 ab = (src_argb[0] + src_argb[4] + src_argb[8]) / 3; uint8 ag = (src_argb[1] + src_argb[5] + src_argb[9]) / 3; uint8 ar = (src_argb[2] + src_argb[6] + src_argb[10]) / 3; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); } else if ((width & 3) == 2) { uint8 ab = (src_argb[0] + src_argb[4]) >> 1; uint8 ag = (src_argb[1] + src_argb[5]) >> 1; uint8 ar = (src_argb[2] + src_argb[6]) >> 1; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); } else if ((width & 3) == 1) { uint8 ab = src_argb[0]; uint8 ag = src_argb[1]; uint8 ar = src_argb[2]; dst_u[0] = RGBToU(ar, ag, ab); dst_v[0] = RGBToV(ar, ag, ab); } } void ARGBGrayRow_C(const uint8* src_argb, uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { uint8 y = RGBToYJ(src_argb[2], src_argb[1], src_argb[0]); dst_argb[2] = dst_argb[1] = dst_argb[0] = y; dst_argb[3] = src_argb[3]; dst_argb += 4; src_argb += 4; } } // Convert a row of image to Sepia tone. void ARGBSepiaRow_C(uint8* dst_argb, int width) { int x; for (x = 0; x < width; ++x) { int b = dst_argb[0]; int g = dst_argb[1]; int r = dst_argb[2]; int sb = (b * 17 + g * 68 + r * 35) >> 7; int sg = (b * 22 + g * 88 + r * 45) >> 7; int sr = (b * 24 + g * 98 + r * 50) >> 7; // b does not over flow. a is preserved from original. dst_argb[0] = sb; dst_argb[1] = clamp255(sg); dst_argb[2] = clamp255(sr); dst_argb += 4; } } // Apply color matrix to a row of image. Matrix is signed. // TODO(fbarchard): Consider adding rounding (+32). void ARGBColorMatrixRow_C(const uint8* src_argb, uint8* dst_argb, const int8* matrix_argb, int width) { int x; for (x = 0; x < width; ++x) { int b = src_argb[0]; int g = src_argb[1]; int r = src_argb[2]; int a = src_argb[3]; int sb = (b * matrix_argb[0] + g * matrix_argb[1] + r * matrix_argb[2] + a * matrix_argb[3]) >> 6; int sg = (b * matrix_argb[4] + g * matrix_argb[5] + r * matrix_argb[6] + a * matrix_argb[7]) >> 6; int sr = (b * matrix_argb[8] + g * matrix_argb[9] + r * matrix_argb[10] + a * matrix_argb[11]) >> 6; int sa = (b * matrix_argb[12] + g * matrix_argb[13] + r * matrix_argb[14] + a * matrix_argb[15]) >> 6; dst_argb[0] = Clamp(sb); dst_argb[1] = Clamp(sg); dst_argb[2] = Clamp(sr); dst_argb[3] = Clamp(sa); src_argb += 4; dst_argb += 4; } } // Apply color table to a row of image. void ARGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width) { int x; for (x = 0; x < width; ++x) { int b = dst_argb[0]; int g = dst_argb[1]; int r = dst_argb[2]; int a = dst_argb[3]; dst_argb[0] = table_argb[b * 4 + 0]; dst_argb[1] = table_argb[g * 4 + 1]; dst_argb[2] = table_argb[r * 4 + 2]; dst_argb[3] = table_argb[a * 4 + 3]; dst_argb += 4; } } // Apply color table to a row of image. void RGBColorTableRow_C(uint8* dst_argb, const uint8* table_argb, int width) { int x; for (x = 0; x < width; ++x) { int b = dst_argb[0]; int g = dst_argb[1]; int r = dst_argb[2]; dst_argb[0] = table_argb[b * 4 + 0]; dst_argb[1] = table_argb[g * 4 + 1]; dst_argb[2] = table_argb[r * 4 + 2]; dst_argb += 4; } } void ARGBQuantizeRow_C(uint8* dst_argb, int scale, int interval_size, int interval_offset, int width) { int x; for (x = 0; x < width; ++x) { int b = dst_argb[0]; int g = dst_argb[1]; int r = dst_argb[2]; dst_argb[0] = (b * scale >> 16) * interval_size + interval_offset; dst_argb[1] = (g * scale >> 16) * interval_size + interval_offset; dst_argb[2] = (r * scale >> 16) * interval_size + interval_offset; dst_argb += 4; } } #define REPEAT8(v) (v) | ((v) << 8) #define SHADE(f, v) v * f >> 24 void ARGBShadeRow_C(const uint8* src_argb, uint8* dst_argb, int width, uint32 value) { const uint32 b_scale = REPEAT8(value & 0xff); const uint32 g_scale = REPEAT8((value >> 8) & 0xff); const uint32 r_scale = REPEAT8((value >> 16) & 0xff); const uint32 a_scale = REPEAT8(value >> 24); int i; for (i = 0; i < width; ++i) { const uint32 b = REPEAT8(src_argb[0]); const uint32 g = REPEAT8(src_argb[1]); const uint32 r = REPEAT8(src_argb[2]); const uint32 a = REPEAT8(src_argb[3]); dst_argb[0] = SHADE(b, b_scale); dst_argb[1] = SHADE(g, g_scale); dst_argb[2] = SHADE(r, r_scale); dst_argb[3] = SHADE(a, a_scale); src_argb += 4; dst_argb += 4; } } #undef REPEAT8 #undef SHADE #define REPEAT8(v) (v) | ((v) << 8) #define SHADE(f, v) v * f >> 16 void ARGBMultiplyRow_C(const uint8* src_argb0, const uint8* src_argb1, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { const uint32 b = REPEAT8(src_argb0[0]); const uint32 g = REPEAT8(src_argb0[1]); const uint32 r = REPEAT8(src_argb0[2]); const uint32 a = REPEAT8(src_argb0[3]); const uint32 b_scale = src_argb1[0]; const uint32 g_scale = src_argb1[1]; const uint32 r_scale = src_argb1[2]; const uint32 a_scale = src_argb1[3]; dst_argb[0] = SHADE(b, b_scale); dst_argb[1] = SHADE(g, g_scale); dst_argb[2] = SHADE(r, r_scale); dst_argb[3] = SHADE(a, a_scale); src_argb0 += 4; src_argb1 += 4; dst_argb += 4; } } #undef REPEAT8 #undef SHADE #define SHADE(f, v) clamp255(v + f) void ARGBAddRow_C(const uint8* src_argb0, const uint8* src_argb1, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { const int b = src_argb0[0]; const int g = src_argb0[1]; const int r = src_argb0[2]; const int a = src_argb0[3]; const int b_add = src_argb1[0]; const int g_add = src_argb1[1]; const int r_add = src_argb1[2]; const int a_add = src_argb1[3]; dst_argb[0] = SHADE(b, b_add); dst_argb[1] = SHADE(g, g_add); dst_argb[2] = SHADE(r, r_add); dst_argb[3] = SHADE(a, a_add); src_argb0 += 4; src_argb1 += 4; dst_argb += 4; } } #undef SHADE #define SHADE(f, v) clamp0(f - v) void ARGBSubtractRow_C(const uint8* src_argb0, const uint8* src_argb1, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { const int b = src_argb0[0]; const int g = src_argb0[1]; const int r = src_argb0[2]; const int a = src_argb0[3]; const int b_sub = src_argb1[0]; const int g_sub = src_argb1[1]; const int r_sub = src_argb1[2]; const int a_sub = src_argb1[3]; dst_argb[0] = SHADE(b, b_sub); dst_argb[1] = SHADE(g, g_sub); dst_argb[2] = SHADE(r, r_sub); dst_argb[3] = SHADE(a, a_sub); src_argb0 += 4; src_argb1 += 4; dst_argb += 4; } } #undef SHADE // Sobel functions which mimics SSSE3. void SobelXRow_C(const uint8* src_y0, const uint8* src_y1, const uint8* src_y2, uint8* dst_sobelx, int width) { int i; for (i = 0; i < width; ++i) { int a = src_y0[i]; int b = src_y1[i]; int c = src_y2[i]; int a_sub = src_y0[i + 2]; int b_sub = src_y1[i + 2]; int c_sub = src_y2[i + 2]; int a_diff = a - a_sub; int b_diff = b - b_sub; int c_diff = c - c_sub; int sobel = Abs(a_diff + b_diff * 2 + c_diff); dst_sobelx[i] = (uint8)(clamp255(sobel)); } } void SobelYRow_C(const uint8* src_y0, const uint8* src_y1, uint8* dst_sobely, int width) { int i; for (i = 0; i < width; ++i) { int a = src_y0[i + 0]; int b = src_y0[i + 1]; int c = src_y0[i + 2]; int a_sub = src_y1[i + 0]; int b_sub = src_y1[i + 1]; int c_sub = src_y1[i + 2]; int a_diff = a - a_sub; int b_diff = b - b_sub; int c_diff = c - c_sub; int sobel = Abs(a_diff + b_diff * 2 + c_diff); dst_sobely[i] = (uint8)(clamp255(sobel)); } } void SobelRow_C(const uint8* src_sobelx, const uint8* src_sobely, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { int r = src_sobelx[i]; int b = src_sobely[i]; int s = clamp255(r + b); dst_argb[0] = (uint8)(s); dst_argb[1] = (uint8)(s); dst_argb[2] = (uint8)(s); dst_argb[3] = (uint8)(255u); dst_argb += 4; } } void SobelToPlaneRow_C(const uint8* src_sobelx, const uint8* src_sobely, uint8* dst_y, int width) { int i; for (i = 0; i < width; ++i) { int r = src_sobelx[i]; int b = src_sobely[i]; int s = clamp255(r + b); dst_y[i] = (uint8)(s); } } void SobelXYRow_C(const uint8* src_sobelx, const uint8* src_sobely, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { int r = src_sobelx[i]; int b = src_sobely[i]; int g = clamp255(r + b); dst_argb[0] = (uint8)(b); dst_argb[1] = (uint8)(g); dst_argb[2] = (uint8)(r); dst_argb[3] = (uint8)(255u); dst_argb += 4; } } void J400ToARGBRow_C(const uint8* src_y, uint8* dst_argb, int width) { // Copy a Y to RGB. int x; for (x = 0; x < width; ++x) { uint8 y = src_y[0]; dst_argb[2] = dst_argb[1] = dst_argb[0] = y; dst_argb[3] = 255u; dst_argb += 4; ++src_y; } } // BT.601 YUV to RGB reference // R = (Y - 16) * 1.164 - V * -1.596 // G = (Y - 16) * 1.164 - U * 0.391 - V * 0.813 // B = (Y - 16) * 1.164 - U * -2.018 // Y contribution to R,G,B. Scale and bias. #define YG 18997 /* round(1.164 * 64 * 256 * 256 / 257) */ #define YGB -1160 /* 1.164 * 64 * -16 + 64 / 2 */ // U and V contributions to R,G,B. #define UB -128 /* max(-128, round(-2.018 * 64)) */ #define UG 25 /* round(0.391 * 64) */ #define VG 52 /* round(0.813 * 64) */ #define VR -102 /* round(-1.596 * 64) */ // Bias values to subtract 16 from Y and 128 from U and V. #define BB (UB * 128 + YGB) #define BG (UG * 128 + VG * 128 + YGB) #define BR (VR * 128 + YGB) // BT.601 constants for YUV to RGB. // TODO(fbarchard): Unify these structures to be platform independent. // TODO(fbarchard): Generate SIMD structures from float matrix. // BT601 constants for YUV to RGB. #if defined(__aarch64__) const YuvConstants SIMD_ALIGNED(kYuvIConstants) = { { -UB, -VR, -UB, -VR, -UB, -VR, -UB, -VR }, { -UB, -VR, -UB, -VR, -UB, -VR, -UB, -VR }, { UG, VG, UG, VG, UG, VG, UG, VG }, { UG, VG, UG, VG, UG, VG, UG, VG }, { BB, BG, BR, 0, 0, 0, 0, 0 }, { 0x0101 * YG, 0, 0, 0 } }; #elif defined(__arm__) const YuvConstants SIMD_ALIGNED(kYuvIConstants) = { { -UB, -UB, -UB, -UB, -VR, -VR, -VR, -VR, 0, 0, 0, 0, 0, 0, 0, 0 }, { UG, UG, UG, UG, VG, VG, VG, VG, 0, 0, 0, 0, 0, 0, 0, 0 }, { BB, BG, BR, 0, 0, 0, 0, 0 }, { 0x0101 * YG, 0, 0, 0 } }; #else const YuvConstants SIMD_ALIGNED(kYuvIConstants) = { { UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0, UB, 0 }, { UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG, UG, VG }, { 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR, 0, VR }, { BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB, BB }, { BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG, BG }, { BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR, BR }, { YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG, YG } }; #endif // C reference code that mimics the YUV assembly. static __inline void YuvPixel(uint8 y, uint8 u, uint8 v, uint8* b, uint8* g, uint8* r, const struct YuvConstants* yuvconstants) { #if defined(__aarch64__) int ub = -yuvconstants->kUVToRB[0]; int ug = yuvconstants->kUVToG[0]; int vg = yuvconstants->kUVToG[1]; int vr = -yuvconstants->kUVToRB[1]; int bb = yuvconstants->kUVBiasBGR[0]; int bg = yuvconstants->kUVBiasBGR[1]; int br = yuvconstants->kUVBiasBGR[2]; int yg = yuvconstants->kYToRgb[0] / 0x0101; #elif defined(__arm__) int ub = -yuvconstants->kUVToRB[0]; int ug = yuvconstants->kUVToG[0]; int vg = yuvconstants->kUVToG[4]; int vr = -yuvconstants->kUVToRB[4]; int bb = yuvconstants->kUVBiasBGR[0]; int bg = yuvconstants->kUVBiasBGR[1]; int br = yuvconstants->kUVBiasBGR[2]; int yg = yuvconstants->kYToRgb[0] / 0x0101; #else int ub = yuvconstants->kUVToB[0]; int ug = yuvconstants->kUVToG[0]; int vg = yuvconstants->kUVToG[1]; int vr = yuvconstants->kUVToR[1]; int bb = yuvconstants->kUVBiasB[0]; int bg = yuvconstants->kUVBiasG[0]; int br = yuvconstants->kUVBiasR[0]; int yg = yuvconstants->kYToRgb[0]; #endif uint32 y1 = (uint32)(y * 0x0101 * yg) >> 16; *b = Clamp((int32)(-(u * ub ) + y1 + bb) >> 6); *g = Clamp((int32)(-(u * ug + v * vg) + y1 + bg) >> 6); *r = Clamp((int32)(-( v * vr) + y1 + br) >> 6); } // C reference code that mimics the YUV assembly. static __inline void YPixel(uint8 y, uint8* b, uint8* g, uint8* r) { uint32 y1 = (uint32)(y * 0x0101 * YG) >> 16; *b = Clamp((int32)(y1 + YGB) >> 6); *g = Clamp((int32)(y1 + YGB) >> 6); *r = Clamp((int32)(y1 + YGB) >> 6); } #undef BB #undef BG #undef BR #undef YGB #undef UB #undef UG #undef VG #undef VR #undef YG // JPEG YUV to RGB reference // * R = Y - V * -1.40200 // * G = Y - U * 0.34414 - V * 0.71414 // * B = Y - U * -1.77200 // Y contribution to R,G,B. Scale and bias. #define YGJ 16320 /* round(1.000 * 64 * 256 * 256 / 257) */ #define YGBJ 32 /* 64 / 2 */ // U and V contributions to R,G,B. #define UBJ -113 /* round(-1.77200 * 64) */ #define UGJ 22 /* round(0.34414 * 64) */ #define VGJ 46 /* round(0.71414 * 64) */ #define VRJ -90 /* round(-1.40200 * 64) */ // Bias values to round, and subtract 128 from U and V. #define BBJ (UBJ * 128 + YGBJ) #define BGJ (UGJ * 128 + VGJ * 128 + YGBJ) #define BRJ (VRJ * 128 + YGBJ) // JPEG constants for YUV to RGB. #if defined(__aarch64__) const YuvConstants SIMD_ALIGNED(kYuvJConstants) = { { -UBJ, -VRJ, -UBJ, -VRJ, -UBJ, -VRJ, -UBJ, -VRJ }, { -UBJ, -VRJ, -UBJ, -VRJ, -UBJ, -VRJ, -UBJ, -VRJ }, { UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ }, { UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ }, { BBJ, BGJ, BRJ, 0, 0, 0, 0, 0 }, { 0x0101 * YGJ, 0, 0, 0 } }; #elif defined(__arm__) const YuvConstants SIMD_ALIGNED(kYuvJConstants) = { { -UBJ, -UBJ, -UBJ, -UBJ, -VRJ, -VRJ, -VRJ, -VRJ, 0, 0, 0, 0, 0, 0, 0, 0 }, { UGJ, UGJ, UGJ, UGJ, VGJ, VGJ, VGJ, VGJ, 0, 0, 0, 0, 0, 0, 0, 0 }, { BBJ, BGJ, BRJ, 0, 0, 0, 0, 0 }, { 0x0101 * YGJ, 0, 0, 0 } }; #else const YuvConstants SIMD_ALIGNED(kYuvJConstants) = { { UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0, UBJ, 0 }, { UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ, UGJ, VGJ }, { 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ, 0, VRJ }, { BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ, BBJ }, { BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ, BGJ }, { BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ, BRJ }, { YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ, YGJ } }; #endif #undef YGJ #undef YGBJ #undef UBJ #undef UGJ #undef VGJ #undef VRJ #undef BBJ #undef BGJ #undef BRJ // BT.709 YUV to RGB reference // * R = Y - V * -1.28033 // * G = Y - U * 0.21482 - V * 0.38059 // * B = Y - U * -2.12798 // Y contribution to R,G,B. Scale and bias. #define YGH 16320 /* round(1.000 * 64 * 256 * 256 / 257) */ #define YGBH 32 /* 64 / 2 */ // TODO(fbarchard): Find way to express 2.12 instead of 2.0. // U and V contributions to R,G,B. #define UBH -128 /* max(-128, round(-2.12798 * 64)) */ #define UGH 14 /* round(0.21482 * 64) */ #define VGH 24 /* round(0.38059 * 64) */ #define VRH -82 /* round(-1.28033 * 64) */ // Bias values to round, and subtract 128 from U and V. #define BBH (UBH * 128 + YGBH) #define BGH (UGH * 128 + VGH * 128 + YGBH) #define BRH (VRH * 128 + YGBH) // BT.709 constants for YUV to RGB. #if defined(__aarch64__) const YuvConstants SIMD_ALIGNED(kYuvHConstants) = { { -UBH, -VRH, -UBH, -VRH, -UBH, -VRH, -UBH, -VRH }, { -UBH, -VRH, -UBH, -VRH, -UBH, -VRH, -UBH, -VRH }, { UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH }, { UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH }, { BBH, BGH, BRH, 0, 0, 0, 0, 0 }, { 0x0101 * YGH, 0, 0, 0 } }; #elif defined(__arm__) const YuvConstants SIMD_ALIGNED(kYuvHConstants) = { { -UBH, -UBH, -UBH, -UBH, -VRH, -VRH, -VRH, -VRH, 0, 0, 0, 0, 0, 0, 0, 0 }, { UGH, UGH, UGH, UGH, VGH, VGH, VGH, VGH, 0, 0, 0, 0, 0, 0, 0, 0 }, { BBH, BGH, BRH, 0, 0, 0, 0, 0 }, { 0x0101 * YGH, 0, 0, 0 } }; #else const YuvConstants SIMD_ALIGNED(kYuvHConstants) = { { UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0, UBH, 0 }, { UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH, UGH, VGH }, { 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH, 0, VRH }, { BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH, BBH }, { BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH, BGH }, { BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH, BRH }, { YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH, YGH } }; #endif #undef YGH #undef YGBH #undef UBH #undef UGH #undef VGH #undef VRH #undef BBH #undef BGH #undef BRH #if !defined(LIBYUV_DISABLE_NEON) && \ (defined(__ARM_NEON__) || defined(__aarch64__) || defined(LIBYUV_NEON)) // C mimic assembly. // TODO(fbarchard): Remove subsampling from Neon. void I444ToARGBRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 u = (src_u[0] + src_u[1] + 1) >> 1; uint8 v = (src_v[0] + src_v[1] + 1) >> 1; YuvPixel(src_y[0], u, v, rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], u, v, rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_u += 2; src_v += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); } } void I444ToABGRRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint8 u = (src_u[0] + src_u[1] + 1) >> 1; uint8 v = (src_v[0] + src_v[1] + 1) >> 1; YuvPixel(src_y[0], u, v, rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], u, v, rgb_buf + 6, rgb_buf + 5, rgb_buf + 4, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_u += 2; src_v += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); } } #else void I444ToARGBRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width; ++x) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; src_y += 1; src_u += 1; src_v += 1; rgb_buf += 4; // Advance 1 pixel. } } void I444ToABGRRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width; ++x) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = 255; src_y += 1; src_u += 1; src_v += 1; rgb_buf += 4; // Advance 1 pixel. } } #endif // Also used for 420 void I422ToARGBRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_u += 1; src_v += 1; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void I422AlphaToARGBRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, const uint8* src_a, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = src_a[0]; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = src_a[1]; src_y += 2; src_u += 1; src_v += 1; src_a += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = src_a[0]; } } void I422ToABGRRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 6, rgb_buf + 5, rgb_buf + 4, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_u += 1; src_v += 1; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = 255; } } void I422AlphaToABGRRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, const uint8* src_a, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = src_a[0]; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 6, rgb_buf + 5, rgb_buf + 4, yuvconstants); rgb_buf[7] = src_a[1]; src_y += 2; src_u += 1; src_v += 1; src_a += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); rgb_buf[3] = src_a[0]; } } void I422ToRGB24Row_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 3, rgb_buf + 4, rgb_buf + 5, yuvconstants); src_y += 2; src_u += 1; src_v += 1; rgb_buf += 6; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); } } void I422ToRAWRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 5, rgb_buf + 4, rgb_buf + 3, yuvconstants); src_y += 2; src_u += 1; src_v += 1; rgb_buf += 6; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 2, rgb_buf + 1, rgb_buf + 0, yuvconstants); } } void I422ToARGB4444Row_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb4444, const struct YuvConstants* yuvconstants, int width) { uint8 b0; uint8 g0; uint8 r0; uint8 b1; uint8 g1; uint8 r1; int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); YuvPixel(src_y[1], src_u[0], src_v[0], &b1, &g1, &r1, yuvconstants); b0 = b0 >> 4; g0 = g0 >> 4; r0 = r0 >> 4; b1 = b1 >> 4; g1 = g1 >> 4; r1 = r1 >> 4; *(uint32*)(dst_argb4444) = b0 | (g0 << 4) | (r0 << 8) | (b1 << 16) | (g1 << 20) | (r1 << 24) | 0xf000f000; src_y += 2; src_u += 1; src_v += 1; dst_argb4444 += 4; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); b0 = b0 >> 4; g0 = g0 >> 4; r0 = r0 >> 4; *(uint16*)(dst_argb4444) = b0 | (g0 << 4) | (r0 << 8) | 0xf000; } } void I422ToARGB1555Row_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb1555, const struct YuvConstants* yuvconstants, int width) { uint8 b0; uint8 g0; uint8 r0; uint8 b1; uint8 g1; uint8 r1; int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); YuvPixel(src_y[1], src_u[0], src_v[0], &b1, &g1, &r1, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 3; r0 = r0 >> 3; b1 = b1 >> 3; g1 = g1 >> 3; r1 = r1 >> 3; *(uint32*)(dst_argb1555) = b0 | (g0 << 5) | (r0 << 10) | (b1 << 16) | (g1 << 21) | (r1 << 26) | 0x80008000; src_y += 2; src_u += 1; src_v += 1; dst_argb1555 += 4; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 3; r0 = r0 >> 3; *(uint16*)(dst_argb1555) = b0 | (g0 << 5) | (r0 << 10) | 0x8000; } } void I422ToRGB565Row_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { uint8 b0; uint8 g0; uint8 r0; uint8 b1; uint8 g1; uint8 r1; int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); YuvPixel(src_y[1], src_u[0], src_v[0], &b1, &g1, &r1, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 2; r0 = r0 >> 3; b1 = b1 >> 3; g1 = g1 >> 2; r1 = r1 >> 3; *(uint32*)(dst_rgb565) = b0 | (g0 << 5) | (r0 << 11) | (b1 << 16) | (g1 << 21) | (r1 << 27); src_y += 2; src_u += 1; src_v += 1; dst_rgb565 += 4; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], &b0, &g0, &r0, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 2; r0 = r0 >> 3; *(uint16*)(dst_rgb565) = b0 | (g0 << 5) | (r0 << 11); } } void I411ToARGBRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 3; x += 4) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; YuvPixel(src_y[2], src_u[0], src_v[0], rgb_buf + 8, rgb_buf + 9, rgb_buf + 10, yuvconstants); rgb_buf[11] = 255; YuvPixel(src_y[3], src_u[0], src_v[0], rgb_buf + 12, rgb_buf + 13, rgb_buf + 14, yuvconstants); rgb_buf[15] = 255; src_y += 4; src_u += 1; src_v += 1; rgb_buf += 16; // Advance 4 pixels. } if (width & 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_y += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void NV12ToARGBRow_C(const uint8* src_y, const uint8* src_uv, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_uv[0], src_uv[1], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_uv[0], src_uv[1], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_uv += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_uv[0], src_uv[1], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void NV21ToARGBRow_C(const uint8* src_y, const uint8* src_vu, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_vu[1], src_vu[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_y[1], src_vu[1], src_vu[0], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_y += 2; src_vu += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_vu[1], src_vu[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void NV12ToRGB565Row_C(const uint8* src_y, const uint8* src_uv, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { uint8 b0; uint8 g0; uint8 r0; uint8 b1; uint8 g1; uint8 r1; int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_uv[0], src_uv[1], &b0, &g0, &r0, yuvconstants); YuvPixel(src_y[1], src_uv[0], src_uv[1], &b1, &g1, &r1, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 2; r0 = r0 >> 3; b1 = b1 >> 3; g1 = g1 >> 2; r1 = r1 >> 3; *(uint32*)(dst_rgb565) = b0 | (g0 << 5) | (r0 << 11) | (b1 << 16) | (g1 << 21) | (r1 << 27); src_y += 2; src_uv += 2; dst_rgb565 += 4; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_uv[0], src_uv[1], &b0, &g0, &r0, yuvconstants); b0 = b0 >> 3; g0 = g0 >> 2; r0 = r0 >> 3; *(uint16*)(dst_rgb565) = b0 | (g0 << 5) | (r0 << 11); } } void YUY2ToARGBRow_C(const uint8* src_yuy2, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_yuy2[0], src_yuy2[1], src_yuy2[3], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_yuy2[2], src_yuy2[1], src_yuy2[3], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_yuy2 += 4; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_yuy2[0], src_yuy2[1], src_yuy2[3], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void UYVYToARGBRow_C(const uint8* src_uyvy, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_uyvy[1], src_uyvy[0], src_uyvy[2], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; YuvPixel(src_uyvy[3], src_uyvy[0], src_uyvy[2], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6, yuvconstants); rgb_buf[7] = 255; src_uyvy += 4; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_uyvy[1], src_uyvy[0], src_uyvy[2], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2, yuvconstants); rgb_buf[3] = 255; } } void I422ToBGRARow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 3, rgb_buf + 2, rgb_buf + 1, yuvconstants); rgb_buf[0] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 7, rgb_buf + 6, rgb_buf + 5, yuvconstants); rgb_buf[4] = 255; src_y += 2; src_u += 1; src_v += 1; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 3, rgb_buf + 2, rgb_buf + 1, yuvconstants); rgb_buf[0] = 255; } } void I422ToRGBARow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* rgb_buf, const struct YuvConstants* yuvconstants, int width) { int x; for (x = 0; x < width - 1; x += 2) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 1, rgb_buf + 2, rgb_buf + 3, yuvconstants); rgb_buf[0] = 255; YuvPixel(src_y[1], src_u[0], src_v[0], rgb_buf + 5, rgb_buf + 6, rgb_buf + 7, yuvconstants); rgb_buf[4] = 255; src_y += 2; src_u += 1; src_v += 1; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YuvPixel(src_y[0], src_u[0], src_v[0], rgb_buf + 1, rgb_buf + 2, rgb_buf + 3, yuvconstants); rgb_buf[0] = 255; } } void I400ToARGBRow_C(const uint8* src_y, uint8* rgb_buf, int width) { int x; for (x = 0; x < width - 1; x += 2) { YPixel(src_y[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2); rgb_buf[3] = 255; YPixel(src_y[1], rgb_buf + 4, rgb_buf + 5, rgb_buf + 6); rgb_buf[7] = 255; src_y += 2; rgb_buf += 8; // Advance 2 pixels. } if (width & 1) { YPixel(src_y[0], rgb_buf + 0, rgb_buf + 1, rgb_buf + 2); rgb_buf[3] = 255; } } void MirrorRow_C(const uint8* src, uint8* dst, int width) { int x; src += width - 1; for (x = 0; x < width - 1; x += 2) { dst[x] = src[0]; dst[x + 1] = src[-1]; src -= 2; } if (width & 1) { dst[width - 1] = src[0]; } } void MirrorUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width) { int x; src_uv += (width - 1) << 1; for (x = 0; x < width - 1; x += 2) { dst_u[x] = src_uv[0]; dst_u[x + 1] = src_uv[-2]; dst_v[x] = src_uv[1]; dst_v[x + 1] = src_uv[-2 + 1]; src_uv -= 4; } if (width & 1) { dst_u[width - 1] = src_uv[0]; dst_v[width - 1] = src_uv[1]; } } void ARGBMirrorRow_C(const uint8* src, uint8* dst, int width) { int x; const uint32* src32 = (const uint32*)(src); uint32* dst32 = (uint32*)(dst); src32 += width - 1; for (x = 0; x < width - 1; x += 2) { dst32[x] = src32[0]; dst32[x + 1] = src32[-1]; src32 -= 2; } if (width & 1) { dst32[width - 1] = src32[0]; } } void SplitUVRow_C(const uint8* src_uv, uint8* dst_u, uint8* dst_v, int width) { int x; for (x = 0; x < width - 1; x += 2) { dst_u[x] = src_uv[0]; dst_u[x + 1] = src_uv[2]; dst_v[x] = src_uv[1]; dst_v[x + 1] = src_uv[3]; src_uv += 4; } if (width & 1) { dst_u[width - 1] = src_uv[0]; dst_v[width - 1] = src_uv[1]; } } void MergeUVRow_C(const uint8* src_u, const uint8* src_v, uint8* dst_uv, int width) { int x; for (x = 0; x < width - 1; x += 2) { dst_uv[0] = src_u[x]; dst_uv[1] = src_v[x]; dst_uv[2] = src_u[x + 1]; dst_uv[3] = src_v[x + 1]; dst_uv += 4; } if (width & 1) { dst_uv[0] = src_u[width - 1]; dst_uv[1] = src_v[width - 1]; } } void CopyRow_C(const uint8* src, uint8* dst, int count) { memcpy(dst, src, count); } void CopyRow_16_C(const uint16* src, uint16* dst, int count) { memcpy(dst, src, count * 2); } void SetRow_C(uint8* dst, uint8 v8, int width) { memset(dst, v8, width); } void ARGBSetRow_C(uint8* dst_argb, uint32 v32, int width) { uint32* d = (uint32*)(dst_argb); int x; for (x = 0; x < width; ++x) { d[x] = v32; } } // Filter 2 rows of YUY2 UV's (422) into U and V (420). void YUY2ToUVRow_C(const uint8* src_yuy2, int src_stride_yuy2, uint8* dst_u, uint8* dst_v, int width) { // Output a row of UV values, filtering 2 rows of YUY2. int x; for (x = 0; x < width; x += 2) { dst_u[0] = (src_yuy2[1] + src_yuy2[src_stride_yuy2 + 1] + 1) >> 1; dst_v[0] = (src_yuy2[3] + src_yuy2[src_stride_yuy2 + 3] + 1) >> 1; src_yuy2 += 4; dst_u += 1; dst_v += 1; } } // Copy row of YUY2 UV's (422) into U and V (422). void YUY2ToUV422Row_C(const uint8* src_yuy2, uint8* dst_u, uint8* dst_v, int width) { // Output a row of UV values. int x; for (x = 0; x < width; x += 2) { dst_u[0] = src_yuy2[1]; dst_v[0] = src_yuy2[3]; src_yuy2 += 4; dst_u += 1; dst_v += 1; } } // Copy row of YUY2 Y's (422) into Y (420/422). void YUY2ToYRow_C(const uint8* src_yuy2, uint8* dst_y, int width) { // Output a row of Y values. int x; for (x = 0; x < width - 1; x += 2) { dst_y[x] = src_yuy2[0]; dst_y[x + 1] = src_yuy2[2]; src_yuy2 += 4; } if (width & 1) { dst_y[width - 1] = src_yuy2[0]; } } // Filter 2 rows of UYVY UV's (422) into U and V (420). void UYVYToUVRow_C(const uint8* src_uyvy, int src_stride_uyvy, uint8* dst_u, uint8* dst_v, int width) { // Output a row of UV values. int x; for (x = 0; x < width; x += 2) { dst_u[0] = (src_uyvy[0] + src_uyvy[src_stride_uyvy + 0] + 1) >> 1; dst_v[0] = (src_uyvy[2] + src_uyvy[src_stride_uyvy + 2] + 1) >> 1; src_uyvy += 4; dst_u += 1; dst_v += 1; } } // Copy row of UYVY UV's (422) into U and V (422). void UYVYToUV422Row_C(const uint8* src_uyvy, uint8* dst_u, uint8* dst_v, int width) { // Output a row of UV values. int x; for (x = 0; x < width; x += 2) { dst_u[0] = src_uyvy[0]; dst_v[0] = src_uyvy[2]; src_uyvy += 4; dst_u += 1; dst_v += 1; } } // Copy row of UYVY Y's (422) into Y (420/422). void UYVYToYRow_C(const uint8* src_uyvy, uint8* dst_y, int width) { // Output a row of Y values. int x; for (x = 0; x < width - 1; x += 2) { dst_y[x] = src_uyvy[1]; dst_y[x + 1] = src_uyvy[3]; src_uyvy += 4; } if (width & 1) { dst_y[width - 1] = src_uyvy[1]; } } #define BLEND(f, b, a) (((256 - a) * b) >> 8) + f // Blend src_argb0 over src_argb1 and store to dst_argb. // dst_argb may be src_argb0 or src_argb1. // This code mimics the SSSE3 version for better testability. void ARGBBlendRow_C(const uint8* src_argb0, const uint8* src_argb1, uint8* dst_argb, int width) { int x; for (x = 0; x < width - 1; x += 2) { uint32 fb = src_argb0[0]; uint32 fg = src_argb0[1]; uint32 fr = src_argb0[2]; uint32 a = src_argb0[3]; uint32 bb = src_argb1[0]; uint32 bg = src_argb1[1]; uint32 br = src_argb1[2]; dst_argb[0] = BLEND(fb, bb, a); dst_argb[1] = BLEND(fg, bg, a); dst_argb[2] = BLEND(fr, br, a); dst_argb[3] = 255u; fb = src_argb0[4 + 0]; fg = src_argb0[4 + 1]; fr = src_argb0[4 + 2]; a = src_argb0[4 + 3]; bb = src_argb1[4 + 0]; bg = src_argb1[4 + 1]; br = src_argb1[4 + 2]; dst_argb[4 + 0] = BLEND(fb, bb, a); dst_argb[4 + 1] = BLEND(fg, bg, a); dst_argb[4 + 2] = BLEND(fr, br, a); dst_argb[4 + 3] = 255u; src_argb0 += 8; src_argb1 += 8; dst_argb += 8; } if (width & 1) { uint32 fb = src_argb0[0]; uint32 fg = src_argb0[1]; uint32 fr = src_argb0[2]; uint32 a = src_argb0[3]; uint32 bb = src_argb1[0]; uint32 bg = src_argb1[1]; uint32 br = src_argb1[2]; dst_argb[0] = BLEND(fb, bb, a); dst_argb[1] = BLEND(fg, bg, a); dst_argb[2] = BLEND(fr, br, a); dst_argb[3] = 255u; } } #undef BLEND #define ATTENUATE(f, a) (a | (a << 8)) * (f | (f << 8)) >> 24 // Multiply source RGB by alpha and store to destination. // This code mimics the SSSE3 version for better testability. void ARGBAttenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width) { int i; for (i = 0; i < width - 1; i += 2) { uint32 b = src_argb[0]; uint32 g = src_argb[1]; uint32 r = src_argb[2]; uint32 a = src_argb[3]; dst_argb[0] = ATTENUATE(b, a); dst_argb[1] = ATTENUATE(g, a); dst_argb[2] = ATTENUATE(r, a); dst_argb[3] = a; b = src_argb[4]; g = src_argb[5]; r = src_argb[6]; a = src_argb[7]; dst_argb[4] = ATTENUATE(b, a); dst_argb[5] = ATTENUATE(g, a); dst_argb[6] = ATTENUATE(r, a); dst_argb[7] = a; src_argb += 8; dst_argb += 8; } if (width & 1) { const uint32 b = src_argb[0]; const uint32 g = src_argb[1]; const uint32 r = src_argb[2]; const uint32 a = src_argb[3]; dst_argb[0] = ATTENUATE(b, a); dst_argb[1] = ATTENUATE(g, a); dst_argb[2] = ATTENUATE(r, a); dst_argb[3] = a; } } #undef ATTENUATE // Divide source RGB by alpha and store to destination. // b = (b * 255 + (a / 2)) / a; // g = (g * 255 + (a / 2)) / a; // r = (r * 255 + (a / 2)) / a; // Reciprocal method is off by 1 on some values. ie 125 // 8.8 fixed point inverse table with 1.0 in upper short and 1 / a in lower. #define T(a) 0x01000000 + (0x10000 / a) const uint32 fixed_invtbl8[256] = { 0x01000000, 0x0100ffff, T(0x02), T(0x03), T(0x04), T(0x05), T(0x06), T(0x07), T(0x08), T(0x09), T(0x0a), T(0x0b), T(0x0c), T(0x0d), T(0x0e), T(0x0f), T(0x10), T(0x11), T(0x12), T(0x13), T(0x14), T(0x15), T(0x16), T(0x17), T(0x18), T(0x19), T(0x1a), T(0x1b), T(0x1c), T(0x1d), T(0x1e), T(0x1f), T(0x20), T(0x21), T(0x22), T(0x23), T(0x24), T(0x25), T(0x26), T(0x27), T(0x28), T(0x29), T(0x2a), T(0x2b), T(0x2c), T(0x2d), T(0x2e), T(0x2f), T(0x30), T(0x31), T(0x32), T(0x33), T(0x34), T(0x35), T(0x36), T(0x37), T(0x38), T(0x39), T(0x3a), T(0x3b), T(0x3c), T(0x3d), T(0x3e), T(0x3f), T(0x40), T(0x41), T(0x42), T(0x43), T(0x44), T(0x45), T(0x46), T(0x47), T(0x48), T(0x49), T(0x4a), T(0x4b), T(0x4c), T(0x4d), T(0x4e), T(0x4f), T(0x50), T(0x51), T(0x52), T(0x53), T(0x54), T(0x55), T(0x56), T(0x57), T(0x58), T(0x59), T(0x5a), T(0x5b), T(0x5c), T(0x5d), T(0x5e), T(0x5f), T(0x60), T(0x61), T(0x62), T(0x63), T(0x64), T(0x65), T(0x66), T(0x67), T(0x68), T(0x69), T(0x6a), T(0x6b), T(0x6c), T(0x6d), T(0x6e), T(0x6f), T(0x70), T(0x71), T(0x72), T(0x73), T(0x74), T(0x75), T(0x76), T(0x77), T(0x78), T(0x79), T(0x7a), T(0x7b), T(0x7c), T(0x7d), T(0x7e), T(0x7f), T(0x80), T(0x81), T(0x82), T(0x83), T(0x84), T(0x85), T(0x86), T(0x87), T(0x88), T(0x89), T(0x8a), T(0x8b), T(0x8c), T(0x8d), T(0x8e), T(0x8f), T(0x90), T(0x91), T(0x92), T(0x93), T(0x94), T(0x95), T(0x96), T(0x97), T(0x98), T(0x99), T(0x9a), T(0x9b), T(0x9c), T(0x9d), T(0x9e), T(0x9f), T(0xa0), T(0xa1), T(0xa2), T(0xa3), T(0xa4), T(0xa5), T(0xa6), T(0xa7), T(0xa8), T(0xa9), T(0xaa), T(0xab), T(0xac), T(0xad), T(0xae), T(0xaf), T(0xb0), T(0xb1), T(0xb2), T(0xb3), T(0xb4), T(0xb5), T(0xb6), T(0xb7), T(0xb8), T(0xb9), T(0xba), T(0xbb), T(0xbc), T(0xbd), T(0xbe), T(0xbf), T(0xc0), T(0xc1), T(0xc2), T(0xc3), T(0xc4), T(0xc5), T(0xc6), T(0xc7), T(0xc8), T(0xc9), T(0xca), T(0xcb), T(0xcc), T(0xcd), T(0xce), T(0xcf), T(0xd0), T(0xd1), T(0xd2), T(0xd3), T(0xd4), T(0xd5), T(0xd6), T(0xd7), T(0xd8), T(0xd9), T(0xda), T(0xdb), T(0xdc), T(0xdd), T(0xde), T(0xdf), T(0xe0), T(0xe1), T(0xe2), T(0xe3), T(0xe4), T(0xe5), T(0xe6), T(0xe7), T(0xe8), T(0xe9), T(0xea), T(0xeb), T(0xec), T(0xed), T(0xee), T(0xef), T(0xf0), T(0xf1), T(0xf2), T(0xf3), T(0xf4), T(0xf5), T(0xf6), T(0xf7), T(0xf8), T(0xf9), T(0xfa), T(0xfb), T(0xfc), T(0xfd), T(0xfe), 0x01000100 }; #undef T void ARGBUnattenuateRow_C(const uint8* src_argb, uint8* dst_argb, int width) { int i; for (i = 0; i < width; ++i) { uint32 b = src_argb[0]; uint32 g = src_argb[1]; uint32 r = src_argb[2]; const uint32 a = src_argb[3]; const uint32 ia = fixed_invtbl8[a] & 0xffff; // 8.8 fixed point b = (b * ia) >> 8; g = (g * ia) >> 8; r = (r * ia) >> 8; // Clamping should not be necessary but is free in assembly. dst_argb[0] = clamp255(b); dst_argb[1] = clamp255(g); dst_argb[2] = clamp255(r); dst_argb[3] = a; src_argb += 4; dst_argb += 4; } } void ComputeCumulativeSumRow_C(const uint8* row, int32* cumsum, const int32* previous_cumsum, int width) { int32 row_sum[4] = {0, 0, 0, 0}; int x; for (x = 0; x < width; ++x) { row_sum[0] += row[x * 4 + 0]; row_sum[1] += row[x * 4 + 1]; row_sum[2] += row[x * 4 + 2]; row_sum[3] += row[x * 4 + 3]; cumsum[x * 4 + 0] = row_sum[0] + previous_cumsum[x * 4 + 0]; cumsum[x * 4 + 1] = row_sum[1] + previous_cumsum[x * 4 + 1]; cumsum[x * 4 + 2] = row_sum[2] + previous_cumsum[x * 4 + 2]; cumsum[x * 4 + 3] = row_sum[3] + previous_cumsum[x * 4 + 3]; } } void CumulativeSumToAverageRow_C(const int32* tl, const int32* bl, int w, int area, uint8* dst, int count) { float ooa = 1.0f / area; int i; for (i = 0; i < count; ++i) { dst[0] = (uint8)((bl[w + 0] + tl[0] - bl[0] - tl[w + 0]) * ooa); dst[1] = (uint8)((bl[w + 1] + tl[1] - bl[1] - tl[w + 1]) * ooa); dst[2] = (uint8)((bl[w + 2] + tl[2] - bl[2] - tl[w + 2]) * ooa); dst[3] = (uint8)((bl[w + 3] + tl[3] - bl[3] - tl[w + 3]) * ooa); dst += 4; tl += 4; bl += 4; } } // Copy pixels from rotated source to destination row with a slope. LIBYUV_API void ARGBAffineRow_C(const uint8* src_argb, int src_argb_stride, uint8* dst_argb, const float* uv_dudv, int width) { int i; // Render a row of pixels from source into a buffer. float uv[2]; uv[0] = uv_dudv[0]; uv[1] = uv_dudv[1]; for (i = 0; i < width; ++i) { int x = (int)(uv[0]); int y = (int)(uv[1]); *(uint32*)(dst_argb) = *(const uint32*)(src_argb + y * src_argb_stride + x * 4); dst_argb += 4; uv[0] += uv_dudv[2]; uv[1] += uv_dudv[3]; } } // Blend 2 rows into 1. static void HalfRow_C(const uint8* src_uv, int src_uv_stride, uint8* dst_uv, int width) { int x; for (x = 0; x < width; ++x) { dst_uv[x] = (src_uv[x] + src_uv[src_uv_stride + x] + 1) >> 1; } } static void HalfRow_16_C(const uint16* src_uv, int src_uv_stride, uint16* dst_uv, int width) { int x; for (x = 0; x < width; ++x) { dst_uv[x] = (src_uv[x] + src_uv[src_uv_stride + x] + 1) >> 1; } } // C version 2x2 -> 2x1. void InterpolateRow_C(uint8* dst_ptr, const uint8* src_ptr, ptrdiff_t src_stride, int width, int source_y_fraction) { int y1_fraction = source_y_fraction; int y0_fraction = 256 - y1_fraction; const uint8* src_ptr1 = src_ptr + src_stride; int x; if (source_y_fraction == 0) { memcpy(dst_ptr, src_ptr, width); return; } if (source_y_fraction == 128) { HalfRow_C(src_ptr, (int)(src_stride), dst_ptr, width); return; } for (x = 0; x < width - 1; x += 2) { dst_ptr[0] = (src_ptr[0] * y0_fraction + src_ptr1[0] * y1_fraction) >> 8; dst_ptr[1] = (src_ptr[1] * y0_fraction + src_ptr1[1] * y1_fraction) >> 8; src_ptr += 2; src_ptr1 += 2; dst_ptr += 2; } if (width & 1) { dst_ptr[0] = (src_ptr[0] * y0_fraction + src_ptr1[0] * y1_fraction) >> 8; } } void InterpolateRow_16_C(uint16* dst_ptr, const uint16* src_ptr, ptrdiff_t src_stride, int width, int source_y_fraction) { int y1_fraction = source_y_fraction; int y0_fraction = 256 - y1_fraction; const uint16* src_ptr1 = src_ptr + src_stride; int x; if (source_y_fraction == 0) { memcpy(dst_ptr, src_ptr, width * 2); return; } if (source_y_fraction == 128) { HalfRow_16_C(src_ptr, (int)(src_stride), dst_ptr, width); return; } for (x = 0; x < width - 1; x += 2) { dst_ptr[0] = (src_ptr[0] * y0_fraction + src_ptr1[0] * y1_fraction) >> 8; dst_ptr[1] = (src_ptr[1] * y0_fraction + src_ptr1[1] * y1_fraction) >> 8; src_ptr += 2; src_ptr1 += 2; dst_ptr += 2; } if (width & 1) { dst_ptr[0] = (src_ptr[0] * y0_fraction + src_ptr1[0] * y1_fraction) >> 8; } } // Use first 4 shuffler values to reorder ARGB channels. void ARGBShuffleRow_C(const uint8* src_argb, uint8* dst_argb, const uint8* shuffler, int width) { int index0 = shuffler[0]; int index1 = shuffler[1]; int index2 = shuffler[2]; int index3 = shuffler[3]; // Shuffle a row of ARGB. int x; for (x = 0; x < width; ++x) { // To support in-place conversion. uint8 b = src_argb[index0]; uint8 g = src_argb[index1]; uint8 r = src_argb[index2]; uint8 a = src_argb[index3]; dst_argb[0] = b; dst_argb[1] = g; dst_argb[2] = r; dst_argb[3] = a; src_argb += 4; dst_argb += 4; } } void I422ToYUY2Row_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_frame, int width) { int x; for (x = 0; x < width - 1; x += 2) { dst_frame[0] = src_y[0]; dst_frame[1] = src_u[0]; dst_frame[2] = src_y[1]; dst_frame[3] = src_v[0]; dst_frame += 4; src_y += 2; src_u += 1; src_v += 1; } if (width & 1) { dst_frame[0] = src_y[0]; dst_frame[1] = src_u[0]; dst_frame[2] = 0; dst_frame[3] = src_v[0]; } } void I422ToUYVYRow_C(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_frame, int width) { int x; for (x = 0; x < width - 1; x += 2) { dst_frame[0] = src_u[0]; dst_frame[1] = src_y[0]; dst_frame[2] = src_v[0]; dst_frame[3] = src_y[1]; dst_frame += 4; src_y += 2; src_u += 1; src_v += 1; } if (width & 1) { dst_frame[0] = src_u[0]; dst_frame[1] = src_y[0]; dst_frame[2] = src_v[0]; dst_frame[3] = 0; } } void ARGBPolynomialRow_C(const uint8* src_argb, uint8* dst_argb, const float* poly, int width) { int i; for (i = 0; i < width; ++i) { float b = (float)(src_argb[0]); float g = (float)(src_argb[1]); float r = (float)(src_argb[2]); float a = (float)(src_argb[3]); float b2 = b * b; float g2 = g * g; float r2 = r * r; float a2 = a * a; float db = poly[0] + poly[4] * b; float dg = poly[1] + poly[5] * g; float dr = poly[2] + poly[6] * r; float da = poly[3] + poly[7] * a; float b3 = b2 * b; float g3 = g2 * g; float r3 = r2 * r; float a3 = a2 * a; db += poly[8] * b2; dg += poly[9] * g2; dr += poly[10] * r2; da += poly[11] * a2; db += poly[12] * b3; dg += poly[13] * g3; dr += poly[14] * r3; da += poly[15] * a3; dst_argb[0] = Clamp((int32)(db)); dst_argb[1] = Clamp((int32)(dg)); dst_argb[2] = Clamp((int32)(dr)); dst_argb[3] = Clamp((int32)(da)); src_argb += 4; dst_argb += 4; } } void ARGBLumaColorTableRow_C(const uint8* src_argb, uint8* dst_argb, int width, const uint8* luma, uint32 lumacoeff) { uint32 bc = lumacoeff & 0xff; uint32 gc = (lumacoeff >> 8) & 0xff; uint32 rc = (lumacoeff >> 16) & 0xff; int i; for (i = 0; i < width - 1; i += 2) { // Luminance in rows, color values in columns. const uint8* luma0 = ((src_argb[0] * bc + src_argb[1] * gc + src_argb[2] * rc) & 0x7F00u) + luma; const uint8* luma1; dst_argb[0] = luma0[src_argb[0]]; dst_argb[1] = luma0[src_argb[1]]; dst_argb[2] = luma0[src_argb[2]]; dst_argb[3] = src_argb[3]; luma1 = ((src_argb[4] * bc + src_argb[5] * gc + src_argb[6] * rc) & 0x7F00u) + luma; dst_argb[4] = luma1[src_argb[4]]; dst_argb[5] = luma1[src_argb[5]]; dst_argb[6] = luma1[src_argb[6]]; dst_argb[7] = src_argb[7]; src_argb += 8; dst_argb += 8; } if (width & 1) { // Luminance in rows, color values in columns. const uint8* luma0 = ((src_argb[0] * bc + src_argb[1] * gc + src_argb[2] * rc) & 0x7F00u) + luma; dst_argb[0] = luma0[src_argb[0]]; dst_argb[1] = luma0[src_argb[1]]; dst_argb[2] = luma0[src_argb[2]]; dst_argb[3] = src_argb[3]; } } void ARGBCopyAlphaRow_C(const uint8* src, uint8* dst, int width) { int i; for (i = 0; i < width - 1; i += 2) { dst[3] = src[3]; dst[7] = src[7]; dst += 8; src += 8; } if (width & 1) { dst[3] = src[3]; } } void ARGBCopyYToAlphaRow_C(const uint8* src, uint8* dst, int width) { int i; for (i = 0; i < width - 1; i += 2) { dst[3] = src[0]; dst[7] = src[1]; dst += 8; src += 2; } if (width & 1) { dst[3] = src[0]; } } // Maximum temporary width for wrappers to process at a time, in pixels. #define MAXTWIDTH 2048 #if !(defined(_MSC_VER) && defined(_M_IX86)) && \ defined(HAS_I422TORGB565ROW_SSSE3) // row_win.cc has asm version, but GCC uses 2 step wrapper. void I422ToRGB565Row_SSSE3(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { SIMD_ALIGNED(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_SSSE3(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToRGB565Row_SSE2(row, dst_rgb565, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_rgb565 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TOARGB1555ROW_SSSE3) void I422ToARGB1555Row_SSSE3(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb1555, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_SSSE3(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToARGB1555Row_SSE2(row, dst_argb1555, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_argb1555 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TOARGB4444ROW_SSSE3) void I422ToARGB4444Row_SSSE3(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb4444, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_SSSE3(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToARGB4444Row_SSE2(row, dst_argb4444, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_argb4444 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_NV12TORGB565ROW_SSSE3) void NV12ToRGB565Row_SSSE3(const uint8* src_y, const uint8* src_uv, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; NV12ToARGBRow_SSSE3(src_y, src_uv, row, yuvconstants, twidth); ARGBToRGB565Row_SSE2(row, dst_rgb565, twidth); src_y += twidth; src_uv += twidth; dst_rgb565 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TORGB565ROW_AVX2) void I422ToRGB565Row_AVX2(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_AVX2(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToRGB565Row_AVX2(row, dst_rgb565, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_rgb565 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TOARGB1555ROW_AVX2) void I422ToARGB1555Row_AVX2(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb1555, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_AVX2(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToARGB1555Row_AVX2(row, dst_argb1555, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_argb1555 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TOARGB4444ROW_AVX2) void I422ToARGB4444Row_AVX2(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_argb4444, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_AVX2(src_y, src_u, src_v, row, yuvconstants, twidth); ARGBToARGB4444Row_AVX2(row, dst_argb4444, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_argb4444 += twidth * 2; width -= twidth; } } #endif #if defined(HAS_I422TORGB24ROW_AVX2) void I422ToRGB24Row_AVX2(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_rgb24, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_AVX2(src_y, src_u, src_v, row, yuvconstants, twidth); // TODO(fbarchard): ARGBToRGB24Row_AVX2 ARGBToRGB24Row_SSSE3(row, dst_rgb24, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_rgb24 += twidth * 3; width -= twidth; } } #endif #if defined(HAS_I422TORAWROW_AVX2) void I422ToRAWRow_AVX2(const uint8* src_y, const uint8* src_u, const uint8* src_v, uint8* dst_raw, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; I422ToARGBRow_AVX2(src_y, src_u, src_v, row, yuvconstants, twidth); // TODO(fbarchard): ARGBToRAWRow_AVX2 ARGBToRAWRow_SSSE3(row, dst_raw, twidth); src_y += twidth; src_u += twidth / 2; src_v += twidth / 2; dst_raw += twidth * 3; width -= twidth; } } #endif #if defined(HAS_NV12TORGB565ROW_AVX2) void NV12ToRGB565Row_AVX2(const uint8* src_y, const uint8* src_uv, uint8* dst_rgb565, const struct YuvConstants* yuvconstants, int width) { // Row buffer for intermediate ARGB pixels. SIMD_ALIGNED32(uint8 row[MAXTWIDTH * 4]); while (width > 0) { int twidth = width > MAXTWIDTH ? MAXTWIDTH : width; NV12ToARGBRow_AVX2(src_y, src_uv, row, yuvconstants, twidth); ARGBToRGB565Row_AVX2(row, dst_rgb565, twidth); src_y += twidth; src_uv += twidth; dst_rgb565 += twidth * 2; width -= twidth; } } #endif #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif
d8695a03f1fab5956c36f7b04946ad3af2c44a6b
fdbfbcf4d6a0ef6f3c1b600e7b8037eed0f03f9e
/math/test/soft_min_max_test.cc
0a06aab09c27602da320fa3e71741c6a7329476a
[ "BSD-3-Clause" ]
permissive
RobotLocomotion/drake
4529c397f8424145623dd70665531b5e246749a0
3905758e8e99b0f2332461b1cb630907245e0572
refs/heads/master
2023-08-30T21:45:12.782437
2023-08-30T15:59:07
2023-08-30T15:59:07
16,256,144
2,904
1,270
NOASSERTION
2023-09-14T20:51:30
2014-01-26T16:11:05
C++
UTF-8
C++
false
false
3,920
cc
#include "drake/math/soft_min_max.h" #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace math { GTEST_TEST(SoftOverMax, TestDouble) { const std::vector<double> x{{1.0, 2.0, 3.0, 1.5, 2.9, 2.99}}; double alpha = 1; const double x_max1 = SoftOverMax(x, alpha); EXPECT_GT(x_max1, 3); alpha = 10; const double x_max10 = SoftOverMax(x, alpha); EXPECT_GT(x_max10, 3); EXPECT_LT(x_max10, x_max1); EXPECT_NEAR(x_max10, 3, 0.1); alpha = 100; const double x_max100 = SoftOverMax(x, alpha); EXPECT_GT(x_max100, 3); EXPECT_LT(x_max100, x_max10); EXPECT_NEAR(x_max100, 3, 0.01); } GTEST_TEST(SoftOverMax, TestAutodiff) { std::vector<AutoDiffXd> x; x.emplace_back(1, Eigen::Vector2d(1, 3)); x.emplace_back(2, Eigen::Vector2d(0, 1)); x.emplace_back(3, Eigen::Vector2d(0, -1)); const AutoDiffXd x_max = SoftOverMax(x, 10); EXPECT_GT(x_max.value(), 3); EXPECT_NEAR(x_max.value(), 3, 0.01); EXPECT_TRUE( CompareMatrices(x_max.derivatives(), Eigen::Vector2d(0, -1), 1E-3)); } GTEST_TEST(SoftUnderMax, TestDouble) { const std::vector<double> x{{0, 1, 2, 3, 0.5, 2.5, 2.9}}; double alpha = 1; const double x_max1 = SoftUnderMax(x, alpha); EXPECT_LT(x_max1, 3); alpha = 10; const double x_max10 = SoftUnderMax(x, alpha); EXPECT_LT(x_max10, 3); EXPECT_LT(x_max1, x_max10); EXPECT_NEAR(x_max10, 3, 0.1); alpha = 100; const double x_max100 = SoftUnderMax(x, alpha); EXPECT_LT(x_max100, 3); EXPECT_LT(x_max10, x_max100); EXPECT_NEAR(x_max100, 3, 1E-5); } GTEST_TEST(SoftUnderMax, TestAutoDiff) { std::vector<AutoDiffXd> x; x.emplace_back(0, Eigen::Vector2d(3, 4)); x.emplace_back(1, Eigen::Vector2d(1, 2)); x.emplace_back(2, Eigen::Vector2d(0, -1)); const AutoDiffXd x_max = SoftUnderMax(x, 10 /* alpha */); EXPECT_LT(x_max.value(), 2); EXPECT_NEAR(x_max.value(), 2, 1E-2); EXPECT_TRUE( CompareMatrices(x_max.derivatives(), Eigen::Vector2d(0, -1), 1E-2)); } GTEST_TEST(SoftOverMin, TestDouble) { const std::vector<double> x{{1, 1.2, 1.5, 2, 3, 4}}; double alpha = 1; const double x_min1 = SoftOverMin(x, alpha); EXPECT_GT(x_min1, 1); alpha = 10; const double x_min10 = SoftOverMin(x, alpha); EXPECT_GT(x_min10, 1); EXPECT_LT(x_min10, x_min1); EXPECT_NEAR(x_min10, 1, 0.1); alpha = 100; const double x_min100 = SoftOverMin(x, alpha); EXPECT_GT(x_min100, 1); EXPECT_LT(x_min100, x_min10); EXPECT_NEAR(x_min100, 1, 1E-3); } GTEST_TEST(SoftOverMin, TestAutoDiff) { std::vector<AutoDiffXd> x; x.emplace_back(0, Eigen::Vector2d(3, 4)); x.emplace_back(1, Eigen::Vector2d(1, 2)); x.emplace_back(2, Eigen::Vector2d(0, -1)); const AutoDiffXd x_min = SoftOverMin(x, 10 /* alpha */); EXPECT_GT(x_min.value(), 0); EXPECT_NEAR(x_min.value(), 0, 1E-2); EXPECT_TRUE( CompareMatrices(x_min.derivatives(), Eigen::Vector2d(3, 4), 1E-2)); } GTEST_TEST(SoftUnderMin, TestDouble) { std::vector<double> x{{1, 1.2, 1.5, 2, 3, 4, 5}}; double alpha = 1; const double x_min1 = SoftUnderMin(x, alpha); EXPECT_LT(x_min1, 1); alpha = 10; const double x_min10 = SoftUnderMin(x, alpha); EXPECT_LT(x_min10, 1); EXPECT_GT(x_min10, x_min1); EXPECT_NEAR(x_min10, 1, 0.1); alpha = 100; const double x_min100 = SoftUnderMin(x, alpha); EXPECT_LT(x_min100, 1); EXPECT_GT(x_min100, x_min10); EXPECT_NEAR(x_min100, 1, 1E-3); } GTEST_TEST(SoftUnderMin, TestAutoDiff) { std::vector<AutoDiffXd> x; x.emplace_back(0, Eigen::Vector2d(3, 4)); x.emplace_back(1, Eigen::Vector2d(1, 2)); x.emplace_back(2, Eigen::Vector2d(0, -1)); const AutoDiffXd x_min = SoftUnderMin(x, 10 /* alpha */); EXPECT_LT(x_min.value(), 0); EXPECT_NEAR(x_min.value(), 0, 1E-2); EXPECT_TRUE( CompareMatrices(x_min.derivatives(), Eigen::Vector2d(3, 4), 1E-2)); } } // namespace math } // namespace drake
2d1026b0e5c80f943912e97075f7c51e4c4773b6
85f5e869641cf533f2d0e786275d96d5ae90da61
/TaskShiftUtils.h
eae4e4a48c47d4fd8043af1decbfef341666b525
[]
no_license
derekwaters/taskshifter-v1
e7aad4046d236a1d4376ef25141f452de2e1fb0d
9b965dd504303cbd2fea2d13c63949e8afecb734
refs/heads/master
2021-01-13T01:42:15.988693
2013-03-22T11:48:40
2013-03-22T11:48:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
789
h
#ifndef TASKSHIFTUTILS_H #define TASKSHIFTUTILS_H class CTaskShiftUtils { public: static CString ValidatePath(LPCTSTR apszInputPath); static CString GetFilePath(LPCTSTR apszFullPath); static CString GetAppPath(); static CString GetCurrentPath(); static CString BrowseForFile(CWnd* apParentWnd, bool abOpenFileDialog, LPCTSTR aszFileTypeExt = NULL, LPCTSTR aszFileTypeName = NULL, LPCTSTR aszInitialDir = NULL, LPCTSTR aszName = NULL, bool abIncludeAllFilesInFilter = true); static CString BrowseForFolder(CWnd* apParentWnd, LPCTSTR apszTitle, LPCTSTR apszInitialPath, bool abNewStyle, bool abEditBox); static int SplitStringIntoArray(CStringArray &aarrResults, LPCTSTR apszInput, LPCTSTR apszDelimiter); static CString GetComputerName(); static CString GetUserName(); }; #endif
8216d152e8c35619945672f6ebc32be4c01fba00
208265e0ec0fab78ec9ea048e7b042b9142cfab0
/delay.hh
a069586d2090918def48876b314da041037e74c4
[ "0BSD" ]
permissive
aicodix/dsp
fcf6bb719b7c91c15bf523933aa4c924faed9239
a53b33587e820b65e9c4463adef238a9304fd5e7
refs/heads/master
2023-05-25T09:38:02.817259
2023-04-17T08:36:04
2023-04-17T08:36:04
123,578,675
29
12
null
null
null
null
UTF-8
C++
false
false
404
hh
/* Digital delay line Copyright 2020 Ahmet Inan <[email protected]> */ #pragma once namespace DSP { template <typename TYPE, int NUM> class Delay { TYPE buf[NUM]; int pos; public: Delay(TYPE init = 0) : pos(0) { for (int i = 0; i < NUM; ++i) buf[i] = init; } TYPE operator () (TYPE input) { TYPE tmp = buf[pos]; buf[pos] = input; if (++pos >= NUM) pos = 0; return tmp; } }; }
98abad7d9c48b8bd6530f0a2ced9fcf1f205fff3
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_patch_hunk_1193.cpp
78dbb1e949e8994c9d35f5aa01103e3afe2cd23e
[]
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
1,116
cpp
} static void statStoreEntry(MemBuf * mb, StoreEntry * e) { MemObject *mem = e->mem_obj; - mb->Printf("KEY %s\n", e->getMD5Text()); - mb->Printf("\t%s\n", describeStatuses(e)); - mb->Printf("\t%s\n", storeEntryFlags(e)); - mb->Printf("\t%s\n", e->describeTimestamps()); - mb->Printf("\t%d locks, %d clients, %d refs\n", - (int) e->locks(), - storePendingNClients(e), - (int) e->refcount); - mb->Printf("\tSwap Dir %d, File %#08X\n", - e->swap_dirn, e->swap_filen); + mb->appendf("KEY %s\n", e->getMD5Text()); + mb->appendf("\t%s\n", describeStatuses(e)); + mb->appendf("\t%s\n", storeEntryFlags(e)); + mb->appendf("\t%s\n", e->describeTimestamps()); + mb->appendf("\t%d locks, %d clients, %d refs\n", (int) e->locks(), storePendingNClients(e), (int) e->refcount); + mb->appendf("\tSwap Dir %d, File %#08X\n", e->swap_dirn, e->swap_filen); if (mem != NULL) mem->stat (mb); - mb->Printf("\n"); + mb->append("\n", 1); } /* process objects list */ static void statObjects(void *data) {
8be0dec714b0c327b0543c89cd3ffa770b9f2d43
6d54a7b26d0eb82152a549a6a9dfde656687752c
/src/lib/dnssd/tests/TestIncrementalResolve.cpp
2791631a32e8a0901a2983ae5cccca05509f6fc9
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
project-chip/connectedhomeip
81a123d675cf527773f70047d1ed1c43be5ffe6d
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
refs/heads/master
2023-09-01T11:43:37.546040
2023-09-01T08:01:32
2023-09-01T08:01:32
244,694,174
6,409
1,789
Apache-2.0
2023-09-14T20:56:31
2020-03-03T17:05:10
C++
UTF-8
C++
false
false
18,611
cpp
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <lib/dnssd/IncrementalResolve.h> #include <string.h> #include <lib/dnssd/minimal_mdns/core/tests/QNameStrings.h> #include <lib/dnssd/minimal_mdns/records/IP.h> #include <lib/dnssd/minimal_mdns/records/Ptr.h> #include <lib/dnssd/minimal_mdns/records/ResourceRecord.h> #include <lib/dnssd/minimal_mdns/records/Srv.h> #include <lib/dnssd/minimal_mdns/records/Txt.h> #include <lib/support/ScopedBuffer.h> #include <lib/support/UnitTestRegistration.h> #include <nlunit-test.h> using namespace chip; using namespace chip::Dnssd; using namespace mdns::Minimal; namespace { // Operational names must be <compressed-fabric>-<node>._matter._tcp.local const auto kTestOperationalName = testing::TestQName<4>({ "1234567898765432-ABCDEFEDCBAABCDE", "_matter", "_tcp", "local" }); // Commissionable names must be <instance>._matterc._udp.local const auto kTestCommissionableNode = testing::TestQName<4>({ "C5038835313B8B98", "_matterc", "_udp", "local" }); // Commissioner names must be <instance>._matterd._udp.local const auto kTestCommissionerNode = testing::TestQName<4>({ "C5038835313B8B98", "_matterd", "_udp", "local" }); // Server name that is preloaded by the `PreloadSrvRecord` const auto kTestHostName = testing::TestQName<2>({ "abcd", "local" }); const auto kIrrelevantHostName = testing::TestQName<2>({ "different", "local" }); void PreloadSrvRecord(nlTestSuite * inSuite, SrvRecord & record) { uint8_t headerBuffer[HeaderRef::kSizeBytes] = {}; HeaderRef dummyHeader(headerBuffer); // NOTE: record pointers persist beyond this function, so // this data MUST be static static uint8_t dataBuffer[256]; chip::Encoding::BigEndian::BufferWriter output(dataBuffer, sizeof(dataBuffer)); RecordWriter writer(&output); NL_TEST_ASSERT(inSuite, SrvResourceRecord(kTestOperationalName.Full(), kTestHostName.Full(), 0x1234 /* port */) .Append(dummyHeader, ResourceType::kAnswer, writer)); ResourceData resource; BytesRange packet(dataBuffer, dataBuffer + sizeof(dataBuffer)); const uint8_t * _ptr = dataBuffer; NL_TEST_ASSERT(inSuite, resource.Parse(packet, &_ptr)); NL_TEST_ASSERT(inSuite, record.Parse(resource.GetData(), packet)); } /// Convenience method to have a serialized QName. /// Assumes valid QName data that is terminated by null. template <size_t N> static SerializedQNameIterator AsSerializedQName(const uint8_t (&v)[N]) { // NOTE: the -1 is because we format these items as STRINGS and that // appends an extra NULL terminator return SerializedQNameIterator(BytesRange(v, v + N - 1), v); } void CallOnRecord(nlTestSuite * inSuite, IncrementalResolver & resolver, const ResourceRecord & record) { uint8_t headerBuffer[HeaderRef::kSizeBytes] = {}; HeaderRef dummyHeader(headerBuffer); uint8_t dataBuffer[256]; chip::Encoding::BigEndian::BufferWriter output(dataBuffer, sizeof(dataBuffer)); RecordWriter writer(&output); NL_TEST_ASSERT(inSuite, record.Append(dummyHeader, ResourceType::kAnswer, writer)); NL_TEST_ASSERT(inSuite, writer.Fit()); ResourceData resource; BytesRange packet(dataBuffer, dataBuffer + sizeof(dataBuffer)); const uint8_t * _ptr = dataBuffer; NL_TEST_ASSERT(inSuite, resource.Parse(packet, &_ptr)); NL_TEST_ASSERT(inSuite, resolver.OnRecord(chip::Inet::InterfaceId::Null(), resource, packet) == CHIP_NO_ERROR); } void TestStoredServerName(nlTestSuite * inSuite, void * inContext) { StoredServerName name; // name should start of as cleared NL_TEST_ASSERT(inSuite, !name.Get().Next()); // Data should be storable in server name NL_TEST_ASSERT(inSuite, name.Set(kTestOperationalName.Serialized()) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, name.Get() == kTestOperationalName.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() != kTestCommissionerNode.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() != kTestCommissionableNode.Serialized()); NL_TEST_ASSERT(inSuite, name.Set(kTestCommissionerNode.Serialized()) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, name.Get() != kTestOperationalName.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() == kTestCommissionerNode.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() != kTestCommissionableNode.Serialized()); NL_TEST_ASSERT(inSuite, name.Set(kTestCommissionableNode.Serialized()) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, name.Get() != kTestOperationalName.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() != kTestCommissionerNode.Serialized()); NL_TEST_ASSERT(inSuite, name.Get() == kTestCommissionableNode.Serialized()); { // setting to a too long value should reset it uint8_t largeBuffer[256]; memset(largeBuffer, 0, sizeof(largeBuffer)); Encoding::BigEndian::BufferWriter writer(largeBuffer, sizeof(largeBuffer)); for (unsigned idx = 0; true; idx++) { writer.Put("\07abcd123"); // will not NULL-terminate, but buffer is 0-filled if (!writer.Fit()) { break; // filled all our tests } if (writer.WritePos() < 64) { // this is how much data can be fit by the copy NL_TEST_ASSERT_LOOP(inSuite, idx, name.Set(AsSerializedQName(largeBuffer)) == CHIP_NO_ERROR); NL_TEST_ASSERT_LOOP(inSuite, idx, name.Get() == AsSerializedQName(largeBuffer)); NL_TEST_ASSERT_LOOP(inSuite, idx, name.Get() != kTestOperationalName.Serialized()); } else { NL_TEST_ASSERT_LOOP(inSuite, idx, name.Set(AsSerializedQName(largeBuffer)) == CHIP_ERROR_NO_MEMORY); NL_TEST_ASSERT_LOOP(inSuite, idx, !name.Get().Next()); } } } } void TestCreation(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveOperationalParse()); NL_TEST_ASSERT( inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kSrvInitialization)); } void TestInactiveResetOnInitError(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); // test host name is not a 'matter' name NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestHostName.Serialized(), srvRecord) != CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, !resolver.IsActive()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveOperationalParse()); } void TestStartOperational(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestOperationalName.Serialized(), srvRecord) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, resolver.IsActive()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, resolver.IsActiveOperationalParse()); NL_TEST_ASSERT(inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)); NL_TEST_ASSERT(inSuite, resolver.GetTargetHostName() == kTestHostName.Serialized()); } void TestStartCommissionable(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestCommissionableNode.Serialized(), srvRecord) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, resolver.IsActive()); NL_TEST_ASSERT(inSuite, resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveOperationalParse()); NL_TEST_ASSERT(inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)); NL_TEST_ASSERT(inSuite, resolver.GetTargetHostName() == kTestHostName.Serialized()); } void TestStartCommissioner(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestCommissionerNode.Serialized(), srvRecord) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, resolver.IsActive()); NL_TEST_ASSERT(inSuite, resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, !resolver.IsActiveOperationalParse()); NL_TEST_ASSERT(inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)); NL_TEST_ASSERT(inSuite, resolver.GetTargetHostName() == kTestHostName.Serialized()); } void TestParseOperational(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestOperationalName.Serialized(), srvRecord) == CHIP_NO_ERROR); // once initialized, parsing should be ready however no IP address is available NL_TEST_ASSERT(inSuite, resolver.IsActiveOperationalParse()); NL_TEST_ASSERT(inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)); NL_TEST_ASSERT(inSuite, resolver.GetTargetHostName() == kTestHostName.Serialized()); // Send an IP for an irrelevant host name { Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::aabb:ccdd:2233:4455", addr)); CallOnRecord(inSuite, resolver, IPResourceRecord(kIrrelevantHostName.Full(), addr)); } // Send a useful IP address here { Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::abcd:ef11:2233:4455", addr)); CallOnRecord(inSuite, resolver, IPResourceRecord(kTestHostName.Full(), addr)); } // Send a TXT record for an irrelevant host name // Note that TXT entries should be addressed to the Record address and // NOT to the server name for A/AAAA records { const char * entries[] = { "some", "foo=bar", "x=y=z", "a=", // unused data "T=1" // TCP supported }; CallOnRecord(inSuite, resolver, TxtResourceRecord(kTestHostName.Full(), entries)); } // Adding actual text entries that are useful // Note that TXT entries should be addressed to the Record address and // NOT to the server name for A/AAAA records { const char * entries[] = { "foo=bar", // unused data "SII=23" // sleepy idle interval }; CallOnRecord(inSuite, resolver, TxtResourceRecord(kTestOperationalName.Full(), entries)); } // Resolver should have all data NL_TEST_ASSERT(inSuite, !resolver.GetMissingRequiredInformation().HasAny()); // At this point taking value should work. Once taken, the resolver is reset. ResolvedNodeData nodeData; NL_TEST_ASSERT(inSuite, resolver.Take(nodeData) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, !resolver.IsActive()); // validate data as it was passed in NL_TEST_ASSERT(inSuite, nodeData.operationalData.peerId == PeerId().SetCompressedFabricId(0x1234567898765432LL).SetNodeId(0xABCDEFEDCBAABCDELL)); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.numIPs == 1); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.port == 0x1234); NL_TEST_ASSERT(inSuite, !nodeData.resolutionData.supportsTcp); NL_TEST_ASSERT(inSuite, !nodeData.resolutionData.GetMrpRetryIntervalActive().HasValue()); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.GetMrpRetryIntervalIdle().HasValue()); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.GetMrpRetryIntervalIdle().Value() == chip::System::Clock::Milliseconds32(23)); Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::abcd:ef11:2233:4455", addr)); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.ipAddress[0] == addr); } void TestParseCommissionable(nlTestSuite * inSuite, void * inContext) { IncrementalResolver resolver; NL_TEST_ASSERT(inSuite, !resolver.IsActive()); SrvRecord srvRecord; PreloadSrvRecord(inSuite, srvRecord); NL_TEST_ASSERT(inSuite, resolver.InitializeParsing(kTestCommissionableNode.Serialized(), srvRecord) == CHIP_NO_ERROR); // once initialized, parsing should be ready however no IP address is available NL_TEST_ASSERT(inSuite, resolver.IsActiveCommissionParse()); NL_TEST_ASSERT(inSuite, resolver.GetMissingRequiredInformation().HasOnly(IncrementalResolver::RequiredInformationBitFlags::kIpAddress)); NL_TEST_ASSERT(inSuite, resolver.GetTargetHostName() == kTestHostName.Serialized()); // Send an IP for an irrelevant host name { Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::aabb:ccdd:2233:4455", addr)); CallOnRecord(inSuite, resolver, IPResourceRecord(kIrrelevantHostName.Full(), addr)); } // Send a useful IP address here { Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::abcd:ef11:2233:4455", addr)); CallOnRecord(inSuite, resolver, IPResourceRecord(kTestHostName.Full(), addr)); } // Send another IP address { Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::f0f1:f2f3:f4f5:1234", addr)); CallOnRecord(inSuite, resolver, IPResourceRecord(kTestHostName.Full(), addr)); } // Send a TXT record for an irrelevant host name // Note that TXT entries should be addressed to the Record address and // NOT to the server name for A/AAAA records { const char * entries[] = { "some", "foo=bar", "x=y=z", "a=", // unused data "SII=123" // Sleepy idle interval }; CallOnRecord(inSuite, resolver, TxtResourceRecord(kTestHostName.Full(), entries)); } // Adding actual text entries that are useful // Note that TXT entries should be addressed to the Record address and // NOT to the server name for A/AAAA records { const char * entries[] = { "foo=bar", // unused data "SAI=321", // sleepy active interval "D=22345", // Long discriminator "VP=321+654", // VendorProduct "DN=mytest" // Device name }; CallOnRecord(inSuite, resolver, TxtResourceRecord(kTestCommissionableNode.Full(), entries)); } // Resolver should have all data NL_TEST_ASSERT(inSuite, !resolver.GetMissingRequiredInformation().HasAny()); // At this point taking value should work. Once taken, the resolver is reset. DiscoveredNodeData nodeData; NL_TEST_ASSERT(inSuite, resolver.Take(nodeData) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, !resolver.IsActive()); // validate data as it was passed in NL_TEST_ASSERT(inSuite, nodeData.resolutionData.numIPs == 2); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.port == 0x1234); NL_TEST_ASSERT(inSuite, !nodeData.resolutionData.supportsTcp); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.GetMrpRetryIntervalActive().HasValue()); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.GetMrpRetryIntervalActive().Value() == chip::System::Clock::Milliseconds32(321)); NL_TEST_ASSERT(inSuite, !nodeData.resolutionData.GetMrpRetryIntervalIdle().HasValue()); Inet::IPAddress addr; NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::abcd:ef11:2233:4455", addr)); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.ipAddress[0] == addr); NL_TEST_ASSERT(inSuite, Inet::IPAddress::FromString("fe80::f0f1:f2f3:f4f5:1234", addr)); NL_TEST_ASSERT(inSuite, nodeData.resolutionData.ipAddress[1] == addr); // parsed txt data for discovered nodes NL_TEST_ASSERT(inSuite, nodeData.commissionData.longDiscriminator == 22345); NL_TEST_ASSERT(inSuite, nodeData.commissionData.vendorId == 321); NL_TEST_ASSERT(inSuite, nodeData.commissionData.productId == 654); NL_TEST_ASSERT(inSuite, strcmp(nodeData.commissionData.deviceName, "mytest") == 0); } const nlTest sTests[] = { // Tests for helper class NL_TEST_DEF("StoredServerName", TestStoredServerName), // // Actual resolver tests NL_TEST_DEF("Creation", TestCreation), // NL_TEST_DEF("InactiveResetOnInitError", TestInactiveResetOnInitError), // NL_TEST_DEF("StartOperational", TestStartOperational), // NL_TEST_DEF("StartCommissionable", TestStartCommissionable), // NL_TEST_DEF("StartCommissioner", TestStartCommissioner), // NL_TEST_DEF("ParseOperational", TestParseOperational), // NL_TEST_DEF("ParseCommissionable", TestParseCommissionable), // NL_TEST_SENTINEL() // }; } // namespace int TestChipDnsSdIncrementalResolve() { nlTestSuite theSuite = { "IncrementalResolve", &sTests[0], nullptr, nullptr }; nlTestRunner(&theSuite, nullptr); return nlTestRunnerStats(&theSuite); } CHIP_REGISTER_TEST_SUITE(TestChipDnsSdIncrementalResolve)
9a99e2c4e30a629b572f46f7d71137294e9b634c
208d7311c5e08388958bdb7fdd3bf23ca6f894fe
/Codeforces AC Solutions/1113A.cpp
65cc1f7f9b4171a510da5890ff48b9a5674c51a6
[]
no_license
krashish8/Online-Judge-Solutions
1aeed9c5feccca777217bdc9cd4abeff75084f41
ed472631b45f1d3e57a6a499579971db19c0385b
refs/heads/master
2020-04-29T22:19:23.996456
2019-06-07T03:31:20
2019-06-07T03:31:20
176,443,587
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,348
cpp
/* Problem Name: A - Sasha and His Trip Problem ID: 1113A Problem URL: https://codeforces.com/contest/1113/problem/A Author: Ashish Kumar (ashishkr23438) Solution ID: 50006158 Solution Time: 2019-02-16 19:54:56 Language: GNU C++17 Time consumed: 31 ms Memory consumed: 0 KB */ #include<bits/stdc++.h> using namespace std; #define int long long int #define double long double #define pb push_back #define pii pair<int,int> #define fi first #define se second #define rep(i,a,b) for (int i=a; i<b; ++i) #define dbg(x) { cerr<<#x<<": "<<x<< endl; } #define dbg2(x,y) { cerr<<#x<<": "<<x<<" , "<<#y<<": "<<y<<endl; } #define dbg3(x,y,z) { cerr<<#x<<": "<<x<<" , "<<#y<<": "<<y<<" , "<<#z<<": "<<z<<endl; } #define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) #ifndef LOCAL #define endl &#39;\n&#39; #endif const int inf = INT_MAX; const double eps = 0.0000001; const double PI = acos(-1.0); const int MOD = 1e9+7; const int N = 5e5+5; signed main(){ #ifdef LOCAL //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif IOS; int n, v; cin >> n >> v; int s = 0; int m = n-1; for (int i = 1; i < n; ++i) { int t = min(v,m); if(i!=1 && t>=1) t=1; if(t<0) t=0; s=s+i*t; m-=t; // dbg2(t,i*t); } cout << s; return 0; }
345f9d2205f39a921f609dff943dff41193eda27
efc4772a909c360a5c82a80d5bda0971415a0361
/core/lib_rtsp/liveMedia/H264or5VideoRTPSink.cpp
7a9ea84ff18a0cddaee6205e2b68391779d82eac
[]
no_license
jasonblog/RTMPLive
7ce6c9f950450eedff21ebae7505a62c9cb9f403
92a018f50f7df19c255b106dc7f584b90f1fe116
refs/heads/master
2020-04-22T01:31:04.504948
2019-02-13T05:30:19
2019-02-13T05:30:19
170,016,488
0
1
null
null
null
null
UTF-8
C++
false
false
8,632
cpp
#include "H264or5VideoRTPSink.hh" #include "H264or5VideoStreamFramer.hh" class H264or5Fragmenter : public FramedFilter { public: H264or5Fragmenter(int hNumber, UsageEnvironment& env, FramedSource* inputSource, unsigned inputBufferMax, unsigned maxOutputPacketSize); virtual ~H264or5Fragmenter(); Boolean lastFragmentCompletedNALUnit() const { return fLastFragmentCompletedNALUnit; } private: virtual void doGetNextFrame(); private: static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); void afterGettingFrame1(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); private: int fHNumber; unsigned fInputBufferSize; unsigned fMaxOutputPacketSize; unsigned char* fInputBuffer; unsigned fNumValidDataBytes; unsigned fCurDataOffset; unsigned fSaveNumTruncatedBytes; Boolean fLastFragmentCompletedNALUnit; }; H264or5VideoRTPSink ::H264or5VideoRTPSink(int hNumber, UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, u_int8_t const* vps, unsigned vpsSize, u_int8_t const* sps, unsigned spsSize, u_int8_t const* pps, unsigned ppsSize) : VideoRTPSink(env, RTPgs, rtpPayloadFormat, 90000, hNumber == 264 ? "H264" : "H265"), fHNumber(hNumber), fOurFragmenter(NULL), fFmtpSDPLine(NULL) { if (vps != NULL) { fVPSSize = vpsSize; fVPS = new u_int8_t[fVPSSize]; memmove(fVPS, vps, fVPSSize); } else { fVPSSize = 0; fVPS = NULL; } if (sps != NULL) { fSPSSize = spsSize; fSPS = new u_int8_t[fSPSSize]; memmove(fSPS, sps, fSPSSize); } else { fSPSSize = 0; fSPS = NULL; } if (pps != NULL) { fPPSSize = ppsSize; fPPS = new u_int8_t[fPPSSize]; memmove(fPPS, pps, fPPSSize); } else { fPPSSize = 0; fPPS = NULL; } } H264or5VideoRTPSink::~H264or5VideoRTPSink() { fSource = fOurFragmenter; delete[] fFmtpSDPLine; delete[] fVPS; delete[] fSPS; delete[] fPPS; stopPlaying(); Medium::close(fOurFragmenter); fSource = NULL; } Boolean H264or5VideoRTPSink::continuePlaying() { if (fOurFragmenter == NULL) { fOurFragmenter = new H264or5Fragmenter(fHNumber, envir(), fSource, OutPacketBuffer::maxSize, ourMaxPacketSize() - 12); } else { fOurFragmenter->reassignInputSource(fSource); } fSource = fOurFragmenter; return MultiFramedRTPSink::continuePlaying(); } void H264or5VideoRTPSink::doSpecialFrameHandling(unsigned, unsigned char *, unsigned, struct timeval framePresentationTime, unsigned) { if (fOurFragmenter != NULL) { H264or5VideoStreamFramer* framerSource = (H264or5VideoStreamFramer *) (fOurFragmenter->inputSource()); if (((H264or5Fragmenter *) fOurFragmenter)->lastFragmentCompletedNALUnit() && framerSource != NULL && framerSource->pictureEndMarker()) { setMarkerBit(); framerSource->pictureEndMarker() = False; } } setTimestamp(framePresentationTime); } Boolean H264or5VideoRTPSink ::frameCanAppearAfterPacketStart(unsigned char const *, unsigned) const { return False; } H264or5Fragmenter::H264or5Fragmenter(int hNumber, UsageEnvironment& env, FramedSource* inputSource, unsigned inputBufferMax, unsigned maxOutputPacketSize) : FramedFilter(env, inputSource), fHNumber(hNumber), fInputBufferSize(inputBufferMax + 1), fMaxOutputPacketSize(maxOutputPacketSize), fNumValidDataBytes(1), fCurDataOffset(1), fSaveNumTruncatedBytes(0), fLastFragmentCompletedNALUnit(True) { fInputBuffer = new unsigned char[fInputBufferSize]; } H264or5Fragmenter::~H264or5Fragmenter() { delete[] fInputBuffer; detachInputSource(); } void H264or5Fragmenter::doGetNextFrame() { if (fNumValidDataBytes == 1) { fInputSource->getNextFrame(&fInputBuffer[1], fInputBufferSize - 1, afterGettingFrame, this, FramedSource::handleClosure, this); } else { if (fMaxSize < fMaxOutputPacketSize) { envir() << "H264or5Fragmenter::doGetNextFrame(): fMaxSize (" << fMaxSize << ") is smaller than expected\n"; } else { fMaxSize = fMaxOutputPacketSize; } fLastFragmentCompletedNALUnit = True; if (fCurDataOffset == 1) { if (fNumValidDataBytes - 1 <= fMaxSize) { memmove(fTo, &fInputBuffer[1], fNumValidDataBytes - 1); fFrameSize = fNumValidDataBytes - 1; fCurDataOffset = fNumValidDataBytes; } else { if (fHNumber == 264) { fInputBuffer[0] = (fInputBuffer[1] & 0xE0) | 28; fInputBuffer[1] = 0x80 | (fInputBuffer[1] & 0x1F); } else { u_int8_t nal_unit_type = (fInputBuffer[1] & 0x7E) >> 1; fInputBuffer[0] = (fInputBuffer[1] & 0x81) | (49 << 1); fInputBuffer[1] = fInputBuffer[2]; fInputBuffer[2] = 0x80 | nal_unit_type; } memmove(fTo, fInputBuffer, fMaxSize); fFrameSize = fMaxSize; fCurDataOffset += fMaxSize - 1; fLastFragmentCompletedNALUnit = False; } } else { unsigned numExtraHeaderBytes; if (fHNumber == 264) { fInputBuffer[fCurDataOffset - 2] = fInputBuffer[0]; fInputBuffer[fCurDataOffset - 1] = fInputBuffer[1] & ~0x80; numExtraHeaderBytes = 2; } else { fInputBuffer[fCurDataOffset - 3] = fInputBuffer[0]; fInputBuffer[fCurDataOffset - 2] = fInputBuffer[1]; fInputBuffer[fCurDataOffset - 1] = fInputBuffer[2] & ~0x80; numExtraHeaderBytes = 3; } unsigned numBytesToSend = numExtraHeaderBytes + (fNumValidDataBytes - fCurDataOffset); if (numBytesToSend > fMaxSize) { numBytesToSend = fMaxSize; fLastFragmentCompletedNALUnit = False; } else { fInputBuffer[fCurDataOffset - 1] |= 0x40; fNumTruncatedBytes = fSaveNumTruncatedBytes; } memmove(fTo, &fInputBuffer[fCurDataOffset - numExtraHeaderBytes], numBytesToSend); fFrameSize = numBytesToSend; fCurDataOffset += numBytesToSend - numExtraHeaderBytes; } if (fCurDataOffset >= fNumValidDataBytes) { fNumValidDataBytes = fCurDataOffset = 1; } FramedSource::afterGetting(this); } } // H264or5Fragmenter::doGetNextFrame void H264or5Fragmenter::afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { H264or5Fragmenter* fragmenter = (H264or5Fragmenter *) clientData; fragmenter->afterGettingFrame1(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); } void H264or5Fragmenter::afterGettingFrame1(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { fNumValidDataBytes += frameSize; fSaveNumTruncatedBytes = numTruncatedBytes; fPresentationTime = presentationTime; fDurationInMicroseconds = durationInMicroseconds; doGetNextFrame(); }
[ "jason_yao" ]
jason_yao
a6d90a13ef70e1e51c02115faf743f817d533a55
be43f5d4d9dd8afa57847248ccdd019dcf39f4be
/Inverse Kinematics/Inverse Kinematics/IK.cpp
52d7528d8c9c747512c53a3609841abf0a79d2c2
[]
no_license
xxie5/cs184
469bd0a64bfc201a993dfd9ac50a65a66fd599d5
143a765d28283a69cebecc4479d23cf26046c1b3
refs/heads/master
2020-05-19T11:16:08.002158
2013-12-03T05:35:25
2013-12-03T05:35:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
55
cpp
#include "IK.h" IK::IK(void) { } IK::~IK(void) { }
0d5ef3777581a9509ec757960e07ad55fd17d5a2
c02e6a950d0bf2ee8c875c70ad707df8b074bb8e
/build/Android/Debug/bimcast/app/src/main/include/Uno.Text.UTF8Encoding.h
4c63b93ff6bb65bf6dcc7853ea951d6404e12a13
[]
no_license
BIMCast/bimcast-landing-ui
38c51ad5f997348f8c97051386552509ff4e3faf
a9c7ff963d32d625dfb0237a8a5d1933c7009516
refs/heads/master
2021-05-03T10:51:50.705052
2016-10-04T12:18:22
2016-10-04T12:18:22
69,959,209
0
0
null
null
null
null
UTF-8
C++
false
false
814
h
// This file was generated based on C:\ProgramData\Uno\Packages\UnoCore\0.35.8\Source\Uno\Text\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Text.Encoding.h> namespace g{namespace Uno{namespace Text{struct Decoder;}}} namespace g{namespace Uno{namespace Text{struct UTF8Encoding;}}} namespace g{ namespace Uno{ namespace Text{ // public sealed class UTF8Encoding :414 // { ::g::Uno::Text::Encoding_type* UTF8Encoding_typeof(); void UTF8Encoding__ctor_1_fn(UTF8Encoding* __this); void UTF8Encoding__GetDecoder_fn(UTF8Encoding* __this, ::g::Uno::Text::Decoder** __retval); void UTF8Encoding__New1_fn(UTF8Encoding** __retval); struct UTF8Encoding : ::g::Uno::Text::Encoding { void ctor_1(); static UTF8Encoding* New1(); }; // } }}} // ::g::Uno::Text
07503d9f3e02a5e2ae0b987b99d0b48589e89af5
d2249116413e870d8bf6cd133ae135bc52021208
/Ultimate TCP-IP/ActiveX/utftp/MarshalEvents.cpp
de869dec34c608b8655d51714825711680f4685f
[]
no_license
Unknow-man/mfc-4
ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5
b58abf9eb4c6d90ef01b9f1203b174471293dfba
refs/heads/master
2023-02-17T18:22:09.276673
2021-01-20T07:46:14
2021-01-20T07:46:14
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,096
cpp
// ================================================================= // Ultimate TCP-IP v4.2 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ================================================================= // MarshalEvents.cpp: implementation of the CMarshalEvents class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MarshalEvents.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction //////////////////////////////////////////////////////////////////////
8a8fa90787cdc0ad65ff5e85bd239abcf432e243
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/content/common/dom_storage/dom_storage_map.cc
0a6b0176a982782fd1472f607f811dd6c183c3fe
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
6,703
cc
// Copyright 2013 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 "content/common/dom_storage/dom_storage_map.h" #include "base/logging.h" namespace content { namespace { size_t size_in_memory(const base::string16& key, const size_t value) { return key.length() * sizeof(base::char16) + sizeof(size_t); } size_t size_in_memory(const base::string16& key, const base::NullableString16& value) { return (key.length() + value.string().length()) * sizeof(base::char16); } size_t size_in_storage(const base::string16& key, const size_t value) { return key.length() * sizeof(base::char16) + value; } size_t size_in_storage(const base::string16& key, const base::NullableString16& value) { // Null value indicates deletion. So, key size is not counted. return value.is_null() ? 0 : size_in_memory(key, value); } } // namespace DOMStorageMap::DOMStorageMap(size_t quota) : DOMStorageMap(quota, false) {} DOMStorageMap::DOMStorageMap(size_t quota, bool has_only_keys) : storage_used_(0), memory_used_(0), quota_(quota), has_only_keys_(has_only_keys) { ResetKeyIterator(); } DOMStorageMap::~DOMStorageMap() {} unsigned DOMStorageMap::Length() const { return has_only_keys_ ? keys_only_.size() : keys_values_.size(); } base::NullableString16 DOMStorageMap::Key(unsigned index) { if (index >= Length()) return base::NullableString16(); while (last_key_index_ != index) { if (last_key_index_ > index) { if (has_only_keys_) --keys_only_iterator_; else --keys_values_iterator_; --last_key_index_; } else { if (has_only_keys_) ++keys_only_iterator_; else ++keys_values_iterator_; ++last_key_index_; } } return base::NullableString16(has_only_keys_ ? keys_only_iterator_->first : keys_values_iterator_->first, false); } bool DOMStorageMap::SetItem( const base::string16& key, const base::string16& value, base::NullableString16* old_value) { if (has_only_keys_) { size_t value_size = value.length() * sizeof(base::char16); return SetItemInternal<KeysMap>(&keys_only_, key, value_size, nullptr); } else { base::NullableString16 new_value(value, false); if (old_value) *old_value = base::NullableString16(); return SetItemInternal<DOMStorageValuesMap>(&keys_values_, key, new_value, old_value); } } bool DOMStorageMap::RemoveItem( const base::string16& key, base::string16* old_value) { if (has_only_keys_) { return RemoveItemInternal<KeysMap>(&keys_only_, key, nullptr); } else { base::NullableString16 nullable_old; bool success = RemoveItemInternal<DOMStorageValuesMap>( &keys_values_, key, old_value ? &nullable_old : nullptr); if (success && old_value) *old_value = nullable_old.string(); return success; } } base::NullableString16 DOMStorageMap::GetItem(const base::string16& key) const { DCHECK(!has_only_keys_); DOMStorageValuesMap::const_iterator found = keys_values_.find(key); if (found == keys_values_.end()) return base::NullableString16(); return found->second; } void DOMStorageMap::ExtractValues(DOMStorageValuesMap* map) const { DCHECK(!has_only_keys_); *map = keys_values_; } void DOMStorageMap::SwapValues(DOMStorageValuesMap* values) { // Note: A pre-existing file may be over the quota budget. DCHECK(!has_only_keys_); keys_values_.swap(*values); storage_used_ = CountBytes(keys_values_); memory_used_ = storage_used_; ResetKeyIterator(); } void DOMStorageMap::TakeKeysFrom(const DOMStorageValuesMap& values) { // Note: A pre-existing file may be over the quota budget. DCHECK(has_only_keys_); keys_only_.clear(); memory_used_ = 0; storage_used_ = 0; for (const auto& item : values) { keys_only_[item.first] = item.second.string().length() * sizeof(base::char16); // Do not count size of values for memory usage. memory_used_ += size_in_memory(item.first, 0 /* unused */); storage_used_ += size_in_storage(item.first, item.second); } ResetKeyIterator(); } DOMStorageMap* DOMStorageMap::DeepCopy() const { DOMStorageMap* copy = new DOMStorageMap(quota_, has_only_keys_); copy->keys_values_ = keys_values_; copy->keys_only_ = keys_only_; copy->storage_used_ = storage_used_; copy->memory_used_ = memory_used_; copy->ResetKeyIterator(); return copy; } void DOMStorageMap::ResetKeyIterator() { keys_only_iterator_ = keys_only_.begin(); keys_values_iterator_ = keys_values_.begin(); last_key_index_ = 0; } // static size_t DOMStorageMap::CountBytes(const DOMStorageValuesMap& values) { if (values.empty()) return 0; size_t count = 0; for (const auto& pair : values) count += size_in_storage(pair.first, pair.second); return count; } template <typename MapType> bool DOMStorageMap::SetItemInternal(MapType* map_type, const base::string16& key, const typename MapType::mapped_type& value, typename MapType::mapped_type* old_value) { const auto found = map_type->find(key); size_t old_item_size = 0; size_t old_item_memory = 0; if (found != map_type->end()) { old_item_size = size_in_storage(key, found->second); old_item_memory = size_in_memory(key, found->second); if (old_value) *old_value = found->second; } size_t new_item_size = size_in_storage(key, value); size_t new_storage_used = storage_used_ - old_item_size + new_item_size; // Only check quota if the size is increasing, this allows // shrinking changes to pre-existing files that are over budget. if (new_item_size > old_item_size && new_storage_used > quota_) return false; (*map_type)[key] = value; ResetKeyIterator(); storage_used_ = new_storage_used; memory_used_ = memory_used_ + size_in_memory(key, value) - old_item_memory; return true; } template <typename MapType> bool DOMStorageMap::RemoveItemInternal( MapType* map_type, const base::string16& key, typename MapType::mapped_type* old_value) { const auto found = map_type->find(key); if (found == map_type->end()) return false; storage_used_ -= size_in_storage(key, found->second); memory_used_ -= size_in_memory(key, found->second); if (old_value) *old_value = found->second; map_type->erase(found); ResetKeyIterator(); return true; } } // namespace content
cf3d056d77375b035a996ed2903853b3f0b37263
37345f863fd417e122a66fcb841ff88c7405c66a
/OrcsandTrolls/OrcsandTrolls/Character .cpp
79c57b1cfd2c196ed7e66dae61a01d67304d88cc
[]
no_license
davemau51074/Orcs-Vs-Trolls
f25bb2cc0707af96932fe34704c43137f9b069ca
63cd8431fa1619a075b35f80cd22f13201982c22
refs/heads/master
2021-01-12T03:00:25.914715
2017-01-05T21:04:46
2017-01-05T21:04:46
78,146,895
0
0
null
null
null
null
UTF-8
C++
false
false
545
cpp
#include <iostream> #include "Troll.h" #include "Orc.h" #include "Character.h" using namespace std; Character::Character() { float health = 100; float strength = 100; float magic = 100; float mana = 100; } void Character::sayStats() { cout << "Stats for your Enemy are :" << std::endl; cout << "Strength:"<< strength << std::endl; cout << "Magic:" << magic << std::endl;; cout << "Mana:"<< mana << std::endl;; } void Character::soldierNumber() { cout << "Your first soldier will have "; } void Character::battleBB() { }
[ "david o gorman" ]
david o gorman
e793ddd3e5ad8514e0785cc59611d595650a6e64
611d8dff7e268a212a04f775932adfaafdbded6f
/lab_heaps/heap.cpp
6141cdc2189809c2aa37ada35ec261193f2e67c1
[]
no_license
dkaraca/past-projects
24992ee69e49e6892ff76b1aa6a527d95fbf8343
a0224a84477e49c0469adcbe6fceab8241e027c3
refs/heads/master
2021-01-25T07:55:09.205410
2017-08-01T20:14:39
2017-08-01T20:14:39
93,686,262
0
0
null
null
null
null
UTF-8
C++
false
false
3,952
cpp
/** * @file heap.cpp * Implementation of a heap class. */ #include <math.h> template <class T, class Compare> size_t heap<T, Compare>::root() const { /// @todo Update to return the index you are choosing to be your root. return 1; } template <class T, class Compare> size_t heap<T, Compare>::leftChild( size_t currentIdx ) const { /// @todo Update to return the index of the left child. return (currentIdx*2); } template <class T, class Compare> size_t heap<T, Compare>::rightChild( size_t currentIdx ) const { /// @todo Update to return the index of the right child. return (currentIdx*2)+1; } template <class T, class Compare> size_t heap<T, Compare>::parent( size_t currentIdx ) const { /// @todo Update to return the index of the parent. return floor(currentIdx/2); } template <class T, class Compare> bool heap<T, Compare>::hasAChild( size_t currentIdx ) const { /// @todo Update to return whether the given node has a child if(_elems[currentIdx*2]) return true; return false; } template <class T, class Compare> size_t heap<T, Compare>::maxPriorityChild( size_t currentIdx ) const { /// @todo Update to return the index of the child with highest priority /// as defined by higherPriority() if(higherPriority(_elems[leftChild(currentIdx)], _elems[rightChild(currentIdx)])) return leftChild(currentIdx); return rightChild(currentIdx); } template <class T, class Compare> void heap<T, Compare>::heapifyDown( size_t currentIdx ) { /// @todo Implement the heapifyDown algorithm. //if(currentIdx == _elems.size()) return; //int size = _elems.size(); if((currentIdx*2)<_elems.size()){ size_t child = maxPriorityChild(currentIdx); if(higherPriority(_elems[child], _elems[currentIdx])){ std::swap(_elems[child], _elems[currentIdx]); heapifyDown(child); } } } template <class T, class Compare> void heap<T, Compare>::heapifyUp( size_t currentIdx ) { if( currentIdx == root() ) return; size_t parentIdx = parent( currentIdx ); if( higherPriority( _elems[ currentIdx ], _elems[ parentIdx ] ) ) { std::swap( _elems[ currentIdx ], _elems[ parentIdx ] ); heapifyUp( parentIdx ); } } template <class T, class Compare> heap<T, Compare>::heap() { /// @todo Depending on your implementation, this function may or may /// not need modifying //_elems.resize(2); _elems.push_back(0); } template <class T, class Compare> heap<T, Compare>::heap( const std::vector<T> & elems ) { /// @todo Construct a heap using the buildHeap algorithm //_elems.resize(elems.size()+1); //int size = int size = elems.size(); _elems.push_back(0); for(int i = 0; i<size; i++) _elems.push_back(elems[i]); for(int i = parent(_elems.size()); i>=1; i--) heapifyDown(i); //for(int i = 1; i<size; i++) // push(elems[i-1]); //for(int i = 0; i<size; i++){ // _elems[i] = _elems[i+1]; ///////////////// if(i == (size-1)) _elems.resize(elems.size()); //} } template <class T, class Compare> T heap<T, Compare>::pop() { /// @todo Remove, and return, the element with highest priority int size = _elems.size(); T tmp = _elems[1]; _elems[1] = _elems[size-1]; _elems.pop_back(); heapifyDown(1); return tmp; } template <class T, class Compare> T heap<T, Compare>::peek() const { /// @todo Return, but do not remove, the element with highest priority return _elems[1]; } template <class T, class Compare> void heap<T, Compare>::push( const T & elem ) { /// @todo Add elem to the heap int size = _elems.size(); //int capacity = _elems.capacity(); //if(size == capacity) growArray(); _elems.resize(_elems.size()+1); _elems[size] = elem; heapifyUp(size); } template <class T, class Compare> bool heap<T, Compare>::empty() const { /// @todo Determine if the heap is empty return _elems.size()==1; } template <class T, class Compare> void heap<T, Compare>::growArray() { _elems.resize(_elems.size()*2); }
8c9e3b27a390bc095d47189ff81fcc54ad69e350
da544eaeed8fe21303f90fdfdb2de5ee46dc64f0
/codeforces/cf_educational_30/d.cpp
de1f674e4838f15681e7337db996989acd5e9d64
[]
no_license
hasan-kamal/Competitive-Programming
7dc1f0d05edfe1611e408e31c8fae83bc79eac93
aeb20b5e93743579e3f4a91ca1885835cb6ee433
refs/heads/master
2023-08-08T22:24:08.763615
2023-07-30T04:12:23
2023-07-30T04:12:23
139,876,312
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
/* @author hasankamal */ #include <iostream> #include <vector> #define pb push_back using namespace std; typedef vector<int> vi; vi make_seq(int s, int e){ vi ans; for(int i = s; i <= e; i++) ans.pb(i); return ans; } vi get_valid_perm(int s, int e, int k, int indent = 0){ // string sp = ""; // for(int t = 0; t < indent; t++) // sp += "\t"; // cout << sp << "entering " << s << ", " << e << " " << k << endl; if(k == 1) return make_seq(s, e); int n = e - s + 1; int k1; if(k >= 1 + ((n / 2) << 1)){ k1 = ((n / 2) << 1) - 1; }else k1 = 1; vi lhs = get_valid_perm(e - n / 2 + 1, e, k1, indent + 1); vi rhs = get_valid_perm(s, e - n / 2, k - k1 - 1, indent + 1); vi ans = lhs; for(int r : rhs) ans.pb(r); // cout << sp << "exiting " << s << ", " << e << " " << k << endl; return ans; } int main(){ int n, k; cin >> n >> k; if((k & 1) == 0 || k > (n << 1) - 1){ cout << "-1"; return 0; } if(n == 1){ cout << "1"; return 0; } vi perm = get_valid_perm(1, n, k); for(int v : perm) cout << v << " "; return 0; }
82db3c81a825a9aef0c764a246022a8feab5a10b
b3037f52eefe799d552439683f6858b32cabbf6f
/Doorbell.ino
85257e4a6cbc2e350ba0c5d7aaf1d60f46701138
[]
no_license
sofwona/bell_project
da1bad99885953bf2a4e5c30b14d883887b1788a
73c5a910933ec269b3269b66d5a28489a9d0802d
refs/heads/master
2021-01-18T15:56:21.695980
2017-03-31T11:40:23
2017-03-31T11:40:23
86,696,881
0
0
null
null
null
null
UTF-8
C++
false
false
1,889
ino
#define BLYNK_PRINT Serial #include <SPI.h> #include <Ethernet.h> #include <BlynkSimpleEthernet.h> #include <SimpleTimer.h> //You should get Auth Token in the Blynk App //Go to the Project Settings (nut icon) char auth[]= "e91c67ddbfa5487b8d055427dbe7608f"; /*IPAddress server_ip (46, 101, 143, 255); byte arduino_mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED}; IPAddress arduino_ip (192, 168, 1, 120); IPAddress dns_ip (192, 168, 1, 254); IPAddress gateway_ip (192, 168, 1, 254); IPAddress subnet_mask (255, 255, 255, 0);*/ SimpleTimer timer; WidgetLCD lcd(V1); void setup() { Serial.begin(9600); Blynk.begin(auth/*, server_ip, 8442, arduino_ip, dns_ip, gateway_ip, subnet_mask, arduino_mac*/); while (Blynk.connect() == false) { //wait until connected } } void notifyOnButtonPress () { //invert state, since button is "Active Low" int isButtonPressed = !digitalRead (2); if (isButtonPressed){ BLYNK_LOG("Button is Pressed"); Blynk.notify("Please open up! Somebody is at the door!"); lcd.clear();//Use it to clear the LCD Widget lcd.print(4, 0, "Open");//use: (position X: 0-15, position Y: 0-1, "Message you want to print") lcd.print(4, 1, "The Door!"); } } void emailOnButtonPress () { int isButtonPressed = !digitalRead (2);//Invert state, since button is "Active LOW" if (isButtonPressed)//You can write any condition to trigger e-mail sending { BLYNK_LOG("Button is pressed"); //This can be seen in the Serial Monitor Blynk.email("[email protected]", "Subject: Doorbell", "Please open up! Somebody is at the door!"); lcd.clear();//use it to clear the LCD Widget lcd.print(4, 0, "Open"); //use: (position X: 0-15, position Y: 0-1, "Message you want to print") lcd.print(4, 1, "The Door!"); } } void loop (){ //put your main code here, to run repeatedly: Blynk.run(); timer.run(); }
338f0b79eb39d233f6e10c4693354659d5f42d65
1cb73a0dece5dc21e8e7e4f88f96d1ad9e92da1a
/thread/thread_mutex.cpp
b4fbcb0edf12efe78e72e63477ece73df21fc9be
[]
no_license
keineahnung2345/cpp-code-snippets
c2af1c7eaaddc2f0c262022743f6d42fec7fede4
d2b48129f2c1bae1940a213517bfa3597c802aee
refs/heads/master
2023-08-16T17:13:55.414432
2023-08-16T02:07:24
2023-08-16T02:07:24
160,354,272
52
16
null
null
null
null
UTF-8
C++
false
false
1,526
cpp
#include <iostream> //https://kheresy.wordpress.com/2012/07/11/multi-thread-programming-in-c-thread-p2/ #define LINUX //MODE 1: no lock, MODE 2 and 3 : two different way of using lock #define MODE 1 #ifdef LINUX #include <thread> #include <mutex> using namespace std; #else #include "mingw-std-threads/mingw.thread.h" #include "mingw-std-threads/mingw.mutex.h" using namespace mingw_stdthread; #endif #if MODE == 2 || MODE == 3 std::mutex gMutex; #endif void OutputValue(int n) { #if MODE == 1 #elif MODE == 2 gMutex.lock(); #elif MODE == 3 std::unique_lock<std::mutex> mLock(gMutex); #endif std::cout << "Number:"; for (int i = 0; i < n; ++i) { this_thread::sleep_for(std::chrono::duration<int, std::milli>(5)); std::cout << " " << i; } std::cout << std::endl; #if MODE == 1 #elif MODE == 2 gMutex.unlock(); #elif MODE == 3 #endif } int main( int argc, char** argv ){ std::cout << "Normal function call" << std::endl; OutputValue( 3 ); OutputValue( 4 ); std::cout << "\nCall function with thread" << std::endl; thread mThread1( OutputValue, 3 ); thread mThread2( OutputValue, 4 ); mThread1.join(); mThread2.join(); std::cout << std::endl; return 0; } /* MODE 1: Normal function call Number: 0 1 2 Number: 0 1 2 3 Call function with thread Number:Number: 0 0 1 1 22 3 */ /* MODE 2 and 3: Normal function call Number: 0 1 2 Number: 0 1 2 3 Call function with thread Number: 0 1 2 Number: 0 1 2 3 */
36bacc6f49b0d2349d56de1bde1c4197050de2e0
ae956d4076e4fc03b632a8c0e987e9ea5ca89f56
/SDK/TBP_UI_SystemMenuAudioSettings_classes.h
53e48227edfd8599f314ce68cb5e90c0e79f8457
[]
no_license
BrownBison/Bloodhunt-BASE
5c79c00917fcd43c4e1932bee3b94e85c89b6bc7
8ae1104b748dd4b294609717142404066b6bc1e6
refs/heads/main
2023-08-07T12:04:49.234272
2021-10-02T15:13:42
2021-10-02T15:13:42
638,649,990
1
0
null
2023-05-09T20:02:24
2023-05-09T20:02:23
null
UTF-8
C++
false
false
6,852
h
#pragma once // Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass TBP_UI_SystemMenuAudioSettings.TBP_UI_SystemMenuAudioSettings_C // 0x0080 (FullSize[0x0310] - InheritedSize[0x0290]) class UTBP_UI_SystemMenuAudioSettings_C : public UTigerMenuWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0290(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UTBP_UI_CheckBox_C* AllowBackgroundAudio; // 0x0298(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* DialogueVolumeSlider; // 0x02A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_CheckBox_C* EnableDolbyAtmos; // 0x02A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_CheckBox_C* EnableVoiceChat; // 0x02B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* MasterVolumeSlider; // 0x02B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* MicVolumeSlider; // 0x02C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* MusicVolumeSlider; // 0x02C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* SfxVolumeSlider; // 0x02D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UVerticalBox* SystemMenuSubItemBox; // 0x02D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTigerStyledRichTextBlock* TigerStyledRichTextBlock_166; // 0x02E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTigerStyledRichTextBlock* TigerStyledRichTextBlock_383; // 0x02E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_CheckBox_C* UsePushToTalk; // 0x02F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* VideoVolumeSlider; // 0x02F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SliderWBox_C* VoiceChatVolumeSlider; // 0x0300(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTBP_UI_SystemMenuItem_C* CurrentlySelectedSystemMenuItem; // 0x0308(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("WidgetBlueprintGeneratedClass TBP_UI_SystemMenuAudioSettings.TBP_UI_SystemMenuAudioSettings_C"); return ptr; } void UpdateVolumeSettings(); void Update_Voip_Settings(); void Construct(); void OnOpen(); void BndEvt__AutoSprintToggle_K2Node_ComponentBoundEvent_4_OnCheckStateChanged__DelegateSignature(bool bIsChecked); void BndEvt__MasterVolumeSlider_K2Node_ComponentBoundEvent_0_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__SfxVolumeSlider_K2Node_ComponentBoundEvent_1_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__VoiceChatVolumeSlider_K2Node_ComponentBoundEvent_2_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__DialogueVolumeSlider_K2Node_ComponentBoundEvent_3_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__VideoVolumeSlider_K2Node_ComponentBoundEvent_5_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__MusicVolumeSlider_K2Node_ComponentBoundEvent_6_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__TBP_UI_SystemMenuAudioSettings_UsePushToTalk_K2Node_ComponentBoundEvent_7_OnCheckStateChanged__DelegateSignature(bool bIsChecked); void BndEvt__TBP_UI_SystemMenuAudioSettings_MicVolumeSlider_K2Node_ComponentBoundEvent_8_OnValueChanged__DelegateSignature(float BoxValue, float SliderValue); void BndEvt__TBP_UI_SystemMenuAudioSettings_MuteWhenMinimized_K2Node_ComponentBoundEvent_9_OnCheckStateChanged__DelegateSignature(bool bIsChecked); void BndEvt__TBP_UI_SystemMenuAudioSettings_EnableDolbyAtmos_K2Node_ComponentBoundEvent_7_OnCheckStateChanged__DelegateSignature(bool bIsChecked); void ExecuteUbergraph_TBP_UI_SystemMenuAudioSettings(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
513e3fe931ce4614f5cdfab04077a5c2e7e53c5a
2710157eabaa334c9582152d5e5087ba87876638
/include/Circle.h
1379b0ab4d0a872c4135df9f827ff723f273b2e6
[]
no_license
GNGenesis/Lucity
f4fed328fb2b65f18a68ac6cc2528220fb1d97d8
03fa5cf930ba0ad9157250477f4072d5f6868c33
refs/heads/master
2020-03-18T07:24:06.006109
2018-07-10T21:07:11
2018-07-10T21:07:11
134,450,080
1
2
null
null
null
null
UTF-8
C++
false
false
382
h
#ifndef CIRCLE_H_ #define CIRCLE_H_ #include "Vec2.h" class Circle { public: float x; float y; float r; Circle(); Circle(float x, float y, float r); ~Circle(); void SetCenter(float x, float y); void SetCenter(Vec2 pos); void SetRadius(float r); bool Contains(float a, float b); bool Contains(Vec2 p); Vec2 GetCenter(); }; #endif /* CIRCLE_H_ */
19cdae3ddaade8780cefd30679c0830dcf08bb7d
540caabe83af65d221fecf4fd4cebe17412ea37d
/TinyGame/Cantan/CantanStage.h
cc90236ca1c1e50a68a05126bd75f3375b02e168
[]
no_license
rodrigobmg/GameProject
939b54d1455bb1ece555a3a9e377216ca7a69c78
80c7df303406e72ea2794e323f027f8fb83c6162
refs/heads/master
2020-04-27T19:33:45.861972
2019-03-02T09:54:46
2019-03-02T09:54:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,652
h
#include "StageBase.h" #include "CantanLevel.h" #include "RenderUtility.h" namespace Cantan { class LevelStage : public StageBase { typedef StageBase BaseClass; public: LevelStage(){} virtual bool onInit() { ::Global::GUI().cleanupWidget(); mCellManager.buildIsotropicMap( 4 ); restart(); return true; } virtual void onEnd() { } virtual void onUpdate( long time ) { BaseClass::onUpdate( time ); int frame = time / gDefaultTickTime; for( int i = 0 ; i < frame ; ++i ) tick(); updateFrame( frame ); } void onRender( float dFrame ) { Graphics2D& g = Global::GetGraphics2D(); bool drawCoord = false; g.setTextColor(Color3ub(0,0,255)); FixString< 256 > str; RenderUtility::SetBrush( g , EColor::Yellow ); for( MapCellManager::CellVec::iterator iter = mCellManager.mCells.begin() , itEnd = mCellManager.mCells.end(); iter != itEnd ; ++iter ) { MapCell* cell = *iter; Vector2 rPos = convertToScreenPos( cell->pos ); g.drawCircle( rPos , 3 ); if ( drawCoord ) g.drawText( rPos , str.format("(%d %d)" , cell->pos.x , cell->pos.y) ); } RenderUtility::SetPen( g , EColor::Blue ); for( MapCellManager::CellEdgeVec::iterator iter = mCellManager.mCellEdges.begin() , itEnd = mCellManager.mCellEdges.end(); iter != itEnd ; ++iter ) { MapCell::Edge* edge = *iter; Vector2 rPosA = convertToScreenPos( edge->v[0]->pos ); Vector2 rPosB = convertToScreenPos( edge->v[1]->pos ); g.drawLine( rPosA , rPosB ); } RenderUtility::SetBrush( g , EColor::Red ); for( MapCellManager::CellVertexVec::iterator iter = mCellManager.mCellVertices.begin() , itEnd = mCellManager.mCellVertices.end(); iter != itEnd ; ++iter ) { MapCell::Vertex* v = *iter; Vector2 rPos = convertToScreenPos( v->pos ); g.drawCircle( rPos , 3 ); if ( drawCoord ) g.drawText( rPos , str.format("(%d %d)" , v->pos.x , v->pos.y) ); } } Vector2 convertToScreenPos( Vec2i const& cPos ) { #define SQRT_3 1.73205080756887729 return Vector2( ::Global::GetDrawEngine()->getScreenSize() / 2 ) + 40 * Vector2( 0.5 * SQRT_3 * cPos.x , cPos.y - 0.5 * cPos.x ); } void restart() { } void tick() { } void updateFrame( int frame ) { } bool onMouse( MouseMsg const& msg ) { if ( !BaseClass::onMouse( msg ) ) return false; return true; } bool onKey( unsigned key , bool isDown ) { if ( !isDown ) return false; switch( key ) { case Keyboard::eR: restart(); break; } return false; } protected: MapCellManager mCellManager; }; }//namespace Cantan
fda74156492b58d7d73b64f4f06c42332456b0a7
4e9e492e752e43400f0b728f854f842d13ba4bad
/CodeForces/1065G.cpp
d76596fe8f988d704a2172f3747ba01d5a8aa2b7
[]
no_license
jocagos/competitive
0ac497b7e6c30e548e0d7e298df0f2892e7e03b1
89c8467b56d4be10c80189b154e2edadfb6a9f3f
refs/heads/master
2021-07-05T23:53:23.607682
2021-05-27T22:17:13
2021-05-27T22:17:13
84,216,647
0
0
null
null
null
null
UTF-8
C++
false
false
4,352
cpp
#include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/trie_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/priority_queue.hpp> using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef unsigned long long i64; typedef long double ld; typedef pair<int, int> ii; typedef pair<double, double> dd; typedef pair<ii, int> tern; typedef pair<ii, ii> quad; typedef vector<int> vi; typedef vector<double> vd; typedef vector<ii> vii; typedef vector<dd> vdd; typedef vector<tern> vtern; typedef vector<quad> vquad; // minHeap, BinomialHeap and FibonacciHeap for later use, policy based data structures template <class T> using minHeap = __gnu_pbds::priority_queue<T, greater<T>, pairing_heap_tag>; template <class T> using minBinHeap = __gnu_pbds::priority_queue<T, greater<T>, rc_binomial_heap_tag>; template <class T> using minFHeap = __gnu_pbds::priority_queue<T, greater<T>, thin_heap_tag>; template <class T> using maxFHeap = __gnu_pbds::priority_queue<T, less<T>, thin_heap_tag>; template <class T> using maxBinHeap = __gnu_pbds::priority_queue<T, less<T>, rc_binomial_heap_tag>; // ordered set and map with policy, policy based data structures template <class T> using oSet = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <class T, class U> using oMap = tree<T, U, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // patricia trie, policy based data structure typedef trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update> Trie; // constants const int INF = (int) 1e9 + 7; const ll LLINF = (ll) 4e18 + 7; const double pi = acos(-1.0); // /* slaps vector */ This bad boy can hold SO MANY // values to compare a value to! template<typename T> bool isIn( T const &value, std::vector<T>& v ){ return std::find( v.begin(), v.end(), value ) != v.end(); } // /* slaps initializer_list */ And THIS bad boy can hold // ANY initializer_list with the same type as the value // to look forward! template<typename T> bool isIn( T const &value, std::initializer_list<T> v ){ return std::find( v.begin(), v.end(), value ) != v.end(); } // easy access/use #define fastio ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define view(x) cout << #x << ": " << x << endl; #define sz(c) (int)((c).size()) #define all(c) (c).begin(), (c).end() #define in( a, b, x ) ( (a) <= (x) and (x) <= (b) ) #define justN(c, n) (c).begin(), (c).begin() + n #define sq(a) (a) * (a) #define fi first #define se second #define PB push_back #define EB emplace_back #define MP make_pair #define MT make_tuple #define UNIQUE(a) sort(all(a)), (a).erase(unique(all(a)), (a).end()) #define FOR(i, start, end) for( int i(start); i < (end); ++ i ) #define REP(i, end) FOR(i, 0, end) #define FORD(i, start, end) for( int i(start); i >= end; -- i ) #define gcd(a, b) __gcd(a, b) // bit related builtin functions #define idxLSB(x) __builtin_ffs(x) #define idxLSBl(x) __builtin_ffsl(x) #define idxLSBll(x) __builtin_ffsll(x) #define leftZeroBits(x) __builtin_clz(x) #define leftZeroBitsl(x) __builtin_clzl(x) #define leftZeroBitsll(x) __builtin_clzll(x) #define rightZeroBits(x) __builtin_ctz(x) #define rightZeroBitsl(x) __builtin_ctzl(x) #define rightZeroBitsll(x) __builtin_ctzll(x) #define cntSetBits(x) __builtin_popcount(x) #define cntSetBitsl(x) __builtin_popcountl(x) #define cntSetBitsll(x) __builtin_popcountll(x) int main(void){ int n, k, m; // auto lex = []( string& left, string& right ){ // int idx = 0, len = min( left.length(), right.length() ); // while( idx < len and left[idx] == right[idx] ) idx ++; // if( idx == len ) return left.length() == len; // else return left[idx] < right[idx]; // }; fastio; cin >> n >> k >> m; vector<string> fibos( n + 1 ); fibos[0] = "0"; fibos[1] = "1"; FOR( i, 2, n + 1 ){ fibos[i] = fibos[i - 2] + fibos[i - 1]; } // nth_element( fibos.begin(), fibos.begin() + n, fibos.end() ); sort( all( fibos ) ); if( m > fibos[k - 1].length() ) cout << fibos[k - 1] << '\n'; else{ REP( i, m ) cout << fibos[k - 1][i]; cout << '\n'; } for( auto x : fibos ) cout << x << '\n'; return 0; }
a67cd7a78307d22bc91e1668c16ba23ce2457fb7
820960e798dd51a21b7304b44a61ca7018e266ed
/PSL/variable.h
948a2b9e03c74084812ef62330d3cf8bf2e4aa3e
[]
no_license
Silica/compiler
6dda361e4a6252191aaaefc20e6fbf89e342d311
1a9c4ca3a8f52aa46786a646dd9cfa3937556468
refs/heads/main
2022-10-31T15:05:44.558945
2012-06-19T10:27:40
2012-06-19T10:27:40
4,711,315
2
1
null
null
null
null
SHIFT_JIS
C++
false
false
16,155
h
#ifdef PSL_DEBUG #define PSL_DUMP(x) void dump x #else #define PSL_DUMP(x) #endif #ifdef PSL_THREAD_SAFE #undef PSL_USE_VARIABLE_MEMORY_MANAGER #undef PSL_SHARED_GLOBAL #define PSL_CONST_STATIC const #else #define PSL_CONST_STATIC const static #endif #ifdef PSL_USE_VARIABLE_MEMORY_MANAGER #define PSL_MEMORY_MANAGER(x) static void *operator new(size_t t){return MemoryManager<sizeof(x)>::Next();}static void operator delete(void *ptr){MemoryManager<sizeof(x)>::Release(ptr);} #else #define PSL_MEMORY_MANAGER(x) #endif #if defined(PSL_USE_VARIABLE_MEMORY_MANAGER) && !defined(PSL_SHARED_GLOBAL) #define PSL_TEMPORARY_ENV(x) Environment &x = StaticObject::envtemp() #define PSL_TEMPORARY_ENV0(x) Environment &x = StaticObject::envtemp() #else #define PSL_TEMPORARY_ENV(x) Environment x #define PSL_TEMPORARY_ENV0(x) Environment x(0) #endif class variable { #ifndef _WIN32 typedef long long __int64; #endif public: #include "pstring.h" struct PSLException { enum ErrorCode { Scope, } errorcode; PSLException(ErrorCode e):errorcode(e){} }; typedef variable(*function)(variable&); typedef variable(*method)(variable&,variable&); typedef unsigned long hex; enum Type { NIL, INT, HEX, FLOAT, STRING, POINTER, RARRAY, OBJECT, METHOD, CFUNCTION, CMETHOD, CPOINTER, THREAD, BCFUNCTION, CCMETHOD, }; class Function{}; template<class C>class Method{}; private: class Variable; #include "container.h" friend class rsv; public: variable() {x = new Variable();} variable(bool b) {x = new Variable(static_cast<int>(b));} variable(int i) {x = new Variable(i);} variable(long i) {x = new Variable(static_cast<int>(i));} variable(unsigned u) {x = new Variable(static_cast<int>(u));} variable(hex h) {x = new Variable(h);} variable(double d) {x = new Variable(d);} variable(const char *s) {x = new Variable(s);} variable(const wchar_t *s) {x = new Variable(s);} variable(const string &s) {x = new Variable(s);} variable(function f) {x = new Variable(f);} variable(method f) {x = new Variable(f);} variable(void *p) {x = new Variable(p);} variable(const variable &v) {x = v.x->clone();} variable(Type t) {x = new Variable(t);} variable(const rsv &v) {x = v.get()->ref();} ~variable() {x->finalize();} Type type() const {return x->type();} bool type(Type t) const {return x->type() == t;} variable clone() const {return *this;} variable &substitution(const variable &v) {x->substitution(v.x);return *this;} variable &assignment(const variable &v) {x->assignment(v.x);return *this;} variable &operator=(const variable &v) {x->substitution(v.x);return *this;} variable &operator->*(const variable &v) {x->assignment(v.x);return *this;} // 何せ余ってる演算子がこれなので… variable &operator=(const rsv &v) {x->finalize();x = v.get()->ref();return *this;} variable &operator=(function f) { if (f == NULL) { variable v = 0; x->substitution(v.x); } else { variable v = f; x->substitution(v.x); } return *this; } #define OP(n,o) variable &operator o##=(const variable &v) {x->n(v.x);return *this;}\ variable operator o(const variable &v) const {variable z = *this;z.x->n(v.x);return z;} OP(add,+) OP(sub,-) OP(mul,*) OP(div,/) OP(mod,%) OP(oand,&) OP(oor,|) OP(oxor,^) OP(shl,<<) OP(shr,>>) #undef OP #define CMP(n,o) bool operator o(const variable &v) const {return x->n(v.x);} CMP(eq,==) CMP(ne,!=) CMP(le,<=) CMP(ge,>=) CMP(lt,<) CMP(gt,>) #undef CMP variable operator+(); variable operator-() const {variable v = *this;v.x->neg();return v;} variable operator*() const {return x->deref();} variable operator~() const {variable v = *this;v.x->Compl();return v;} bool operator!() const {return !x->toBool();} variable &operator++(); variable &operator--(); variable operator++(int i); // suf variable operator--(int i); operator int() const {return x->toInt();} operator double() const {return x->toDouble();} operator bool() const {return x->toBool();} operator char() const {return x->toInt();} operator signed char() const {return x->toInt();} operator unsigned char() const {return x->toInt();} operator short() const {return x->toInt();} operator unsigned short() const {return x->toInt();} operator unsigned() const {return x->toInt();} operator long() const {return x->toInt();} operator unsigned long() const {return x->toInt();} operator __int64() const {return x->toInt();} #ifdef __clang__ operator unsigned long long() const {return x->toInt();} #else operator unsigned __int64() const {return x->toInt();} #endif operator float() const {return x->toDouble();} operator long double() const {return x->toDouble();} operator string() const {return x->toString();} string toString() const {return x->toString();} operator void*() const {return x->toPointer();} template<class T> T *toPointer() const {return static_cast<T*>(x->toPointer());} template<class T> operator T*() const {return static_cast<T*>(x->toPointer());} #ifndef PSL_THREAD_SAFE #ifdef __BORLANDC__ template<> #endif operator const char*() const {static string s;s = x->toString();return s.c_str();} const char *c_str() const {static string s;s = x->toString();return s.c_str();} #endif variable operator[](size_t i) {return x->index(i);} variable operator[](int i) {return x->index(minusindex(i));} variable operator[](const char *s) {return x->child(s);} variable operator[](const string &s) {return x->child(s);} variable operator[](const variable &v) { if (v.type(STRING) || v.type(FLOAT)) return x->child(v); if (v.type(RARRAY)) { int s = minusindex(v.x->index(0)->toInt()); int l = v.x->index(1)->toInt(); variable r(RARRAY); if (l < 0) for (int i = 0; i > l; --i) r.x->push(x->index(s+i)); else for (int i = 0; i < l; ++i) r.x->push(x->index(s+i)); return r.x; } int i = minusindex(v); return x->index(i); } size_t length() const {return x->length();} bool exist(const string &s) const {return x->exist(s);} void push(const variable &v) {return x->push(v.x);} variable keys() {return x->keys();} bool set(const string &s, const variable &v) {return x->set(s, v);} void del(const string &s) {return x->del(s);} private: int minusindex(int i) { if (i < 0) { int l = x->length(); i = l + i; if (i < 0) i = 0; } return i; } #include "PSLlib.h" #include "tokenizer.h" #include "parser.h" class Variable { public: Variable() {rc = 1;x = new vObject();} Variable(int i) {rc = 1;x = new vInt(i);} Variable(hex h) {rc = 1;x = new vHex(h);} Variable(double d) {rc = 1;x = new vFloat(d);} Variable(const string &s) {rc = 1;x = new vString(s);} Variable(function f) {rc = 1;x = new vCFunction(f);} Variable(method f) {rc = 1;x = new vCMethod(f, NULL);} Variable(void *p) {rc = 1;x = new vCPointer(p);} Variable(Variable *v) {rc = 1;x = new vPointer(v);} Variable(Type t, int i) {rc = 1;x = new vRArray(i);} Variable(Type t){rc = 1;switch (t){ case NIL: x = new vBase();break; case INT: x = new vInt(0);break; case HEX: x = new vHex(0);break; case FLOAT: x = new vFloat(0);break; case STRING: x = new vString("");break; case POINTER: x = new vPointer();break; case RARRAY: x = new vRArray();break; case THREAD: x = new vThread();break; default: x = new vObject();break; }} #ifdef PSL_USE_DESTRUCTOR void finalize() {if (rc==1) {x->destructor();delete this;}else --rc;} #else void finalize() {if (!--rc) delete this;} #endif void safedelete() {rsv v(new Variable(x), 0);x = NULL;x = new vInt(0);} bool searchcount(Variable *v, int &c) { if (rc & 0x40000000) return true; if (rc & 0x80000000) { if (v == this) ++c; return false; } rc |= 0x80000000; x->searchcount(v, c); return false; } void markstart(int c) { if ((rc & 0xFFFFFF) != c) mark(); } void mark() { if (rc & 0x40000000) return; rc |= 0x40000000; x->mark(); } void unmark(unsigned long m) { rc &= m; } void destructor_unmark() { if (rc & 0x40000000) return; x->destructor(); } void delete_unmark() { if (rc & 0x40000000) return; safedelete(); } Type type() const {return x->type();} void substitution(Variable *v) {x = x->substitution(v);x->method_this(this);} void assignment(Variable *v) {x = x->assignment(v);x->method_this(this);} void gset(Variable *v) {x = x->assignment(v);} void add(Variable *v) {x->add(v);x->method_this(this);} #define OP(n) void n(Variable *v) {x->n(v);} OP(sub) OP(mul) OP(div) OP(mod) OP(oand) OP(oor) OP(oxor) OP(shl) OP(shr) #undef OP #define CMP(n) bool n(Variable *v) {return x->n(v);} CMP(eq) CMP(ne) CMP(le) CMP(ge) CMP(lt) CMP(gt) #undef CMP void neg() {x->neg();} void Compl(){x->Compl();} Variable *deref() {Variable *v = x->deref();return v ? v : this;} bool toBool() const {return x->toBool();} int toInt() const {return x->toInt();} double toDouble() const {return x->toDouble();} string toString() const {return x->toString();} void *toPointer() const {return x->toPointer();} size_t length() const {return x->length();} bool exist(const string &s) const {return x->exist(s);} void push(Variable *v) {x->push(v);} Variable *index(size_t t) {Variable *v = x->index(t);return v ? v : this;} Variable *child(const string &s) {Variable *v = x->child(s);return v ? v : this;} Variable *keys() {Variable *v = x->keys();v->rc = 0;return v;} Variable *getifexist(const string &s) {return x->getifexist(s);} bool set(const string &s, const variable &v) {return x->set(s, v);} void del(const string &s) {x->del(s);} #include "bytecode.h" private: #include "environment.h" friend class Parser; friend class variable; public: void prepare(Environment &env) {x->prepare(env, this);} void prepareInstance(Environment &env) {x->prepareInstance(env, this);} variable call(Environment &env, variable &arg) {return x->call(env, arg, this);} rsv instance(Environment &env) {return x->instance(env, this);} Variable(Code *c) {rc = 1;x = new vObject(c);} size_t codelength() {return x->codelength();} Code *getcode() {return x->getcode();} void pushcode(OpCode *c){return x->pushcode(c);} void pushlabel(const string &s){return x->pushlabel(s);} void write(const string &s, bytecode &b){x->write(s, b);} private: class vBase { public: PSL_MEMORY_MANAGER(vBase) vBase() {} virtual ~vBase(){} virtual Type type() const {return NIL;} virtual vBase *clone() {return new vBase();} virtual void searchcount(Variable *v, int &c){} virtual void mark(){} virtual void destructor(){} virtual vBase *substitution(Variable *v) {vBase *x = v->bclone();delete this;return x;} virtual vBase *assignment(Variable *v) {vBase *x = v->bclone();delete this;return x;} #define OP(n) virtual void n(Variable *v) {} OP(add) OP(sub) OP(mul) OP(div) OP(mod) OP(oand) OP(oor) OP(oxor) OP(shl) OP(shr) #undef OP #define CMP(n) virtual bool n(Variable *v) {return false;} CMP(eq) CMP(ne) CMP(le) CMP(ge) CMP(lt) CMP(gt) #undef CMP virtual void neg() {} virtual void Compl(){} virtual Variable *deref() {return NULL;} virtual bool toBool() const {return false;} virtual int toInt() const {return 0;} virtual double toDouble() const {return 0;} virtual string toString() const {return "";} virtual void *toPointer() const {return NULL;} virtual size_t length() const {return 0;} virtual bool exist(const string &s) const {return false;} virtual Variable *index(size_t t) {return NULL;} virtual Variable *child(const string &s) {return NULL;} virtual void push(Variable *v){} virtual Variable *keys() {return new Variable();} virtual Variable *getifexist(const string &s) {return NULL;} virtual bool set(const string &s, const variable &v) {return false;} virtual void del(const string &s) {} virtual void method_this(Variable *v) {} virtual void prepare(Environment &env, Variable *v) { variable a = env.pop(); variable c(v->clone(), 0); env.push(c.substitution(a)); } virtual void prepareInstance(Environment &env, Variable *v) {env.push(rsv(v->clone(), 0));} virtual rsv call(Environment &env, variable &arg, Variable *v) {return variable(NIL);} virtual rsv instance(Environment &env, Variable *v) {return v->clone();} virtual size_t codelength() {return 0;} virtual Code *getcode() {return NULL;} virtual void pushcode(OpCode *c){delete c;} virtual void pushlabel(const string &s){} virtual void write(const string &s, bytecode &b){} virtual void dump(){PSL_PRINTF(("vBase\n"));} } *x; private: int rc; ~Variable() {delete x;} public: Variable(vBase *v) {rc = 1;x = v;x->method_this(this);} vBase *bclone() {return x->clone();} Variable *clone() {return new Variable(x->clone());} Variable *ref() {++rc;return this;} PSL_DUMP((){PSL_PRINTF(("rc:%4d, ", rc));x->dump();}) #ifdef PSL_USE_VARIABLE_MEMORY_MANAGER static void *operator new(size_t t) {return VMemoryManager::Next();} static void operator delete(void *ptr) {VMemoryManager::Release(ptr);} #endif private: #include "vdata.h" friend class vRArray; template<class F>Variable(Function z, F f) {rc = 1;x = BCFunction(f);} template<class C, class M>Variable(Method<C> z, M m) {rc = 1;x = CCMethod<C>(m);} } *x; typedef Variable::Environment Environment; #ifdef PSL_USE_VARIABLE_MEMORY_MANAGER #include "memory.h" #endif variable(Variable *v) {x = v->ref();} variable(Variable *v, int i) {x = v;} variable(Type t, Variable *v) {x = new Variable(v);} void gset(const variable &v) {x->gset(v.x);} void prepare(Environment &env) {x->prepare(env);} size_t codelength() {return x->codelength();} Variable::Code *getcode() {return x->getcode();} void pushcode(Variable::OpCode *c) {return x->pushcode(c);} void pushlabel(const string &s) {return x->pushlabel(s);} friend class PSLVM; friend class Parser; friend class Variable::vBase; friend class Variable::vCMethod; friend class Variable::CALL; friend class Variable::bcreader; friend class Variable::Code; public: typedef Variable::bytecode buffer; rsv ref() const {return x;} rsv pointer() const {return variable(POINTER, x);} variable operator()() {PSL_TEMPORARY_ENV(env);variable v;return x->call(env, v);} variable operator()(const variable &arg) {PSL_TEMPORARY_ENV(env);variable v = arg.ref();return x->call(env, v);} #ifndef PSL_SHARED_GLOBAL variable operator()(Environment &env, variable &arg) {return x->call(env, arg);} variable instance(Environment &env) {return x->instance(env);} #endif variable instance() {PSL_TEMPORARY_ENV(env);return x->instance(env);} #define cva(n) const variable &arg##n #define ap(n) arg.push(arg##n); #define CALL(z,y) variable operator()z{variable arg(RARRAY);y PSL_TEMPORARY_ENV(env);return x->call(env, arg);} CALL((cva(1),cva(2)), ap(1)ap(2)) CALL((cva(1),cva(2),cva(3)), ap(1)ap(2)ap(3)) CALL((cva(1),cva(2),cva(3),cva(4)), ap(1)ap(2)ap(3)ap(4)) CALL((cva(1),cva(2),cva(3),cva(4),cva(5)), ap(1)ap(2)ap(3)ap(4)ap(5)) CALL((cva(1),cva(2),cva(3),cva(4),cva(5),cva(6)), ap(1)ap(2)ap(3)ap(4)ap(5)ap(6)) #undef CALL #undef ap #define ap(n) x->push(arg##n.x); #define LIST(n,z,y) variable z{x = new Variable(RARRAY, n);y} LIST(2,(cva(1),cva(2)), ap(1)ap(2)) LIST(3,(cva(1),cva(2),cva(3)), ap(1)ap(2)ap(3)) LIST(4,(cva(1),cva(2),cva(3),cva(4)), ap(1)ap(2)ap(3)ap(4)) LIST(5,(cva(1),cva(2),cva(3),cva(4),cva(5)), ap(1)ap(2)ap(3)ap(4)ap(5)) LIST(6,(cva(1),cva(2),cva(3),cva(4),cva(5),cva(6)), ap(1)ap(2)ap(3)ap(4)ap(5)ap(6)) #undef LIST #undef ap #undef cva template<class F>variable(Function z, F f) {x = new Variable(z, f);} template<class C, class M>variable(Method<C> z, M m) {x = new Variable(z, m);} PSL_DUMP((){x->dump();}) };
[ "Puro@puro001.(none)" ]
Puro@puro001.(none)
9ba296c858546adf86963499e7b88a1c73b45865
d1cf34b4d5280e33ebcf1cd788b470372fdd5a26
/codeforces/ac/0/055/E.cpp
c30b5f9f4eea6869f5d000fcfb62231269b27a2f
[]
no_license
watashi/AlgoSolution
985916ac511892b7e87f38c9b364069f6b51a0ea
bbbebda189c7e74edb104615f9c493d279e4d186
refs/heads/master
2023-08-17T17:25:10.748003
2023-08-06T04:34:19
2023-08-06T04:34:19
2,525,282
97
32
null
2020-10-09T18:52:29
2011-10-06T10:40:07
C++
UTF-8
C++
false
false
1,234
cpp
#include <iostream> #include <algorithm> using namespace std; struct Point { long long x, y; Point() { } Point(long long x, long long y) : x(x), y(y) { } }; Point operator-(const Point& lhs, const Point& rhs) { return Point(lhs.x - rhs.x, lhs.y - rhs.y); } long long operator*(const Point& lhs, const Point& rhs) { return lhs.x * rhs.y - lhs.y * rhs.x; } long long s[1 << 20]; Point p[1 << 20], q; int main() { int n, re; long long l, r, ans; for (int i = 2; i < (1 << 20); ++i) { s[i] += s[i - 1] + i - 1; } cin >> n; for (int i = 0; i < n; ++i) { cin >> p[i].x >> p[i].y; p[n + i] = p[i]; } cin >> re; for (int i = 0; i < re; ++i) { cin >> q.x >> q.y; for (int j = 0; j < n; ++j) { if ((p[j] - q) * (p[j + 1] - q) >= 0) { cout << 0 << endl; goto NEXT; } } ans = 0; for (int j = 0, k = 0; j < n; ++j) { while ((p[j] - q) * (p[k] - q) <= 0) { ++k; } l = k - 1 - j; r = n + j - k; ans += s[l] + s[r]; } cout << 1LL * n * (n - 1) * (n - 2) / 6 - ans / 2 << endl; NEXT: continue; } return 0; } //# When Who Problem Lang Verdict Time Memory //251430 Jan 14, 2011 1:46:03 PM watashi E - Very simple problem GNU C++ Accepted 800 ms 25944 KB
f3d955c0f791cb6016ffe882d95928b6d3f7c207
34bcb3c7d3fa1ccd42fb573ab282868d19e08ecb
/SDK/SoT_BP_msc_hurdygurdy_smp_01_a_Wieldable_classes.hpp
57a0be58dddf1429265bbfc7ddf6d611124b4743
[]
no_license
Rioo-may/SoT-SDK
7da49ae8aaabb833a92f1b7ec60c9aadc48e0ca2
178f6f4ea2670a8a2239f20ee18e0d548c586fe2
refs/heads/master
2023-01-03T08:42:52.472446
2020-11-01T23:09:33
2020-11-01T23:09:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_msc_hurdygurdy_smp_01_a_Wieldable_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_msc_hurdygurdy_smp_01_a_Wieldable.BP_msc_hurdygurdy_smp_01_a_Wieldable_C // 0x0000 (0x08D0 - 0x08D0) class ABP_msc_hurdygurdy_smp_01_a_Wieldable_C : public ABP_HurdyGurdy_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_msc_hurdygurdy_smp_01_a_Wieldable.BP_msc_hurdygurdy_smp_01_a_Wieldable_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
3ce3055ad8ba2dc3eb516da82ae8600af4a77b8f
24f3b4653e796bc5502dddf759980793471ba642
/Experis/C++/ExceptionHandler/TException_t.h
d1fefae5aea61b7653d635c845a14637a9b04b7c
[]
no_license
madmandidj/github_work
286ccc1df71f8306f54e285ff9cc9c0cff9f5968
f2f5779d8398fa60466ab2ae25fc02b157699074
refs/heads/master
2018-12-16T20:15:16.867844
2018-10-03T19:58:25
2018-10-03T19:58:25
116,257,701
0
0
null
null
null
null
UTF-8
C++
false
false
2,700
h
#ifndef __TEXCEPTION_T_H__ #define __TEXCEPTION_T_H__ #include <iostream> #include <string> /******************************************************************************** Test for this file is included in MemoryManager exercise for function SetPosition ********************************************************************************/ template <class T> class TException_t { public: TException_t(T const _object, const std::string& _description, const std::string& _sourceFileName, size_t _lineNumber); TException_t(const TException_t& _tException); TException_t& operator= (const TException_t& _tException); ~TException_t(); T GetObject() const; const std::string& GetDescription() const; const std::string& GetSourceFileName() const; size_t GetLineNumber() const; private: T m_object; //TODO: should be T std::string m_description; std::string m_sourceFileName; size_t m_lineNumber; }; template <class T> std::ostream& operator<< (std::ostream& _os, TException_t<T>& _tException) { _os << "Description: " << _tException.GetDescription() << ", File: " << _tException.GetSourceFileName() << ", Line: " << _tException.GetLineNumber() << std::endl; return _os; } template <class T> TException_t<T>::TException_t(T const _object, const std::string& _description, const std::string& _sourceFileName, size_t _lineNumber) { if (0 == _object) { /* TODO: handle invalid pointer */ } m_object = _object; m_description.assign(_description); m_sourceFileName.assign(_sourceFileName); m_lineNumber = _lineNumber; } template <class T> TException_t<T>::TException_t(const TException_t& _tException) { m_object = _tException.m_object; m_description.assign(_tException.m_description); m_sourceFileName.assign(_tException.m_sourceFileName); m_lineNumber = _tException.m_lineNumber; } template <class T> TException_t<T>& TException_t<T>::operator= (const TException_t& _tException) { if (this != &_tException) { m_object = _tException.m_object; m_description.assign(_tException.m_description); m_sourceFileName.assign(_tException.m_sourceFileName); m_lineNumber = _tException.m_lineNumber; } return *this; } template <class T> TException_t<T>::~TException_t(){} template <class T> T TException_t<T>::GetObject() const { return m_object; } template <class T> const std::string& TException_t<T>::GetDescription() const { return m_description; } template <class T> const std::string& TException_t<T>::GetSourceFileName() const { return m_sourceFileName; } template <class T> size_t TException_t<T>::GetLineNumber() const { return m_lineNumber; } #endif /* #ifndef __TEXCEPTION_T_H__ */
90f8170ae4f3b7b7bbd9e2b47c380fda0909e145
384d1b5e6a63ad656ba6ee5ed790d4a84bf5c7d3
/src/Sensor/GenericVoltage.h
cf95fcc62dafb12796ebef0e47438258c8bf3fef
[ "MIT" ]
permissive
kalmanolah/kalmon-fw
2069932f3e7dc2823a49cae54745706ddc1a008d
382be821afa3c1e4f6e0b93c4d85fa870550a20b
refs/heads/master
2020-06-02T14:43:45.913851
2015-09-17T20:56:06
2015-09-17T20:56:06
28,712,111
2
0
null
null
null
null
UTF-8
C++
false
false
768
h
/** * Generic voltage sensor. */ #ifndef generic_voltage_h #define generic_voltage_h #include "GenericAnalogSensor.h" /* * GenericVoltage * * A class that is in charge of managing a relatively generic voltage sensor. */ class GenericVoltage: public GenericAnalogSensor { protected: uint8_t sample_count = 1; float coefficient = 1.0; public: GenericVoltage(uint8_t input_pin, uint8_t sample_count = 1, float coefficient = 1.0): GenericAnalogSensor(input_pin), sample_count(sample_count), coefficient(coefficient) {}; void read(); inline float getLevel() const { return ((((float) this->level / (float) this->sample_count) / (float) 1024.0) * 5.0) / (float) this->coefficient; }; }; #endif
2d4be5bd7e7cfb8ad62fbcd654eb9ea5bfddf482
98410335456794507c518e361c1c52b6a13b0b39
/sprayMASCOTTELAM2/0.23/dQ
4326d3a6a7d175e4cf72c5d9d46fd60833becf81
[]
no_license
Sebvi26/MASCOTTE
d3d817563f09310dfc8c891d11b351ec761904f3
80241928adec6bcaad85dca1f2159f6591483986
refs/heads/master
2022-10-21T03:19:24.725958
2020-06-14T21:19:38
2020-06-14T21:19:38
270,176,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,559
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format binary; class volScalarField; location "0.23"; object dQ; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 2 -3 0 0 0 0]; internalField uniform 0; boundaryField { inlet { type calculated; value uniform 0; } outlet { type calculated; value uniform 0; } bottom1 { type calculated; value uniform 0; } bottom2 { type calculated; value uniform 0; } top1 { type calculated; value uniform 0; } top2 { type calculated; value uniform 0; } defaultFaces { type empty; } } // ************************************************************************* //
a66a37422a578e337e024c8acebf9af460266736
ec4778a5e799888bcc6c4b9355b7d4577f7a591c
/3_Semestr/GameOfLife/Rule1.h
9b4ecf20d9ca41ca0e16bf9ff36c39b5eb58971e
[]
no_license
Cristina-F/16212_Fefelova
ec9ea4f4c9ff237daf927ccf8807e7c3f122ba91
2826afd6fe1062bb02ce925cc9a483583cdd692b
refs/heads/master
2021-03-27T14:16:58.139936
2018-01-25T11:26:36
2018-01-25T11:26:36
69,357,483
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
#ifndef RULE1_H #define RULE1_H #include "Rule.h" class Field; class Rule1 : public Rule { public: Rule1(); ~Rule1() override; void change( Field * field, Field * newField, int liveNeighbors, int x, int y ) override; const std::string getName() override; private: const int THREE_NEIGHBORS = 3; const int TWO_NEIGHBORS = 2; const bool LIFE_CELL = 1; const bool DEAD_CELL = 0; const std:: string name_ = "B3/S23"; }; #endif // RULE1_H
987d6e2a5ec41a841c507596b269f9f36da3ee87
c3ca68aea5d824e75576c50dce68a6392cf5afbe
/UVA/10926_How_Many_Dependencies.cpp
2981cc11317db5496d384dab796084ebbf75d320
[]
no_license
ManuelLoaizaVasquez/competitive-programming-solutions
bddcacdc54a63afc5f7fd5be19dc0a8afe47eb16
b502fcc2774b3f4286393f00e6e009cb30fa2c53
refs/heads/master
2021-06-18T14:29:06.103654
2021-03-05T14:23:41
2021-03-05T14:23:41
144,772,199
2
0
null
null
null
null
UTF-8
C++
false
false
1,838
cpp
// // Created by ManuelLoaiza on 05/26/18 // #include <bits/stdc++.h> using namespace std; const int MAX_N = 100; vector <int> adj[MAX_N]; bool visited[MAX_N]; bool dependency[MAX_N][MAX_N]; queue <int> orderedTasks; void initialize(int n) { for (int i = 0; i < n; i++) { adj[i].clear(); visited[i] = false; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dependency[i][j] = false; } } while (not orderedTasks.empty()) { orderedTasks.pop(); } } void createGraph(int n) { for (int i = 0; i < n; i++) { int t; cin >> t; while (t--) { int x; cin >> x; x--; adj[i].push_back(x); } } } void DFS(int u) { visited[u] = true; int l = adj[u].size(); for (int i = 0; i < l; i++) { int v = adj[u][i]; if (not visited[v]) { DFS(v); } } orderedTasks.push(u); } void topologicalSort(int n) { for (int i = 0; i < n; i++) { if (not visited[i]) { DFS(i); } } } void fillDependencies(int n) { while (not orderedTasks.empty()) { int u = orderedTasks.front(); orderedTasks.pop(); int l = adj[u].size(); for (int i = 0; i < l; i++) { int v = adj[u][i]; dependency[u][v] = true; for (int w = 0; w < n; w++) { if (dependency[v][w]) { dependency[u][w] = true; } } } } } int findAnswer(int n) { int answer = -1; int maxDependencies = -1; for (int i = 0; i < n; i++) { int dependencies = 0; for (int j = 0; j < n; j++) { if (dependency[i][j]) dependencies++; } if (dependencies > maxDependencies) { answer = i; maxDependencies = dependencies; } } return answer; } void solve(int n) { initialize(n); createGraph(n); topologicalSort(n); fillDependencies(n); int answer = findAnswer(n) + 1; cout << answer << endl; } int main() { int n; while (cin >> n) { if (n == 0) break; solve(n); } return 0; }
935ff8cbd9ed23d593d9466625c35250295400dd
ae91bab8753529894f261b4b4a433ee6b0626b50
/RLForge/RLForge/RL/SDK.hpp
06204da01a0b1c4297ac3a7bbb61eb92422bb33e
[]
no_license
baipgej222/RLForge
8d6650eb3136837ac316b223002ea9b246dd6e80
600781c01c59876e17747150fe06dd253daffe2c
refs/heads/master
2020-05-19T13:44:15.408012
2018-06-06T20:42:06
2018-06-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
hpp
#pragma once // Rocket League (1.31) SDK #include <set> #include <string> #include <locale> #include "SDK/RL_Basic.hpp" #include "SDK/RL_Core_structs.hpp" #include "SDK/RL_Core_classes.hpp" #include "SDK/RL_Core_parameters.hpp" #include "SDK/RL_Engine_structs.hpp" #include "SDK/RL_Engine_classes.hpp" #include "SDK/RL_Engine_parameters.hpp" #include "SDK/RL_GFxUI_structs.hpp" #include "SDK/RL_GFxUI_classes.hpp" #include "SDK/RL_GFxUI_parameters.hpp" #include "SDK/RL_GameFramework_structs.hpp" #include "SDK/RL_GameFramework_classes.hpp" #include "SDK/RL_GameFramework_parameters.hpp" #include "SDK/RL_IpDrv_structs.hpp" #include "SDK/RL_IpDrv_classes.hpp" #include "SDK/RL_IpDrv_parameters.hpp" #include "SDK/RL_WinDrv_structs.hpp" #include "SDK/RL_WinDrv_classes.hpp" #include "SDK/RL_WinDrv_parameters.hpp" #include "SDK/RL_AkAudio_structs.hpp" #include "SDK/RL_AkAudio_classes.hpp" #include "SDK/RL_AkAudio_parameters.hpp" #include "SDK/RL_ProjectX_structs.hpp" #include "SDK/RL_ProjectX_classes.hpp" #include "SDK/RL_ProjectX_parameters.hpp" #include "SDK/RL_XAudio2_structs.hpp" #include "SDK/RL_XAudio2_classes.hpp" #include "SDK/RL_XAudio2_parameters.hpp" #include "SDK/RL_OnlineSubsystemSteamworks_structs.hpp" #include "SDK/RL_OnlineSubsystemSteamworks_classes.hpp" #include "SDK/RL_OnlineSubsystemSteamworks_parameters.hpp" #include "SDK/RL_TAGame_structs.hpp" #include "SDK/RL_TAGame_classes.hpp" #include "SDK/RL_TAGame_parameters.hpp"
ea8ced7de4f06616ef3a88d6c257e6be483f3fd6
24f26275ffcd9324998d7570ea9fda82578eeb9e
/third_party/blink/renderer/core/loader/threadable_loader.cc
6661a3f2c39ac505c707497004f84bcbd72637d0
[ "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
42,471
cc
/* * Copyright (C) 2011, 2012 Google Inc. All rights reserved. * Copyright (C) 2013, Intel Corporation * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/loader/threadable_loader.h" #include <memory> #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "services/network/public/cpp/cors/cors_error_status.h" #include "services/network/public/mojom/cors.mojom-blink.h" #include "services/network/public/mojom/fetch_api.mojom-blink.h" #include "third_party/blink/public/common/service_worker/service_worker_utils.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_security_origin.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/frame_console.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/web_feature.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/inspector/inspector_network_agent.h" #include "third_party/blink/renderer/core/inspector/inspector_trace_events.h" #include "third_party/blink/renderer/core/loader/base_fetch_context.h" #include "third_party/blink/renderer/core/loader/frame_loader.h" #include "third_party/blink/renderer/core/loader/threadable_loader_client.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h" #include "third_party/blink/renderer/platform/heap/self_keep_alive.h" #include "third_party/blink/renderer/platform/loader/cors/cors.h" #include "third_party/blink/renderer/platform/loader/cors/cors_error_string.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/shared_buffer.h" namespace blink { namespace { // Fetch API Spec: https://fetch.spec.whatwg.org/#cors-preflight-fetch-0 AtomicString CreateAccessControlRequestHeadersHeader( const HTTPHeaderMap& headers) { Vector<String> filtered_headers = cors::CorsUnsafeRequestHeaderNames(headers); if (!filtered_headers.size()) return g_null_atom; // Sort header names lexicographically. std::sort(filtered_headers.begin(), filtered_headers.end(), WTF::CodeUnitCompareLessThan); StringBuilder header_buffer; for (const String& header : filtered_headers) { if (!header_buffer.IsEmpty()) header_buffer.Append(","); header_buffer.Append(header); } return header_buffer.ToAtomicString(); } } // namespace // DetachedClient is a ThreadableLoaderClient for a "detached" // ThreadableLoader. It's for fetch requests with keepalive set, so // it keeps itself alive during loading. class ThreadableLoader::DetachedClient final : public GarbageCollected<DetachedClient>, public ThreadableLoaderClient { USING_GARBAGE_COLLECTED_MIXIN(DetachedClient); public: explicit DetachedClient(ThreadableLoader* loader) : self_keep_alive_(PERSISTENT_FROM_HERE, this), loader_(loader) {} ~DetachedClient() override {} void DidFinishLoading(uint64_t identifier) override { self_keep_alive_.Clear(); } void DidFail(const ResourceError&) override { self_keep_alive_.Clear(); } void DidFailRedirectCheck() override { self_keep_alive_.Clear(); } void Trace(Visitor* visitor) override { visitor->Trace(loader_); ThreadableLoaderClient::Trace(visitor); } private: SelfKeepAlive<DetachedClient> self_keep_alive_; // Keep it alive. const Member<ThreadableLoader> loader_; }; class ThreadableLoader::AssignOnScopeExit final { STACK_ALLOCATED(); public: AssignOnScopeExit(const KURL& from, KURL* to) : from_(from), to_(to) {} ~AssignOnScopeExit() { *to_ = from_; } private: const KURL& from_; KURL* to_; DISALLOW_COPY_AND_ASSIGN(AssignOnScopeExit); }; // Max number of CORS redirects handled in ThreadableLoader. // See https://fetch.spec.whatwg.org/#http-redirect-fetch. // //net/url_request/url_request.cc and // //services/network/cors/cors_url_loader.cc also implement the same logic // separately. static const int kMaxRedirects = 20; // static std::unique_ptr<ResourceRequest> ThreadableLoader::CreateAccessControlPreflightRequest( const ResourceRequest& request, const SecurityOrigin* origin) { const KURL& request_url = request.Url(); DCHECK(request_url.User().IsEmpty()); DCHECK(request_url.Pass().IsEmpty()); std::unique_ptr<ResourceRequest> preflight_request = std::make_unique<ResourceRequest>(request_url); preflight_request->SetHttpMethod(http_names::kOPTIONS); preflight_request->SetHttpHeaderField(http_names::kAccessControlRequestMethod, request.HttpMethod()); preflight_request->SetMode(network::mojom::RequestMode::kCors); preflight_request->SetPriority(request.Priority()); preflight_request->SetRequestContext(request.GetRequestContext()); preflight_request->SetCredentialsMode(network::mojom::CredentialsMode::kOmit); preflight_request->SetSkipServiceWorker(true); preflight_request->SetReferrerString(request.ReferrerString()); preflight_request->SetReferrerPolicy(request.GetReferrerPolicy()); if (request.IsExternalRequest()) { preflight_request->SetHttpHeaderField( http_names::kAccessControlRequestExternal, "true"); } const AtomicString request_headers = CreateAccessControlRequestHeadersHeader(request.HttpHeaderFields()); if (request_headers != g_null_atom) { preflight_request->SetHttpHeaderField( http_names::kAccessControlRequestHeaders, request_headers); } if (origin) preflight_request->SetHTTPOrigin(origin); return preflight_request; } // static std::unique_ptr<ResourceRequest> ThreadableLoader::CreateAccessControlPreflightRequestForTesting( const ResourceRequest& request) { return CreateAccessControlPreflightRequest(request, nullptr); } ThreadableLoader::ThreadableLoader( ExecutionContext& execution_context, ThreadableLoaderClient* client, const ResourceLoaderOptions& resource_loader_options, ResourceFetcher* resource_fetcher) : client_(client), execution_context_(execution_context), resource_fetcher_(resource_fetcher), resource_loader_options_(resource_loader_options), out_of_blink_cors_(RuntimeEnabledFeatures::OutOfBlinkCorsEnabled()), async_(resource_loader_options.synchronous_policy == kRequestAsynchronously), request_context_(mojom::RequestContextType::UNSPECIFIED), request_mode_(network::mojom::RequestMode::kSameOrigin), credentials_mode_(network::mojom::CredentialsMode::kOmit), timeout_timer_(execution_context_->GetTaskRunner(TaskType::kNetworking), this, &ThreadableLoader::DidTimeout), redirect_limit_(kMaxRedirects), redirect_mode_(network::mojom::RedirectMode::kFollow), override_referrer_(false) { DCHECK(client); if (!resource_fetcher_) { if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_)) scope->EnsureFetcher(); resource_fetcher_ = execution_context_->Fetcher(); } } void ThreadableLoader::Start(const ResourceRequest& request) { original_security_origin_ = security_origin_ = request.RequestorOrigin(); // Setting an outgoing referer is only supported in the async code path. DCHECK(async_ || request.HttpReferrer().IsEmpty()); bool cors_enabled = cors::IsCorsEnabledRequestMode(request.GetMode()); // kPreventPreflight can be used only when the CORS is enabled. DCHECK(request.CorsPreflightPolicy() == network::mojom::CorsPreflightPolicy::kConsiderPreflight || cors_enabled); initial_request_url_ = request.Url(); last_request_url_ = initial_request_url_; request_context_ = request.GetRequestContext(); request_mode_ = request.GetMode(); credentials_mode_ = request.GetCredentialsMode(); redirect_mode_ = request.GetRedirectMode(); if (request.GetMode() == network::mojom::RequestMode::kNoCors) { SECURITY_CHECK(cors::IsNoCorsAllowedContext(request_context_)); } cors_flag_ = cors::CalculateCorsFlag(request.Url(), GetSecurityOrigin(), request.IsolatedWorldOrigin().get(), request.GetMode()); // The CORS flag variable is not yet used at the step in the spec that // corresponds to this line, but divert |cors_flag_| here for convenience. if (cors_flag_ && request.GetMode() == network::mojom::RequestMode::kSameOrigin) { ThreadableLoaderClient* client = client_; Clear(); client->DidFail(ResourceError( request.Url(), network::CorsErrorStatus( network::mojom::CorsError::kDisallowedByMode))); return; } request_started_ = base::TimeTicks::Now(); // Save any headers on the request here. If this request redirects // cross-origin, we cancel the old request create a new one, and copy these // headers. request_headers_ = request.HttpHeaderFields(); report_upload_progress_ = request.ReportUploadProgress(); ResourceRequest new_request(request); // Set the service worker mode to none if "bypass for network" in DevTools is // enabled. bool should_bypass_service_worker = false; probe::ShouldBypassServiceWorker(execution_context_, &should_bypass_service_worker); if (should_bypass_service_worker) new_request.SetSkipServiceWorker(true); // Process the CORS protocol inside the ThreadableLoader for the // following cases: // // - When the request is sync or the protocol is unsupported since we can // assume that any service worker (SW) is skipped for such requests by // content/ code. // - When |GetSkipServiceWorker()| is true, any SW will be skipped. // - If we're not yet controlled by a SW, then we're sure that this // request won't be intercepted by a SW. In case we end up with // sending a CORS preflight request, the actual request to be sent later // may be intercepted. This is taken care of in LoadPreflightRequest() by // setting |GetSkipServiceWorker()| to true. // // From the above analysis, you can see that the request can never be // intercepted by a SW inside this if-block. It's because: // - |GetSkipServiceWorker()| needs to be false, and // - we're controlled by a SW at this point // to allow a SW to intercept the request. Even when the request gets issued // asynchronously after performing the CORS preflight, it doesn't get // intercepted since LoadPreflightRequest() sets the flag to kNone in advance. const bool is_controlled_by_service_worker = resource_fetcher_->IsControlledByServiceWorker() == blink::mojom::ControllerServiceWorkerMode::kControlled; if (!async_ || new_request.GetSkipServiceWorker() || !SchemeRegistry::ShouldTreatURLSchemeAsAllowingServiceWorkers( new_request.Url().Protocol()) || !is_controlled_by_service_worker) { DispatchInitialRequest(new_request); return; } if (cors::IsCorsEnabledRequestMode(request.GetMode())) { // Save the request to fallback_request_for_service_worker to use when the // service worker doesn't handle (call respondWith()) a CORS enabled // request. fallback_request_for_service_worker_ = ResourceRequest(request); // Skip the service worker for the fallback request. fallback_request_for_service_worker_.SetSkipServiceWorker(true); } LoadRequest(new_request, resource_loader_options_); } void ThreadableLoader::DispatchInitialRequest(ResourceRequest& request) { if (out_of_blink_cors_ || (!request.IsExternalRequest() && !cors_flag_)) { LoadRequest(request, resource_loader_options_); return; } DCHECK(cors::IsCorsEnabledRequestMode(request.GetMode()) || request.IsExternalRequest()); MakeCrossOriginAccessRequest(request); } void ThreadableLoader::PrepareCrossOriginRequest( ResourceRequest& request) const { if (GetSecurityOrigin()) request.SetHTTPOrigin(GetSecurityOrigin()); if (override_referrer_) { request.SetReferrerString(referrer_after_redirect_.referrer); request.SetReferrerPolicy(referrer_after_redirect_.referrer_policy); } } void ThreadableLoader::LoadPreflightRequest( const ResourceRequest& actual_request, const ResourceLoaderOptions& actual_options) { std::unique_ptr<ResourceRequest> preflight_request = CreateAccessControlPreflightRequest(actual_request, GetSecurityOrigin()); actual_request_ = actual_request; actual_options_ = actual_options; // Explicitly set |skip_service_worker| to true here. Although the page is // not controlled by a SW at this point, a new SW may be controlling the // page when this actual request gets sent later. We should not send the // actual request to the SW. See https://crbug.com/604583. actual_request_.SetSkipServiceWorker(true); // Create a ResourceLoaderOptions for preflight. ResourceLoaderOptions preflight_options = actual_options; LoadRequest(*preflight_request, preflight_options); } void ThreadableLoader::MakeCrossOriginAccessRequest( const ResourceRequest& request) { DCHECK(cors::IsCorsEnabledRequestMode(request.GetMode()) || request.IsExternalRequest()); DCHECK(client_); DCHECK(!GetResource()); // Cross-origin requests are only allowed certain registered schemes. We would // catch this when checking response headers later, but there is no reason to // send a request, preflighted or not, that's guaranteed to be denied. if (!SchemeRegistry::ShouldTreatURLSchemeAsCorsEnabled( request.Url().Protocol())) { DispatchDidFail(ResourceError( request.Url(), network::CorsErrorStatus( network::mojom::CorsError::kCorsDisabledScheme))); return; } // Non-secure origins may not make "external requests": // https://wicg.github.io/cors-rfc1918/#integration-fetch String error_message; // TODO(yhirano): Consider moving this branch elsewhere. if (!execution_context_->IsSecureContext(error_message) && request.IsExternalRequest()) { // TODO(yhirano): Fix the link. DispatchDidFail(ResourceError::CancelledDueToAccessCheckError( request.Url(), ResourceRequestBlockedReason::kOrigin, "Requests to internal network resources are not allowed " "from non-secure contexts (see https://goo.gl/Y0ZkNV). " "This is an experimental restriction which is part of " "'https://mikewest.github.io/cors-rfc1918/'.")); return; } ResourceRequest cross_origin_request(request); ResourceLoaderOptions cross_origin_options(resource_loader_options_); cross_origin_request.RemoveUserAndPassFromURL(); // Enforce the CORS preflight for checking the Access-Control-Allow-External // header. The CORS preflight cache doesn't help for this purpose. if (request.IsExternalRequest()) { LoadPreflightRequest(cross_origin_request, cross_origin_options); return; } if (request.GetMode() != network::mojom::RequestMode::kCorsWithForcedPreflight) { if (request.CorsPreflightPolicy() == network::mojom::CorsPreflightPolicy::kPreventPreflight) { PrepareCrossOriginRequest(cross_origin_request); LoadRequest(cross_origin_request, cross_origin_options); return; } DCHECK_EQ(request.CorsPreflightPolicy(), network::mojom::CorsPreflightPolicy::kConsiderPreflight); // We use ContainsOnlyCorsSafelistedOrForbiddenHeaders() here since // |request| may have been modified in the process of loading (not from // the user's input). For example, referrer. We need to accept them. For // security, we must reject forbidden headers/methods at the point we // accept user's input. Not here. if (cors::IsCorsSafelistedMethod(request.HttpMethod()) && cors::ContainsOnlyCorsSafelistedOrForbiddenHeaders( request.HttpHeaderFields())) { PrepareCrossOriginRequest(cross_origin_request); LoadRequest(cross_origin_request, cross_origin_options); return; } } // Now, we need to check that the request passes the CORS preflight either by // issuing a CORS preflight or based on an entry in the CORS preflight cache. bool should_ignore_preflight_cache = false; // Prevent use of the CORS preflight cache when instructed by the DevTools // not to use caches. probe::ShouldForceCorsPreflight(execution_context_, &should_ignore_preflight_cache); if (should_ignore_preflight_cache || !cors::CheckIfRequestCanSkipPreflight( GetSecurityOrigin()->ToString(), cross_origin_request.Url(), cross_origin_request.GetCredentialsMode(), cross_origin_request.HttpMethod(), cross_origin_request.HttpHeaderFields())) { LoadPreflightRequest(cross_origin_request, cross_origin_options); return; } // We don't want any requests that could involve a CORS preflight to get // intercepted by a foreign SW, even if we have the result of the preflight // cached already. See https://crbug.com/674370. cross_origin_request.SetSkipServiceWorker(true); PrepareCrossOriginRequest(cross_origin_request); LoadRequest(cross_origin_request, cross_origin_options); } ThreadableLoader::~ThreadableLoader() {} void ThreadableLoader::SetTimeout(const base::TimeDelta& timeout) { timeout_ = timeout; // |request_started_| <= base::TimeTicks() indicates loading is either not yet // started or is already finished, and thus we don't need to do anything with // timeout_timer_. if (request_started_ <= base::TimeTicks()) { DCHECK(!timeout_timer_.IsActive()); return; } DCHECK(async_); timeout_timer_.Stop(); // At the time of this method's implementation, it is only ever called for an // inflight request by XMLHttpRequest. // // The XHR request says to resolve the time relative to when the request // was initially sent, however other uses of this method may need to // behave differently, in which case this should be re-arranged somehow. if (!timeout_.is_zero()) { base::TimeDelta elapsed_time = base::TimeTicks::Now() - request_started_; base::TimeDelta resolved_time = std::max(timeout_ - elapsed_time, base::TimeDelta()); timeout_timer_.StartOneShot(resolved_time, FROM_HERE); } } void ThreadableLoader::Cancel() { // Cancel can re-enter, and therefore |resource()| might be null here as a // result. if (!client_ || !GetResource()) { Clear(); return; } DispatchDidFail(ResourceError::CancelledError(GetResource()->Url())); } void ThreadableLoader::Detach() { Resource* resource = GetResource(); if (!resource) return; detached_ = true; client_ = MakeGarbageCollected<DetachedClient>(this); } void ThreadableLoader::SetDefersLoading(bool value) { if (GetResource() && GetResource()->Loader()) GetResource()->Loader()->SetDefersLoading(value); } void ThreadableLoader::Clear() { client_ = nullptr; timeout_timer_.Stop(); request_started_ = base::TimeTicks(); if (GetResource()) checker_.WillRemoveClient(); ClearResource(); } // In this method, we can clear |request| to tell content::WebURLLoaderImpl of // Chromium not to follow the redirect. This works only when this method is // called by RawResource::willSendRequest(). If called by // RawResource::didAddClient(), clearing |request| won't be propagated to // content::WebURLLoaderImpl. So, this loader must also get detached from the // resource by calling clearResource(). // TODO(toyoshim): Implement OOR-CORS mode specific redirect code. bool ThreadableLoader::RedirectReceived( Resource* resource, const ResourceRequest& new_request, const ResourceResponse& redirect_response) { DCHECK(client_); DCHECK_EQ(resource, GetResource()); { AssignOnScopeExit assign_on_scope_exit(new_request.Url(), &last_request_url_); checker_.RedirectReceived(); const KURL& new_url = new_request.Url(); const KURL& original_url = redirect_response.CurrentRequestUrl(); if (out_of_blink_cors_) return client_->WillFollowRedirect(new_url, redirect_response); if (!actual_request_.IsNull()) { ReportResponseReceived(resource->InspectorId(), redirect_response); HandlePreflightFailure( original_url, network::CorsErrorStatus( network::mojom::CorsError::kPreflightDisallowedRedirect)); return false; } if (cors_flag_) { if (const auto error_status = cors::CheckAccess( original_url, redirect_response.HttpStatusCode(), redirect_response.HttpHeaderFields(), new_request.GetCredentialsMode(), *GetSecurityOrigin())) { DispatchDidFail(ResourceError(original_url, *error_status)); return false; } } if (redirect_mode_ == network::mojom::RedirectMode::kError) { bool follow = client_->WillFollowRedirect(new_url, redirect_response); DCHECK(!follow); return false; } if (redirect_mode_ == network::mojom::RedirectMode::kManual) { auto redirect_response_to_pass = redirect_response; redirect_response_to_pass.SetType( network::mojom::FetchResponseType::kOpaqueRedirect); bool follow = client_->WillFollowRedirect(new_url, redirect_response_to_pass); DCHECK(!follow); return false; } DCHECK_EQ(redirect_mode_, network::mojom::RedirectMode::kFollow); if (redirect_limit_ <= 0) { ThreadableLoaderClient* client = client_; Clear(); ConsoleMessage* message = ConsoleMessage::Create( mojom::ConsoleMessageSource::kNetwork, mojom::ConsoleMessageLevel::kError, "Failed to load resource: net::ERR_TOO_MANY_REDIRECTS", SourceLocation::Capture(original_url, 0, 0)); execution_context_->AddConsoleMessage(message); client->DidFailRedirectCheck(); return false; } --redirect_limit_; auto redirect_response_to_pass = redirect_response; redirect_response_to_pass.SetType(response_tainting_); // Allow same origin requests to continue after allowing clients to audit // the redirect. if (!(cors_flag_ || cors::CalculateCorsFlag(new_url, GetSecurityOrigin(), new_request.IsolatedWorldOrigin().get(), new_request.GetMode()))) { bool follow = client_->WillFollowRedirect(new_url, redirect_response_to_pass); response_tainting_ = cors::CalculateResponseTainting( new_url, new_request.GetMode(), GetSecurityOrigin(), new_request.IsolatedWorldOrigin().get(), CorsFlag::Unset); return follow; } probe::DidReceiveCorsRedirectResponse( execution_context_, resource->InspectorId(), GetDocument() && GetDocument()->GetFrame() ? GetDocument()->GetFrame()->Loader().GetDocumentLoader() : nullptr, redirect_response_to_pass, resource); if (auto error_status = cors::CheckRedirectLocation( new_url, request_mode_, GetSecurityOrigin(), cors_flag_ ? CorsFlag::Set : CorsFlag::Unset)) { DispatchDidFail(ResourceError(original_url, *error_status)); return false; } if (!client_->WillFollowRedirect(new_url, redirect_response_to_pass)) return false; // FIXME: consider combining this with CORS redirect handling performed by // CrossOriginAccessControl::handleRedirect(). if (GetResource()) checker_.WillRemoveClient(); ClearResource(); // If // - CORS flag is set, and // - the origin of the redirect target URL is not same origin with the // origin of the current request's URL // set the source origin to a unique opaque origin. // // See https://fetch.spec.whatwg.org/#http-redirect-fetch. if (cors_flag_) { scoped_refptr<const SecurityOrigin> original_origin = SecurityOrigin::Create(original_url); scoped_refptr<const SecurityOrigin> new_origin = SecurityOrigin::Create(new_url); if (!original_origin->IsSameSchemeHostPort(new_origin.get())) security_origin_ = SecurityOrigin::CreateUniqueOpaque(); } // Set |cors_flag_| so that further logic (corresponds to the main fetch in // the spec) will be performed with CORS flag set. // See https://fetch.spec.whatwg.org/#http-redirect-fetch. cors_flag_ = true; // Save the referrer to use when following the redirect. override_referrer_ = true; // TODO(domfarolino): Use ReferrerString() once https://crbug.com/850813 is // closed and we stop storing the referrer string as a `Referer` header. referrer_after_redirect_ = Referrer(new_request.HttpReferrer(), new_request.GetReferrerPolicy()); } // We're initiating a new request (for redirect), so update // |last_request_url_| by destroying |assign_on_scope_exit|. ResourceRequest cross_origin_request(new_request); cross_origin_request.SetInitialUrlForResourceTiming(initial_request_url_); // Remove any headers that may have been added by the network layer that cause // access control to fail. cross_origin_request.ClearHTTPReferrer(); cross_origin_request.ClearHTTPOrigin(); cross_origin_request.ClearHTTPUserAgent(); // Add any request headers which we previously saved from the // original request. for (const auto& header : request_headers_) cross_origin_request.SetHttpHeaderField(header.key, header.value); cross_origin_request.SetReportUploadProgress(report_upload_progress_); MakeCrossOriginAccessRequest(cross_origin_request); return false; } void ThreadableLoader::RedirectBlocked() { checker_.RedirectBlocked(); // Tells the client that a redirect was received but not followed (for an // unknown reason). ThreadableLoaderClient* client = client_; Clear(); client->DidFailRedirectCheck(); } void ThreadableLoader::DataSent(Resource* resource, uint64_t bytes_sent, uint64_t total_bytes_to_be_sent) { DCHECK(client_); DCHECK_EQ(resource, GetResource()); DCHECK(async_); checker_.DataSent(); client_->DidSendData(bytes_sent, total_bytes_to_be_sent); } void ThreadableLoader::DataDownloaded(Resource* resource, uint64_t data_length) { DCHECK(client_); DCHECK_EQ(resource, GetResource()); DCHECK(actual_request_.IsNull()); checker_.DataDownloaded(); client_->DidDownloadData(data_length); } void ThreadableLoader::DidDownloadToBlob(Resource* resource, scoped_refptr<BlobDataHandle> blob) { DCHECK(client_); DCHECK_EQ(resource, GetResource()); checker_.DidDownloadToBlob(); client_->DidDownloadToBlob(std::move(blob)); } void ThreadableLoader::HandlePreflightResponse( const ResourceResponse& response) { base::Optional<network::CorsErrorStatus> cors_error_status = cors::CheckPreflightAccess( response.CurrentRequestUrl(), response.HttpStatusCode(), response.HttpHeaderFields(), actual_request_.GetCredentialsMode(), *GetSecurityOrigin()); if (cors_error_status) { HandlePreflightFailure(response.CurrentRequestUrl(), *cors_error_status); return; } base::Optional<network::mojom::CorsError> preflight_error = cors::CheckPreflight(response.HttpStatusCode()); if (preflight_error) { HandlePreflightFailure(response.CurrentRequestUrl(), network::CorsErrorStatus(*preflight_error)); return; } base::Optional<network::CorsErrorStatus> error_status; if (actual_request_.IsExternalRequest()) { error_status = cors::CheckExternalPreflight(response.HttpHeaderFields()); if (error_status) { HandlePreflightFailure(response.CurrentRequestUrl(), *error_status); return; } } String access_control_error_description; error_status = cors::EnsurePreflightResultAndCacheOnSuccess( response.HttpHeaderFields(), GetSecurityOrigin()->ToString(), actual_request_.Url(), actual_request_.HttpMethod(), actual_request_.HttpHeaderFields(), actual_request_.GetCredentialsMode()); if (error_status) HandlePreflightFailure(response.CurrentRequestUrl(), *error_status); } void ThreadableLoader::ReportResponseReceived( uint64_t identifier, const ResourceResponse& response) { LocalFrame* frame = GetDocument() ? GetDocument()->GetFrame() : nullptr; if (!frame) return; DocumentLoader* loader = frame->Loader().GetDocumentLoader(); probe::DidReceiveResourceResponse(probe::ToCoreProbeSink(execution_context_), identifier, loader, response, GetResource()); frame->Console().ReportResourceResponseReceived(loader, identifier, response); } void ThreadableLoader::ResponseReceived(Resource* resource, const ResourceResponse& response) { DCHECK_EQ(resource, GetResource()); DCHECK(client_); checker_.ResponseReceived(); // TODO(toyoshim): Support OOR-CORS preflight and Service Worker case. // Note that CORS-preflight is usually handled in the Network Service side, // but still done in Blink side when it is needed on redirects. // https://crbug.com/736308. if (out_of_blink_cors_ && !response.WasFetchedViaServiceWorker()) { DCHECK(actual_request_.IsNull()); fallback_request_for_service_worker_ = ResourceRequest(); client_->DidReceiveResponse(resource->InspectorId(), response); return; } // Code path for legacy Blink CORS. if (!actual_request_.IsNull()) { ReportResponseReceived(resource->InspectorId(), response); HandlePreflightResponse(response); return; } if (response.WasFetchedViaServiceWorker()) { if (response.WasFallbackRequiredByServiceWorker()) { // At this point we must have m_fallbackRequestForServiceWorker. (For // SharedWorker the request won't be CORS or CORS-with-preflight, // therefore fallback-to-network is handled in the browser process when // the ServiceWorker does not call respondWith().) DCHECK(!fallback_request_for_service_worker_.IsNull()); ReportResponseReceived(resource->InspectorId(), response); LoadFallbackRequestForServiceWorker(); return; } // It's possible that we issue a fetch with request with non "no-cors" // mode but get an opaque filtered response if a service worker is involved. // We dispatch a CORS failure for the case. // TODO(yhirano): This is probably not spec conformant. Fix it after // https://github.com/w3c/preload/issues/100 is addressed. if (request_mode_ != network::mojom::RequestMode::kNoCors && response.GetType() == network::mojom::FetchResponseType::kOpaque) { DispatchDidFail( ResourceError(response.CurrentRequestUrl(), network::CorsErrorStatus( network::mojom::CorsError::kInvalidResponse))); return; } fallback_request_for_service_worker_ = ResourceRequest(); client_->DidReceiveResponse(resource->InspectorId(), response); return; } // Even if the request met the conditions to get handled by a Service Worker // in the constructor of this class (and therefore // |m_fallbackRequestForServiceWorker| is set), the Service Worker may skip // processing the request. Only if the request is same origin, the skipped // response may come here (wasFetchedViaServiceWorker() returns false) since // such a request doesn't have to go through the CORS algorithm by calling // loadFallbackRequestForServiceWorker(). DCHECK(fallback_request_for_service_worker_.IsNull() || GetSecurityOrigin()->CanRequest( fallback_request_for_service_worker_.Url())); fallback_request_for_service_worker_ = ResourceRequest(); if (cors_flag_) { base::Optional<network::CorsErrorStatus> access_error = cors::CheckAccess( response.CurrentRequestUrl(), response.HttpStatusCode(), response.HttpHeaderFields(), credentials_mode_, *GetSecurityOrigin()); if (access_error) { ReportResponseReceived(resource->InspectorId(), response); DispatchDidFail( ResourceError(response.CurrentRequestUrl(), *access_error)); return; } } DCHECK_EQ(&response, &resource->GetResponse()); resource->SetResponseType(response_tainting_); DCHECK_EQ(response.GetType(), response_tainting_); client_->DidReceiveResponse(resource->InspectorId(), response); } void ThreadableLoader::ResponseBodyReceived(Resource*, BytesConsumer& body) { checker_.ResponseBodyReceived(); client_->DidStartLoadingResponseBody(body); } void ThreadableLoader::SetSerializedCachedMetadata(Resource*, const uint8_t* data, size_t size) { checker_.SetSerializedCachedMetadata(); if (!actual_request_.IsNull()) return; client_->DidReceiveCachedMetadata(reinterpret_cast<const char*>(data), SafeCast<int>(size)); } void ThreadableLoader::DataReceived(Resource* resource, const char* data, size_t data_length) { DCHECK_EQ(resource, GetResource()); DCHECK(client_); checker_.DataReceived(); // Preflight data should be invisible to clients. if (!actual_request_.IsNull()) return; DCHECK(fallback_request_for_service_worker_.IsNull()); // TODO(junov): Fix the ThreadableLoader ecosystem to use size_t. Until then, // we use safeCast to trap potential overflows. client_->DidReceiveData(data, SafeCast<unsigned>(data_length)); } void ThreadableLoader::NotifyFinished(Resource* resource) { DCHECK(client_); DCHECK_EQ(resource, GetResource()); checker_.NotifyFinished(resource); if (resource->ErrorOccurred()) { DispatchDidFail(resource->GetResourceError()); return; } DCHECK(fallback_request_for_service_worker_.IsNull()); if (!actual_request_.IsNull()) { DCHECK(actual_request_.IsExternalRequest() || cors_flag_); LoadActualRequest(); return; } ThreadableLoaderClient* client = client_; // Protect the resource in |didFinishLoading| in order not to release the // downloaded file. Persistent<Resource> protect = GetResource(); Clear(); client->DidFinishLoading(resource->InspectorId()); } void ThreadableLoader::DidTimeout(TimerBase* timer) { DCHECK(async_); DCHECK_EQ(timer, &timeout_timer_); // clearResource() may be called in clear() and some other places. clear() // calls stop() on |m_timeoutTimer|. In the other places, the resource is set // again. If the creation fails, clear() is called. So, here, resource() is // always non-nullptr. DCHECK(GetResource()); // When |m_client| is set to nullptr only in clear() where |m_timeoutTimer| // is stopped. So, |m_client| is always non-nullptr here. DCHECK(client_); DispatchDidFail(ResourceError::TimeoutError(GetResource()->Url())); } void ThreadableLoader::LoadFallbackRequestForServiceWorker() { if (GetResource()) checker_.WillRemoveClient(); ClearResource(); ResourceRequest fallback_request(fallback_request_for_service_worker_); fallback_request_for_service_worker_ = ResourceRequest(); DispatchInitialRequest(fallback_request); } void ThreadableLoader::LoadActualRequest() { ResourceRequest actual_request = actual_request_; ResourceLoaderOptions actual_options = actual_options_; actual_request_ = ResourceRequest(); actual_options_ = ResourceLoaderOptions(); if (GetResource()) checker_.WillRemoveClient(); ClearResource(); PrepareCrossOriginRequest(actual_request); LoadRequest(actual_request, actual_options); } void ThreadableLoader::HandlePreflightFailure( const KURL& url, const network::CorsErrorStatus& error_status) { // Prevent NotifyFinished() from bypassing access check. actual_request_ = ResourceRequest(); DispatchDidFail(ResourceError(url, error_status)); } void ThreadableLoader::DispatchDidFail(const ResourceError& error) { if (!out_of_blink_cors_ && error.CorsErrorStatus()) { String message = cors::GetErrorString( *error.CorsErrorStatus(), initial_request_url_, last_request_url_, *GetSecurityOrigin(), ResourceType::kRaw, resource_loader_options_.initiator_info.name); execution_context_->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kError, std::move(message))); } Resource* resource = GetResource(); if (resource) resource->SetResponseType(network::mojom::FetchResponseType::kError); ThreadableLoaderClient* client = client_; Clear(); client->DidFail(error); } void ThreadableLoader::LoadRequest( ResourceRequest& request, ResourceLoaderOptions resource_loader_options) { resource_loader_options.cors_handling_by_resource_fetcher = kDisableCorsHandlingByResourceFetcher; if (out_of_blink_cors_) { if (request.GetCredentialsMode() == network::mojom::CredentialsMode::kOmit) { // See comments at network::ResourceRequest::credentials_mode. request.SetAllowStoredCredentials(false); } } else { if (actual_request_.IsNull()) { response_tainting_ = cors::CalculateResponseTainting( request.Url(), request.GetMode(), GetSecurityOrigin(), request.IsolatedWorldOrigin().get(), cors_flag_ ? CorsFlag::Set : CorsFlag::Unset); request.SetAllowStoredCredentials(cors::CalculateCredentialsFlag( request.GetCredentialsMode(), response_tainting_)); } else { request.SetAllowStoredCredentials(false); } } request.SetRequestorOrigin(original_security_origin_); if (!actual_request_.IsNull()) resource_loader_options.data_buffering_policy = kBufferData; if (!timeout_.is_zero()) { if (!async_) { request.SetTimeoutInterval(timeout_); } else if (!timeout_timer_.IsActive()) { // The timer can be active if this is the actual request of a // CORS-with-preflight request. timeout_timer_.StartOneShot(timeout_, FROM_HERE); } } FetchParameters new_params(request, resource_loader_options); DCHECK(!GetResource()); checker_.WillAddClient(); if (request.GetRequestContext() == mojom::RequestContextType::VIDEO || request.GetRequestContext() == mojom::RequestContextType::AUDIO) { DCHECK(async_); RawResource::FetchMedia(new_params, resource_fetcher_, this); } else if (request.GetRequestContext() == mojom::RequestContextType::MANIFEST) { DCHECK(async_); RawResource::FetchManifest(new_params, resource_fetcher_, this); } else if (async_) { RawResource::Fetch(new_params, resource_fetcher_, this); } else { RawResource::FetchSynchronously(new_params, resource_fetcher_, this); } } const SecurityOrigin* ThreadableLoader::GetSecurityOrigin() const { return security_origin_ ? security_origin_.get() : resource_fetcher_->GetProperties() .GetFetchClientSettingsObject() .GetSecurityOrigin(); } Document* ThreadableLoader::GetDocument() const { return DynamicTo<Document>(execution_context_.Get()); } void ThreadableLoader::Trace(blink::Visitor* visitor) { visitor->Trace(execution_context_); visitor->Trace(client_); visitor->Trace(resource_fetcher_); RawResourceClient::Trace(visitor); } } // namespace blink
bd3c9245fa994d01505c242466d4dac6b3da8ffa
462fd31fcdbc4b25b20cfe35ec119ac1db60fe00
/chrome/browser/sync/chrome_sync_client.cc
c34582637e4467e274aad8706b1c5aff019fa41d
[ "BSD-3-Clause" ]
permissive
sandwichandtoast/chromium
6f65efa55a1c02cface02e5b641c751a57eaae94
8477524140c1fbe839eefe6f79ef71fd097da32f
refs/heads/master
2023-01-13T12:57:04.375740
2016-01-10T04:03:01
2016-01-10T04:05:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,421
cc
// Copyright 2015 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 "chrome/browser/sync/chrome_sync_client.h" #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" #include "build/build_config.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/prefs/pref_service_syncable_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/sync/glue/sync_start_util.h" #include "chrome/browser/sync/glue/theme_data_type_controller.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sessions/notification_service_sessions_router.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/themes/theme_syncable_service.h" #include "chrome/browser/ui/sync/browser_synced_window_delegates_getter.h" #include "chrome/browser/undo/bookmark_undo_service_factory.h" #include "chrome/browser/web_data_service_factory.h" #include "chrome/common/channel_info.h" #include "chrome/common/features.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/autofill/core/browser/webdata/autocomplete_syncable_service.h" #include "components/autofill/core/browser/webdata/autofill_profile_syncable_service.h" #include "components/autofill/core/browser/webdata/autofill_wallet_metadata_syncable_service.h" #include "components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/browser_sync/browser/profile_sync_components_factory_impl.h" #include "components/browser_sync/browser/profile_sync_service.h" #include "components/browser_sync/common/browser_sync_switches.h" #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/history/core/browser/history_model_worker.h" #include "components/history/core/browser/history_service.h" #include "components/invalidation/impl/profile_invalidation_provider.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/sync/browser/password_model_worker.h" #include "components/search_engines/search_engine_data_type_controller.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/sync_driver/glue/browser_thread_model_worker.h" #include "components/sync_driver/glue/chrome_report_unrecoverable_error.h" #include "components/sync_driver/glue/ui_model_worker.h" #include "components/sync_driver/sync_api_component_factory.h" #include "components/sync_driver/sync_util.h" #include "components/sync_driver/ui_data_type_controller.h" #include "components/sync_sessions/sync_sessions_client.h" #include "components/syncable_prefs/pref_service_syncable.h" #include "content/public/browser/browser_thread.h" #include "sync/internal_api/public/engine/passive_model_worker.h" #include "ui/base/device_form_factor.h" #if defined(ENABLE_APP_LIST) #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #include "ui/app_list/app_list_switches.h" #endif #if defined(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/api/storage/settings_sync_util.h" #include "chrome/browser/extensions/extension_sync_service.h" #include "chrome/browser/sync/glue/extension_data_type_controller.h" #include "chrome/browser/sync/glue/extension_setting_data_type_controller.h" #endif #if defined(ENABLE_SUPERVISED_USERS) #include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h" #include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service_factory.h" #include "chrome/browser/supervised_user/legacy/supervised_user_sync_service.h" #include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_sync_data_type_controller.h" #include "chrome/browser/supervised_user/supervised_user_whitelist_service.h" #endif #if defined(ENABLE_SPELLCHECK) #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/spellchecker/spellcheck_service.h" #endif #if BUILDFLAG(ANDROID_JAVA_UI) #include "chrome/browser/sync/glue/synced_window_delegates_getter_android.h" #endif #if defined(OS_CHROMEOS) #include "components/wifi_sync/wifi_credential_syncable_service.h" #include "components/wifi_sync/wifi_credential_syncable_service_factory.h" #endif using content::BrowserThread; #if defined(ENABLE_EXTENSIONS) using browser_sync::ExtensionDataTypeController; using browser_sync::ExtensionSettingDataTypeController; #endif using browser_sync::SearchEngineDataTypeController; using sync_driver::UIDataTypeController; namespace browser_sync { // Chrome implementation of SyncSessionsClient. Needs to be in a separate class // due to possible multiple inheritance issues, wherein ChromeSyncClient might // inherit from other interfaces with same methods. class SyncSessionsClientImpl : public sync_sessions::SyncSessionsClient { public: explicit SyncSessionsClientImpl(Profile* profile) : profile_(profile) { window_delegates_getter_.reset( #if BUILDFLAG(ANDROID_JAVA_UI) // Android doesn't have multi-profile support, so no need to pass the // profile in. new browser_sync::SyncedWindowDelegatesGetterAndroid()); #else new browser_sync::BrowserSyncedWindowDelegatesGetter(profile)); #endif } ~SyncSessionsClientImpl() override {} // SyncSessionsClient implementation. bookmarks::BookmarkModel* GetBookmarkModel() override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return BookmarkModelFactory::GetForProfile(profile_); } favicon::FaviconService* GetFaviconService() override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return FaviconServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); } history::HistoryService* GetHistoryService() override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); return HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); } bool ShouldSyncURL(const GURL& url) const override { if (url == GURL(chrome::kChromeUIHistoryURL)) { // The history page is treated specially as we want it to trigger syncable // events for UI purposes. return true; } return url.is_valid() && !url.SchemeIs(content::kChromeUIScheme) && !url.SchemeIs(chrome::kChromeNativeScheme) && !url.SchemeIsFile(); } SyncedWindowDelegatesGetter* GetSyncedWindowDelegatesGetter() override { return window_delegates_getter_.get(); } scoped_ptr<browser_sync::LocalSessionEventRouter> GetLocalSessionEventRouter() override { syncer::SyncableService::StartSyncFlare flare( sync_start_util::GetFlareForSyncableService(profile_->GetPath())); return make_scoped_ptr( new NotificationServiceSessionsRouter(profile_, this, flare)); } private: Profile* profile_; scoped_ptr<SyncedWindowDelegatesGetter> window_delegates_getter_; DISALLOW_COPY_AND_ASSIGN(SyncSessionsClientImpl); }; ChromeSyncClient::ChromeSyncClient(Profile* profile) : profile_(profile), sync_sessions_client_(new SyncSessionsClientImpl(profile)), browsing_data_remover_observer_(NULL), weak_ptr_factory_(this) {} ChromeSyncClient::~ChromeSyncClient() { } void ChromeSyncClient::Initialize(sync_driver::SyncService* sync_service) { DCHECK_CURRENTLY_ON(BrowserThread::UI); web_data_service_ = WebDataServiceFactory::GetAutofillWebDataForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); // TODO(crbug.com/558320) Is EXPLICIT_ACCESS appropriate here? password_store_ = PasswordStoreFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); // Component factory may already be set in tests. if (!GetSyncApiComponentFactory()) { const GURL sync_service_url = GetSyncServiceURL( *base::CommandLine::ForCurrentProcess(), chrome::GetChannel()); ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); net::URLRequestContextGetter* url_request_context_getter = profile_->GetRequestContext(); component_factory_.reset(new ProfileSyncComponentsFactoryImpl( this, chrome::GetChannel(), chrome::GetVersionString(), ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_TABLET, *base::CommandLine::ForCurrentProcess(), prefs::kSavingBrowserHistoryDisabled, sync_service_url, content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI), content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::DB), token_service, url_request_context_getter, web_data_service_, password_store_)); } sync_service_ = sync_service; } sync_driver::SyncService* ChromeSyncClient::GetSyncService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return sync_service_; } PrefService* ChromeSyncClient::GetPrefService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return profile_->GetPrefs(); } bookmarks::BookmarkModel* ChromeSyncClient::GetBookmarkModel() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return BookmarkModelFactory::GetForProfile(profile_); } favicon::FaviconService* ChromeSyncClient::GetFaviconService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return FaviconServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); } history::HistoryService* ChromeSyncClient::GetHistoryService() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); } autofill::PersonalDataManager* ChromeSyncClient::GetPersonalDataManager() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return autofill::PersonalDataManagerFactory::GetForProfile(profile_); } sync_driver::ClearBrowsingDataCallback ChromeSyncClient::GetClearBrowsingDataCallback() { return base::Bind(&ChromeSyncClient::ClearBrowsingData, base::Unretained(this)); } base::Closure ChromeSyncClient::GetPasswordStateChangedCallback() { return base::Bind( &PasswordStoreFactory::OnPasswordsSyncedStatePotentiallyChanged, base::Unretained(profile_)); } sync_driver::SyncApiComponentFactory::RegisterDataTypesMethod ChromeSyncClient::GetRegisterPlatformTypesCallback() { return base::Bind( #if BUILDFLAG(ANDROID_JAVA_UI) &ChromeSyncClient::RegisterAndroidDataTypes, #else &ChromeSyncClient::RegisterDesktopDataTypes, #endif // BUILDFLAG(ANDROID_JAVA_UI) weak_ptr_factory_.GetWeakPtr()); } BookmarkUndoService* ChromeSyncClient::GetBookmarkUndoServiceIfExists() { return BookmarkUndoServiceFactory::GetForProfileIfExists(profile_); } invalidation::InvalidationService* ChromeSyncClient::GetInvalidationService() { invalidation::ProfileInvalidationProvider* provider = invalidation::ProfileInvalidationProviderFactory::GetForProfile(profile_); if (provider) return provider->GetInvalidationService(); return nullptr; } scoped_refptr<syncer::ExtensionsActivity> ChromeSyncClient::GetExtensionsActivity() { return extensions_activity_monitor_.GetExtensionsActivity(); } sync_sessions::SyncSessionsClient* ChromeSyncClient::GetSyncSessionsClient() { return sync_sessions_client_.get(); } base::WeakPtr<syncer::SyncableService> ChromeSyncClient::GetSyncableServiceForType(syncer::ModelType type) { if (!profile_) { // For tests. return base::WeakPtr<syncer::SyncableService>(); } switch (type) { case syncer::DEVICE_INFO: return ProfileSyncServiceFactory::GetForProfile(profile_) ->GetDeviceInfoSyncableService() ->AsWeakPtr(); case syncer::PREFERENCES: return PrefServiceSyncableFromProfile(profile_) ->GetSyncableService(syncer::PREFERENCES) ->AsWeakPtr(); case syncer::PRIORITY_PREFERENCES: return PrefServiceSyncableFromProfile(profile_) ->GetSyncableService(syncer::PRIORITY_PREFERENCES) ->AsWeakPtr(); case syncer::AUTOFILL: case syncer::AUTOFILL_PROFILE: case syncer::AUTOFILL_WALLET_DATA: case syncer::AUTOFILL_WALLET_METADATA: { if (!web_data_service_) return base::WeakPtr<syncer::SyncableService>(); if (type == syncer::AUTOFILL) { return autofill::AutocompleteSyncableService::FromWebDataService( web_data_service_.get())->AsWeakPtr(); } else if (type == syncer::AUTOFILL_PROFILE) { return autofill::AutofillProfileSyncableService::FromWebDataService( web_data_service_.get())->AsWeakPtr(); } else if (type == syncer::AUTOFILL_WALLET_METADATA) { return autofill::AutofillWalletMetadataSyncableService:: FromWebDataService(web_data_service_.get())->AsWeakPtr(); } return autofill::AutofillWalletSyncableService::FromWebDataService( web_data_service_.get())->AsWeakPtr(); } case syncer::SEARCH_ENGINES: return TemplateURLServiceFactory::GetForProfile(profile_)->AsWeakPtr(); #if defined(ENABLE_EXTENSIONS) case syncer::APPS: case syncer::EXTENSIONS: return ExtensionSyncService::Get(profile_)->AsWeakPtr(); case syncer::APP_SETTINGS: case syncer::EXTENSION_SETTINGS: return extensions::settings_sync_util::GetSyncableService(profile_, type) ->AsWeakPtr(); #endif #if defined(ENABLE_APP_LIST) case syncer::APP_LIST: return app_list::AppListSyncableServiceFactory::GetForProfile(profile_)-> AsWeakPtr(); #endif #if defined(ENABLE_THEMES) case syncer::THEMES: return ThemeServiceFactory::GetForProfile(profile_)-> GetThemeSyncableService()->AsWeakPtr(); #endif case syncer::HISTORY_DELETE_DIRECTIVES: { history::HistoryService* history = GetHistoryService(); return history ? history->AsWeakPtr() : base::WeakPtr<history::HistoryService>(); } case syncer::TYPED_URLS: { history::HistoryService* history = HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (!history) return base::WeakPtr<history::TypedUrlSyncableService>(); return history->GetTypedUrlSyncableService()->AsWeakPtr(); } #if defined(ENABLE_SPELLCHECK) case syncer::DICTIONARY: return SpellcheckServiceFactory::GetForContext(profile_)-> GetCustomDictionary()->AsWeakPtr(); #endif case syncer::FAVICON_IMAGES: case syncer::FAVICON_TRACKING: { browser_sync::FaviconCache* favicons = ProfileSyncServiceFactory::GetForProfile(profile_)-> GetFaviconCache(); return favicons ? favicons->AsWeakPtr() : base::WeakPtr<syncer::SyncableService>(); } #if defined(ENABLE_SUPERVISED_USERS) case syncer::SUPERVISED_USER_SETTINGS: return SupervisedUserSettingsServiceFactory::GetForProfile(profile_)-> AsWeakPtr(); #if !defined(OS_ANDROID) && !defined(OS_IOS) case syncer::SUPERVISED_USERS: return SupervisedUserSyncServiceFactory::GetForProfile(profile_)-> AsWeakPtr(); case syncer::SUPERVISED_USER_SHARED_SETTINGS: return SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext( profile_)->AsWeakPtr(); #endif case syncer::SUPERVISED_USER_WHITELISTS: return SupervisedUserServiceFactory::GetForProfile(profile_) ->GetWhitelistService() ->AsWeakPtr(); #endif case syncer::ARTICLES: { dom_distiller::DomDistillerService* service = dom_distiller::DomDistillerServiceFactory::GetForBrowserContext( profile_); if (service) return service->GetSyncableService()->AsWeakPtr(); return base::WeakPtr<syncer::SyncableService>(); } case syncer::SESSIONS: { return ProfileSyncServiceFactory::GetForProfile(profile_)-> GetSessionsSyncableService()->AsWeakPtr(); } case syncer::PASSWORDS: { return password_store_.get() ? password_store_->GetPasswordSyncableService() : base::WeakPtr<syncer::SyncableService>(); } #if defined(OS_CHROMEOS) case syncer::WIFI_CREDENTIALS: return wifi_sync::WifiCredentialSyncableServiceFactory:: GetForBrowserContext(profile_)->AsWeakPtr(); #endif default: // The following datatypes still need to be transitioned to the // syncer::SyncableService API: // Bookmarks // Typed URLs NOTREACHED(); return base::WeakPtr<syncer::SyncableService>(); } } scoped_refptr<syncer::ModelSafeWorker> ChromeSyncClient::CreateModelWorkerForGroup( syncer::ModelSafeGroup group, syncer::WorkerLoopDestructionObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); switch (group) { case syncer::GROUP_DB: return new BrowserThreadModelWorker( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB), syncer::GROUP_DB, observer); case syncer::GROUP_FILE: return new BrowserThreadModelWorker( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), syncer::GROUP_FILE, observer); case syncer::GROUP_UI: return new UIModelWorker( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI), observer); case syncer::GROUP_PASSIVE: return new syncer::PassiveModelWorker(observer); case syncer::GROUP_HISTORY: { history::HistoryService* history_service = GetHistoryService(); if (!history_service) return nullptr; return new HistoryModelWorker( history_service->AsWeakPtr(), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI), observer); } case syncer::GROUP_PASSWORD: { if (!password_store_.get()) return nullptr; return new PasswordModelWorker(password_store_, observer); } default: return nullptr; } } sync_driver::SyncApiComponentFactory* ChromeSyncClient::GetSyncApiComponentFactory() { return component_factory_.get(); } void ChromeSyncClient::ClearBrowsingData(base::Time start, base::Time end) { // BrowsingDataRemover deletes itself when it's done. BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(profile_, start, end); if (browsing_data_remover_observer_) remover->AddObserver(browsing_data_remover_observer_); remover->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL); scoped_refptr<password_manager::PasswordStore> password = PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); password->RemoveLoginsSyncedBetween(start, end); } void ChromeSyncClient::SetBrowsingDataRemoverObserverForTesting( BrowsingDataRemover::Observer* observer) { browsing_data_remover_observer_ = observer; } void ChromeSyncClient::SetSyncApiComponentFactoryForTesting( scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory) { component_factory_ = std::move(component_factory); } void ChromeSyncClient::RegisterDesktopDataTypes( syncer::ModelTypeSet disabled_types, syncer::ModelTypeSet enabled_types) { sync_driver::SyncService* sync_service = GetSyncService(); base::Closure error_callback = base::Bind(&ChromeReportUnrecoverableError, chrome::GetChannel()); const scoped_refptr<base::SingleThreadTaskRunner> ui_thread = BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI); #if defined(ENABLE_EXTENSIONS) // App sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::APPS)) { sync_service->RegisterDataTypeController(new ExtensionDataTypeController( syncer::APPS, error_callback, this, profile_)); } // Extension sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::EXTENSIONS)) { sync_service->RegisterDataTypeController(new ExtensionDataTypeController( syncer::EXTENSIONS, error_callback, this, profile_)); } #endif // Preference sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::PREFERENCES)) { sync_service->RegisterDataTypeController(new UIDataTypeController( ui_thread, error_callback, syncer::PREFERENCES, this)); } #if defined(ENABLE_THEMES) // Theme sync is enabled by default. Register unless explicitly disabled. if (!disabled_types.Has(syncer::THEMES)) { sync_service->RegisterDataTypeController( new ThemeDataTypeController(error_callback, this, profile_)); } #endif // Search Engine sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::SEARCH_ENGINES)) { sync_service->RegisterDataTypeController(new SearchEngineDataTypeController( ui_thread, error_callback, this, TemplateURLServiceFactory::GetForProfile(profile_))); } #if defined(ENABLE_EXTENSIONS) // Extension setting sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::EXTENSION_SETTINGS)) { sync_service->RegisterDataTypeController( new ExtensionSettingDataTypeController(syncer::EXTENSION_SETTINGS, error_callback, this, profile_)); } // App setting sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::APP_SETTINGS)) { sync_service->RegisterDataTypeController( new ExtensionSettingDataTypeController(syncer::APP_SETTINGS, error_callback, this, profile_)); } #endif #if defined(ENABLE_APP_LIST) if (app_list::switches::IsAppListSyncEnabled()) { sync_service->RegisterDataTypeController(new UIDataTypeController( ui_thread, error_callback, syncer::APP_LIST, this)); } #endif #if defined(OS_LINUX) || defined(OS_WIN) || defined(OS_CHROMEOS) // Dictionary sync is enabled by default. if (!disabled_types.Has(syncer::DICTIONARY)) { sync_service->RegisterDataTypeController(new UIDataTypeController( ui_thread, error_callback, syncer::DICTIONARY, this)); } #endif #if defined(ENABLE_SUPERVISED_USERS) sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController(syncer::SUPERVISED_USER_SETTINGS, error_callback, this, profile_)); sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController( syncer::SUPERVISED_USER_WHITELISTS, error_callback, this, profile_)); sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController(syncer::SUPERVISED_USERS, error_callback, this, profile_)); sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController( syncer::SUPERVISED_USER_SHARED_SETTINGS, error_callback, this, profile_)); #endif #if defined(OS_CHROMEOS) if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWifiCredentialSync) && !disabled_types.Has(syncer::WIFI_CREDENTIALS)) { sync_service->RegisterDataTypeController(new UIDataTypeController( ui_thread, error_callback, syncer::WIFI_CREDENTIALS, this)); } #endif } void ChromeSyncClient::RegisterAndroidDataTypes( syncer::ModelTypeSet disabled_types, syncer::ModelTypeSet enabled_types) { sync_driver::SyncService* sync_service = GetSyncService(); base::Closure error_callback = base::Bind(&ChromeReportUnrecoverableError, chrome::GetChannel()); #if defined(ENABLE_SUPERVISED_USERS) sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController(syncer::SUPERVISED_USER_SETTINGS, error_callback, this, profile_)); sync_service->RegisterDataTypeController( new SupervisedUserSyncDataTypeController( syncer::SUPERVISED_USER_WHITELISTS, error_callback, this, profile_)); #endif } } // namespace browser_sync
a0e2d4ef2737ebc4215d6747748093879edfcd3b
1e3c90c358c57c2a69c727ab1113ae421ed37d1b
/google/cloud/pubsub/topic_admin_connection.cc
05077b0d84c6f4b00f4fa66e06bee0d0a8eb880c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AditiThirdEye/google-cloud-cpp
14d9f62f23fa12f634469d6f27c93f380b351021
5c74d4f9388293b3b758e0d321d6267220a8107c
refs/heads/main
2023-09-01T22:01:08.234718
2021-10-20T23:51:47
2021-10-20T23:51:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,375
cc
// Copyright 2020 Google LLC // // 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 "google/cloud/pubsub/topic_admin_connection.h" #include "google/cloud/pubsub/internal/create_channel.h" #include "google/cloud/pubsub/internal/defaults.h" #include "google/cloud/pubsub/internal/publisher_auth.h" #include "google/cloud/pubsub/internal/publisher_logging.h" #include "google/cloud/pubsub/internal/publisher_metadata.h" #include "google/cloud/pubsub/internal/publisher_stub.h" #include "google/cloud/pubsub/options.h" #include "google/cloud/internal/retry_loop.h" #include "google/cloud/log.h" #include "absl/strings/str_split.h" #include <initializer_list> #include <memory> namespace google { namespace cloud { namespace pubsub { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { using ::google::cloud::internal::Idempotency; using ::google::cloud::internal::RetryLoop; class TopicAdminConnectionImpl : public pubsub::TopicAdminConnection { public: explicit TopicAdminConnectionImpl( std::unique_ptr<google::cloud::BackgroundThreads> background, std::shared_ptr<pubsub_internal::PublisherStub> stub, std::unique_ptr<pubsub::RetryPolicy const> retry_policy, std::unique_ptr<pubsub::BackoffPolicy const> backoff_policy) : background_(std::move(background)), stub_(std::move(stub)), retry_policy_(std::move(retry_policy)), backoff_policy_(std::move(backoff_policy)) {} ~TopicAdminConnectionImpl() override = default; StatusOr<google::pubsub::v1::Topic> CreateTopic( CreateTopicParams p) override { return RetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, [this](grpc::ClientContext& context, google::pubsub::v1::Topic const& request) { return stub_->CreateTopic(context, request); }, p.topic, __func__); } StatusOr<google::pubsub::v1::Topic> GetTopic(GetTopicParams p) override { google::pubsub::v1::GetTopicRequest request; request.set_topic(p.topic.FullName()); return RetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, [this](grpc::ClientContext& context, google::pubsub::v1::GetTopicRequest const& request) { return stub_->GetTopic(context, request); }, request, __func__); } StatusOr<google::pubsub::v1::Topic> UpdateTopic( UpdateTopicParams p) override { return RetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, [this](grpc::ClientContext& context, google::pubsub::v1::UpdateTopicRequest const& request) { return stub_->UpdateTopic(context, request); }, p.request, __func__); } pubsub::ListTopicsRange ListTopics(ListTopicsParams p) override { google::pubsub::v1::ListTopicsRequest request; request.set_project(std::move(p.project_id)); auto& stub = stub_; // Because we do not have C++14 generalized lambda captures we cannot just // use the unique_ptr<> here, so convert to shared_ptr<> instead. auto retry = std::shared_ptr<pubsub::RetryPolicy const>(retry_policy_->clone()); auto backoff = std::shared_ptr<pubsub::BackoffPolicy const>(backoff_policy_->clone()); char const* function_name = __func__; auto list_functor = [stub, retry, backoff, function_name](google::pubsub::v1::ListTopicsRequest const& request) { return RetryLoop( retry->clone(), backoff->clone(), Idempotency::kIdempotent, [stub](grpc::ClientContext& c, google::pubsub::v1::ListTopicsRequest const& r) { return stub->ListTopics(c, r); }, request, function_name); }; return internal::MakePaginationRange<pubsub::ListTopicsRange>( std::move(request), list_functor, [](google::pubsub::v1::ListTopicsResponse response) { std::vector<google::pubsub::v1::Topic> items; items.reserve(response.topics_size()); for (auto& item : *response.mutable_topics()) { items.push_back(std::move(item)); } return items; }); } Status DeleteTopic(DeleteTopicParams p) override { google::pubsub::v1::DeleteTopicRequest request; request.set_topic(p.topic.FullName()); return RetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, [this](grpc::ClientContext& context, google::pubsub::v1::DeleteTopicRequest const& request) { return stub_->DeleteTopic(context, request); }, request, __func__); } StatusOr<google::pubsub::v1::DetachSubscriptionResponse> DetachSubscription( DetachSubscriptionParams p) override { google::pubsub::v1::DetachSubscriptionRequest request; request.set_subscription(p.subscription.FullName()); grpc::ClientContext context; return RetryLoop( retry_policy_->clone(), backoff_policy_->clone(), Idempotency::kIdempotent, [this](grpc::ClientContext& context, google::pubsub::v1::DetachSubscriptionRequest const& request) { return stub_->DetachSubscription(context, request); }, request, __func__); } pubsub::ListTopicSubscriptionsRange ListTopicSubscriptions( ListTopicSubscriptionsParams p) override { google::pubsub::v1::ListTopicSubscriptionsRequest request; request.set_topic(std::move(p.topic_full_name)); auto& stub = stub_; // Because we do not have C++14 generalized lambda captures we cannot just // use the unique_ptr<> here, so convert to shared_ptr<> instead. auto retry = std::shared_ptr<pubsub::RetryPolicy const>(retry_policy_->clone()); auto backoff = std::shared_ptr<pubsub::BackoffPolicy const>(backoff_policy_->clone()); char const* function_name = __func__; auto list_functor = [stub, retry, backoff, function_name]( google::pubsub::v1::ListTopicSubscriptionsRequest const& request) { return RetryLoop( retry->clone(), backoff->clone(), Idempotency::kIdempotent, [stub]( grpc::ClientContext& c, google::pubsub::v1::ListTopicSubscriptionsRequest const& r) { return stub->ListTopicSubscriptions(c, r); }, request, function_name); }; return internal::MakePaginationRange<pubsub::ListTopicSubscriptionsRange>( std::move(request), std::move(list_functor), [](google::pubsub::v1::ListTopicSubscriptionsResponse response) { std::vector<std::string> items; items.reserve(response.subscriptions_size()); for (auto& item : *response.mutable_subscriptions()) { items.push_back(std::move(item)); } return items; }); } pubsub::ListTopicSnapshotsRange ListTopicSnapshots( ListTopicSnapshotsParams p) override { google::pubsub::v1::ListTopicSnapshotsRequest request; request.set_topic(std::move(p.topic_full_name)); auto& stub = stub_; // Because we do not have C++14 generalized lambda captures we cannot just // use the unique_ptr<> here, so convert to shared_ptr<> instead. auto retry = std::shared_ptr<pubsub::RetryPolicy const>(retry_policy_->clone()); auto backoff = std::shared_ptr<pubsub::BackoffPolicy const>(backoff_policy_->clone()); char const* function_name = __func__; auto list_functor = [stub, retry, backoff, function_name]( google::pubsub::v1::ListTopicSnapshotsRequest const& request) { return RetryLoop( retry->clone(), backoff->clone(), Idempotency::kIdempotent, [stub](grpc::ClientContext& c, google::pubsub::v1::ListTopicSnapshotsRequest const& r) { return stub->ListTopicSnapshots(c, r); }, request, function_name); }; return internal::MakePaginationRange<pubsub::ListTopicSnapshotsRange>( std::move(request), list_functor, [](google::pubsub::v1::ListTopicSnapshotsResponse response) { std::vector<std::string> items; items.reserve(response.snapshots_size()); for (auto& item : *response.mutable_snapshots()) { items.push_back(std::move(item)); } return items; }); } private: std::unique_ptr<google::cloud::BackgroundThreads> background_; std::shared_ptr<pubsub_internal::PublisherStub> stub_; std::unique_ptr<pubsub::RetryPolicy const> retry_policy_; std::unique_ptr<pubsub::BackoffPolicy const> backoff_policy_; }; // Decorates a TopicAdminStub. This works for both mock and real stubs. std::shared_ptr<pubsub_internal::PublisherStub> DecorateTopicAdminStub( Options const& opts, std::shared_ptr<internal::GrpcAuthenticationStrategy> auth, std::shared_ptr<pubsub_internal::PublisherStub> stub) { if (auth->RequiresConfigureContext()) { stub = std::make_shared<pubsub_internal::PublisherAuth>(std::move(auth), std::move(stub)); } stub = std::make_shared<pubsub_internal::PublisherMetadata>(std::move(stub)); if (internal::Contains(opts.get<TracingComponentsOption>(), "rpc")) { GCP_LOG(INFO) << "Enabled logging for gRPC calls"; stub = std::make_shared<pubsub_internal::PublisherLogging>( std::move(stub), opts.get<GrpcTracingOptionsOption>()); } return stub; } } // namespace TopicAdminConnection::~TopicAdminConnection() = default; StatusOr<google::pubsub::v1::Topic> TopicAdminConnection::CreateTopic( CreateTopicParams) { // NOLINT(performance-unnecessary-value-param) return Status{StatusCode::kUnimplemented, "needs-override"}; } StatusOr<google::pubsub::v1::Topic> TopicAdminConnection::GetTopic( GetTopicParams) { // NOLINT(performance-unnecessary-value-param) return Status{StatusCode::kUnimplemented, "needs-override"}; } StatusOr<google::pubsub::v1::Topic> TopicAdminConnection::UpdateTopic( UpdateTopicParams) { // NOLINT(performance-unnecessary-value-param) return Status{StatusCode::kUnimplemented, "needs-override"}; } // NOLINTNEXTLINE(performance-unnecessary-value-param) ListTopicsRange TopicAdminConnection::ListTopics(ListTopicsParams) { return internal::MakeUnimplementedPaginationRange<ListTopicsRange>(); } // NOLINTNEXTLINE(performance-unnecessary-value-param) Status TopicAdminConnection::DeleteTopic(DeleteTopicParams) { return Status{StatusCode::kUnimplemented, "needs-override"}; } StatusOr<google::pubsub::v1::DetachSubscriptionResponse> // NOLINTNEXTLINE(performance-unnecessary-value-param) TopicAdminConnection::DetachSubscription(DetachSubscriptionParams) { return Status{StatusCode::kUnimplemented, "needs-override"}; } ListTopicSubscriptionsRange TopicAdminConnection::ListTopicSubscriptions( ListTopicSubscriptionsParams) { // NOLINT(performance-unnecessary-value-param) return internal::MakeUnimplementedPaginationRange< ListTopicSubscriptionsRange>(); } ListTopicSnapshotsRange TopicAdminConnection::ListTopicSnapshots( ListTopicSnapshotsParams) { // NOLINT(performance-unnecessary-value-param) return internal::MakeUnimplementedPaginationRange<ListTopicSnapshotsRange>(); } std::shared_ptr<TopicAdminConnection> MakeTopicAdminConnection( std::initializer_list<pubsub_internal::NonConstructible>) { return MakeTopicAdminConnection(); } std::shared_ptr<TopicAdminConnection> MakeTopicAdminConnection(Options opts) { internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList, PolicyOptionList>(opts, __func__); opts = pubsub_internal::DefaultCommonOptions(std::move(opts)); auto background = internal::MakeBackgroundThreadsFactory(opts)(); auto auth = google::cloud::internal::CreateAuthenticationStrategy( background->cq(), opts); auto stub = pubsub_internal::CreateDefaultPublisherStub(auth->CreateChannel( opts.get<EndpointOption>(), internal::MakeChannelArguments(opts))); stub = DecorateTopicAdminStub(opts, std::move(auth), std::move(stub)); return std::make_shared<TopicAdminConnectionImpl>( std::move(background), std::move(stub), opts.get<pubsub::RetryPolicyOption>()->clone(), opts.get<pubsub::BackoffPolicyOption>()->clone()); } std::shared_ptr<TopicAdminConnection> MakeTopicAdminConnection( ConnectionOptions const& options, std::unique_ptr<pubsub::RetryPolicy const> retry_policy, std::unique_ptr<pubsub::BackoffPolicy const> backoff_policy) { auto opts = internal::MakeOptions(options); if (retry_policy) opts.set<RetryPolicyOption>(retry_policy->clone()); if (backoff_policy) opts.set<BackoffPolicyOption>(backoff_policy->clone()); return MakeTopicAdminConnection(std::move(opts)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsub namespace pubsub_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr<pubsub::TopicAdminConnection> MakeTestTopicAdminConnection( Options const& opts, std::shared_ptr<PublisherStub> stub) { auto background = internal::MakeBackgroundThreadsFactory(opts)(); auto auth = google::cloud::internal::CreateAuthenticationStrategy( background->cq(), opts); stub = pubsub::DecorateTopicAdminStub(opts, std::move(auth), std::move(stub)); return std::make_shared<pubsub::TopicAdminConnectionImpl>( std::move(background), std::move(stub), opts.get<pubsub::RetryPolicyOption>()->clone(), opts.get<pubsub::BackoffPolicyOption>()->clone()); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsub_internal } // namespace cloud } // namespace google
6ff351f41e7ddfa12cac3ab05c512a7541c5a95d
8433c3a0aced8c51ade4e9ace01ec80ba9624f70
/Two Pointer/Minimize the Absolute Difference.cpp
af1ef9f1915abeb11e82935f4365416e29b906f2
[]
no_license
VarunManchanda/InterViewBit-Solutions
5bf4d09a17766e04a1c68de8a55a502e1bca9fd7
4d7ecb4c4e2958d25e4ea34c0a0a6b6ff84e687f
refs/heads/master
2022-08-09T19:35:47.498130
2020-05-23T06:58:10
2020-05-23T06:58:10
266,248,116
0
0
null
null
null
null
UTF-8
C++
false
false
720
cpp
//Proof:- In order to minimize the difference abs(max-min) => abs(a-b) => a-b < INT_MAX only when a decrease and b increases, So we use //three pointers point from last and calculate the difference now in order to minimize the value we start to decrease maximum value. int Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) { int p = A.size()-1; int q = B.size()-1; int s = C.size()-1; int ans = 1e9; while(p>=0 and q>=0 and s>=0) { int cal = abs(max(A[p],max(B[q],C[s])) - min(A[p],min(B[q],C[s]))); ans = min(ans,cal); if(max(A[p],max(B[q],C[s]))==A[p]) p-=1; else if(max(A[p],max(B[q],C[s]))==B[q]) q-=1; else s-=1; } return ans; }
54b89fdd975686188ce590e3a6ee74e7ae04b914
98529dcc0f59731f48cdf592210eccf02834886f
/leetcode_链表_1/main.cpp
e97e7607a2f862d7b7eb38253c422c2c82a0457e
[]
no_license
HYIUYOU/print-lianbiao
10878bf509a7fd8d6ce92212175b7e4d8ebb5f72
631af60a610d0397d72b151af241a9148280ede4
refs/heads/master
2022-06-02T06:51:48.104442
2020-05-01T13:10:16
2020-05-01T13:10:16
260,461,777
0
0
null
null
null
null
UTF-8
C++
false
false
3,055
cpp
// // main.cpp // leetcode_链表_1 // // Created by 何忆源 on 2020/4/30. // Copyright © 2020 何忆源. All rights reserved. // #include <iostream> #include <stdio.h> #include <stdlib.h> struct Node //定义一个链表结构 { int data; //链表节点的数据 struct Node * pNext; //链表节点指向下一个节点的指针 }; int i; struct Node * create_list(void); //创建链表的函数声明 void traverse_list(struct Node *); //打印链表的函数声明 int main() { struct Node * pHead = NULL; //先给头指针赋值为NULL pHead = create_list(); //调用链表创建函数,并将头指针的值赋给pHead traverse_list(pHead); //打印链表 return 0; } struct Node * create_list(void) //创建链表的函数 { int len; //链表的节点数 int val; //链表节点中数据域的值 // int deldata; struct Node * pHead=(struct Node *)malloc(sizeof(struct Node)); //动态分配头结点的内存 if(pHead == NULL) { printf("内存分配失败,程序终止!\n"); exit(-1); } struct Node * pTail = pHead; //定义一个尾节点指针,将pHead的值赋给它 pTail->pNext = NULL; //尾节点的指针域一定为空 printf("请输入您需要生成的链表节点的个数:len ="); scanf("%d",&len); for (i=0;i<len;i++) { printf("请输入第%d个节点的值:",i+1); scanf("%d",&val); struct Node * pNew=(struct Node *)malloc(sizeof(struct Node)); //动态分配新节点的内存 if(pNew== NULL) { printf("内存分配失败,程序终止!\n"); exit(-1); } // printf("请输入要删除的节点"); // scanf("%d",&deldata); pNew->data = val; //把输入的值传给*pNew数据域 pNew->pNext = NULL; // *pNew是新的尾节点,所以 pNew->pNext应该为空 pTail->pNext = pNew; //把*pNew的地址传给pTail->pNext指针域,等效于*pTail.pNext=pNew //第一次的pTail->pNext = pNew相当于把首节点的地址给了头结点 pTail = pNew; //执行此操作,*pNew就变成了新的*pTail //之后的pTail = pNew则是让最后一个与上一个节点连接上 } return pHead; //返回 pHead的值 } void traverse_list(struct Node * pHead) //遍历链表 { struct Node * p = pHead->pNext; //定义一个指向下一个节点的指针 while(p!=NULL) //尾节点的指针域一定是NULL,如果非NULL,则继续打印 { printf("%d\t",p->data); p = p->pNext; //下一个节点的地址赋值给p } return; //循环结束 }
8b4d462411525022ced1fc1f30651259389844d4
37e2a3e18dc74e26a46e6f62f65d9aa3cbf6a2bf
/src/caffe/layers/broadcast_to_layer.cpp
bb17cbf2ee0b64ef03c852a0596d6bd501fb81d9
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
foss-for-synopsys-dwc-arc-processors/synopsys-caffe
bc5d91e81575460137fa22623ba01816413d3bf0
63123ca6c80b72365c87332bbb3de2995e063065
refs/heads/main
2023-09-02T10:25:17.991467
2023-08-02T11:01:05
2023-08-02T11:01:05
103,567,504
27
20
NOASSERTION
2023-08-02T10:44:05
2017-09-14T18:28:41
C++
UTF-8
C++
false
false
2,648
cpp
#include <vector> #include "caffe/layers/broadcast_to_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void BroadcastToLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const BroadcastToParameter& broadcast_to_param = this->layer_param_.broadcast_to_param(); output_shape_.clear(); std::copy(broadcast_to_param.shape().begin(), broadcast_to_param.shape().end(), std::back_inserter(output_shape_)); CHECK_GE(output_shape_.size(), bottom[0]->num_axes()) << "Output shape should not have less axis than input!"; int dim_diff = output_shape_.size() - bottom[0]->num_axes(); for(int i=output_shape_.size()-1; i>=dim_diff; i--) { CHECK_GT(output_shape_[i], 0) << "Values in output shape must be positive!"; CHECK(output_shape_[i]==bottom[0]->shape(i-dim_diff) || bottom[0]->shape(i-dim_diff)==1) << "The broadcasting shape is incompatible with the input!"; } } template <typename Dtype> void BroadcastToLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->Reshape(output_shape_); } template <typename Dtype> void BroadcastToLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); int count = top[0]->count(); int dim = top[0]->num_axes(); int dim_diff = output_shape_.size() - bottom[0]->num_axes(); // Assume top index (x,y,z) with top shape (A, B, C) // top offset d = xBC + yC + z // So to count the bottom index, should first figure out x, y, z // x = d / BC // y = (d % BC) / C // z = d % C // Then consider bottom shape (A', B', C'), where A' = 1 or A // So bottom offset = x'B'C' + y'C' + z for(int d=0; d<count; d++) { int offset = 0; for(int i=dim_diff;i<dim-1;i++) { int num = (d % top[0]->count(i)) / top[0]->count(i+1); int n0 = 1 == bottom[0]->shape(i-dim_diff) ? 0 : num; offset += n0 * bottom[0]->count(i-dim_diff+1); } int z = d % top[0]->shape(dim-1); int z0 = 1 == bottom[0]->shape(dim-dim_diff-1) ? 0 : z; offset += z0; top_data[d] = bottom_data[offset]; } } template <typename Dtype> void BroadcastToLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } //#ifdef CPU_ONLY //STUB_GPU(TileLayer); //#endif INSTANTIATE_CLASS(BroadcastToLayer); REGISTER_LAYER_CLASS(BroadcastTo); } // namespace caffe
a46bc927b3d8245c9440c42fc4c7c0139baa21f1
65cf7b6e29c31d106ee46f0c94db1036898a652f
/Chap02_source/swap2.cpp
dd524b2a249f6bb33370e02e74660ce37375f749
[]
no_license
umairsajid/Book_CPP_FreeLecByYoon
0b5881ff1ee6a567d418c85e7e5fe101dd5e6949
df3a86688efb287951d4d5697c6ee1685df7fc90
refs/heads/master
2021-01-18T12:37:12.043911
2015-09-29T10:24:20
2015-09-29T10:24:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
322
cpp
/* swap2.cpp */ #include <iostream> using std::cout; using std::endl; void swap(int &a, int &b) { int temp=a; a=b; b=temp; } int main(void) { int val1=10; int val2=20; cout<<"val1:"<<val1<<' '; cout<<"val2:"<<val2<<endl; swap(val1, val2); cout<<"val1:"<<val1<<' '; cout<<"val2:"<<val2<<endl; return 0; }
6cd7ad58a2323660a085ccd6fc5774ff4dd815c3
ad5b72656f0da99443003984c1e646cb6b3e67ea
/src/plugins/auto/common.hpp
877f9198eb84381cb4746483c577826a9435e63c
[ "Apache-2.0" ]
permissive
novakale/openvino
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
544c1acd2be086c35e9f84a7b4359439515a0892
refs/heads/master
2022-12-31T08:04:48.124183
2022-12-16T09:05:34
2022-12-16T09:05:34
569,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
5,323
hpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <map> #include <string> #include "ie_icore.hpp" #include "ie_metric_helpers.hpp" #include <ie_plugin_config.hpp> #include "cpp_interfaces/impl/ie_executable_network_thread_safe_default.hpp" #include "threading/ie_executor_manager.hpp" #include "threading/ie_immediate_executor.hpp" #include "threading/ie_istreams_executor.hpp" #include "threading/ie_itask_executor.hpp" #include "threading/ie_thread_safe_containers.hpp" #include "utils/log_util.hpp" #include <ie_performance_hints.hpp> #include "openvino/runtime/auto/properties.hpp" #include "ngraph/opsets/opset1.hpp" #include "transformations/utils/utils.hpp" #include "utils/log_util.hpp" #include "itt.hpp" #ifdef MULTIUNITTEST #define MOCKTESTMACRO virtual #define MultiDevicePlugin MockMultiDevicePlugin #else #define MOCKTESTMACRO #endif namespace MultiDevicePlugin { namespace IE = InferenceEngine; using DeviceName = std::string; using IInferPtr = IE::IInferRequestInternal::Ptr; using IExecNetwork = IE::IExecutableNetworkInternal; using SoInfer = IE::SoIInferRequestInternal; using SoExecNetwork = IE::SoExecutableNetworkInternal; using Time = std::chrono::time_point<std::chrono::steady_clock>; template<typename T> using DeviceMap = std::unordered_map<DeviceName, T>; struct DeviceInformation { DeviceName deviceName; std::map<std::string, std::string> config; int numRequestsPerDevices; std::string defaultDeviceID; DeviceName uniqueName; unsigned int devicePriority; }; struct WorkerInferRequest { SoInfer _inferRequest; IE::Task _task; std::exception_ptr _exceptionPtr = nullptr; std::list<Time> _startTimes; std::list<Time> _endTimes; int _index = 0; }; using NotBusyPriorityWorkerRequests = IE::ThreadSafeBoundedPriorityQueue<std::pair<int, WorkerInferRequest*>>; using NotBusyWorkerRequests = IE::ThreadSafeBoundedQueue<WorkerInferRequest*>; template <typename T> struct IdleGuard {}; template<> struct IdleGuard<NotBusyWorkerRequests> { explicit IdleGuard(WorkerInferRequest* workerInferRequestPtr, NotBusyWorkerRequests& notBusyWorkerRequests) : _workerInferRequestPtr{workerInferRequestPtr}, _notBusyWorkerRequests{&notBusyWorkerRequests} { } ~IdleGuard() { if (nullptr != _notBusyWorkerRequests) { _notBusyWorkerRequests->try_push(_workerInferRequestPtr); } } NotBusyWorkerRequests* Release() { auto notBusyWorkerRequests = _notBusyWorkerRequests; _notBusyWorkerRequests = nullptr; return notBusyWorkerRequests; } WorkerInferRequest* _workerInferRequestPtr = nullptr; NotBusyWorkerRequests* _notBusyWorkerRequests = nullptr; }; template<> struct IdleGuard<NotBusyPriorityWorkerRequests> { explicit IdleGuard(WorkerInferRequest* workerInferRequestPtr, NotBusyPriorityWorkerRequests& notBusyWorkerRequests) : _workerInferRequestPtr{workerInferRequestPtr}, _notBusyWorkerRequests{&notBusyWorkerRequests} { } ~IdleGuard() { if (nullptr != _notBusyWorkerRequests) { _notBusyWorkerRequests->try_push(std::make_pair(_workerInferRequestPtr->_index, _workerInferRequestPtr)); } } NotBusyPriorityWorkerRequests* Release() { auto notBusyWorkerRequests = _notBusyWorkerRequests; _notBusyWorkerRequests = nullptr; return notBusyWorkerRequests; } WorkerInferRequest* _workerInferRequestPtr = nullptr; NotBusyPriorityWorkerRequests* _notBusyWorkerRequests = nullptr; }; class ScheduleContext : public std::enable_shared_from_this<ScheduleContext> { public: using Ptr = std::shared_ptr<ScheduleContext>; std::shared_ptr<IE::ICore> _core; std::weak_ptr<IExecNetwork> _executableNetwork; std::string _LogTag; virtual ~ScheduleContext() = default; }; class MultiScheduleContext : public ScheduleContext { public: using Ptr = std::shared_ptr<MultiScheduleContext>; std::vector<DeviceInformation> _devicePriorities; std::vector<DeviceInformation> _devicePrioritiesInitial; std::unordered_map<std::string, IE::Parameter> _config; DeviceMap<SoExecNetwork> _networksPerDevice; std::mutex _mutex; bool _needPerfCounters; bool _batchingDisabled = {false}; bool _bindBuffer = false; virtual ~MultiScheduleContext() = default; }; class MultiDeviceInferencePlugin; class AutoScheduleContext : public MultiScheduleContext { public: using Ptr = std::shared_ptr<AutoScheduleContext>; std::string _modelPath; IE::CNNNetwork _network; std::string _strDevices; unsigned int _modelPriority = 0; std::string _performanceHint; std::mutex _confMutex; MultiDeviceInferencePlugin* _plugin; virtual ~AutoScheduleContext() = default; }; } // namespace MultiDevicePlugin
bde6b47063bedeba02f68b4146b40fec822c6b6a
63c8b9227a6b3178d918769042ecb060acc557be
/devmand/gateway/src/devmand/channels/cli/ReconnectingCli.h
d381fd2c6994dc02f79265b22730d40aa134ca77
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
snwfdhmp/magma
7c4898db68d2668fd39ed25f73bb9a2bc5959066
8b3ff20a2717337a83c8ef531fa773a851d2e54d
refs/heads/master
2020-12-06T09:06:25.806497
2020-01-07T18:27:09
2020-01-07T18:28:51
232,418,366
1
0
NOASSERTION
2020-01-07T21:12:28
2020-01-07T21:12:27
null
UTF-8
C++
false
false
2,264
h
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #pragma once #include <boost/thread/mutex.hpp> #include <devmand/channels/cli/Cli.h> #include <devmand/channels/cli/Command.h> #include <folly/Executor.h> #include <folly/executors/SerialExecutor.h> #include <folly/futures/Future.h> #include <folly/futures/ThreadWheelTimekeeper.h> namespace devmand { namespace channels { namespace cli { using namespace std; using namespace folly; using boost::mutex; using devmand::channels::cli::Cli; using devmand::channels::cli::Command; class ReconnectingCli : public Cli { public: static shared_ptr<ReconnectingCli> make( string id, shared_ptr<Executor> executor, function<SemiFuture<shared_ptr<Cli>>()>&& createCliStack, shared_ptr<Timekeeper> timekeeper, chrono::milliseconds quietPeriod); ~ReconnectingCli() override; folly::SemiFuture<std::string> executeRead(const ReadCommand cmd) override; folly::SemiFuture<std::string> executeWrite(const WriteCommand cmd) override; private: struct ReconnectParameters { string id; atomic<bool> isReconnecting; // TODO: merge with maybeCli atomic<bool> shutdown; shared_ptr<Executor> executor; function<SemiFuture<shared_ptr<Cli>>()> createCliStack; mutex cliMutex; // guarded by mutex shared_ptr<Cli> maybeCli; std::chrono::milliseconds quietPeriod; shared_ptr<Timekeeper> timekeeper; }; shared_ptr<ReconnectParameters> reconnectParameters; ReconnectingCli( string id, shared_ptr<Executor> executor, function<SemiFuture<shared_ptr<Cli>>()>&& createCliStack, shared_ptr<Timekeeper> timekeeper, chrono::milliseconds quietPeriod); SemiFuture<string> executeSomething( const string&& loggingPrefix, const function<SemiFuture<string>(shared_ptr<Cli>)>& innerFunc, const Command cmd); static void triggerReconnect(shared_ptr<ReconnectParameters> params); }; } // namespace cli } // namespace channels } // namespace devmand
f46868502c4dafb96c22bce727538d882221c82f
77f2080188c454ab04cd50311799f40b575b1a18
/test/TestOramSelector.cpp
a9da222508bce6c69edf460f92ff103278f923a1
[]
no_license
jianyu-m/OnionOram
671cfe87ebc83bfa807bfb473e6e071bfa85a21a
c03fb91d2b2672cae73c608af95aa97156a4ea1f
refs/heads/master
2016-09-13T12:30:08.603230
2016-06-03T08:52:32
2016-06-03T08:52:32
59,989,101
3
1
null
null
null
null
UTF-8
C++
false
false
2,490
cpp
// // Created by maxxie on 16-5-28. // #include <cassert> #include "../src/OramSelector.h" #include "../src/OramCrypto.h" int main(int argc, char **args) { char *key = "ORAM"; OramCrypto::init_crypto(key, 4, 9, 100, 1024); OramBlock::init_size(1024, 10240); unsigned char buf[40960]; OramBlock **block_list = (OramBlock**)malloc(sizeof(OramBlock*)*5); for (int i = 0;i<1;i++) { buf[0] = 0; block_list[0] = new OramBlock(buf); unsigned char *de_0 = (unsigned char*)block_list[0]->decrypt(); buf[0] = 1; block_list[1] = new OramBlock(buf); unsigned char *de_1 = (unsigned char*)block_list[1]->decrypt(); buf[0] = 2; block_list[2] = new OramBlock(buf); unsigned char *de_2 = (unsigned char*)block_list[2]->decrypt(); buf[0] = 3; block_list[3] = new OramBlock(buf); unsigned char *de_3 = (unsigned char*)block_list[3]->decrypt(); buf[0] = 4; block_list[4] = new OramBlock(buf); unsigned char *de_4 = (unsigned char*)block_list[4]->decrypt(); OramSelector *oramSelector = new OramSelector(5, 1, 1); // // damgard_jurik_ciphertext_t *sec_0 = OramCrypto::get_crypto()->ahe_sys->encrypt(new damgard_jurik_plaintext_t((unsigned long)0), 10); // damgard_jurik_ciphertext_t *sec_1 = OramCrypto::get_crypto()->ahe_sys->encrypt(new damgard_jurik_plaintext_t((unsigned long)0), 10); // damgard_jurik_ciphertext_t sec_result = ((*sec_0)^(*block_list[1]->block[0])) * ((*sec_1)^(*block_list[2]->block[0])) ; // damgard_jurik_plaintext_t *pl = OramCrypto::get_crypto()->ahe_sys->decrypt(&sec_result); // unsigned char * one_de = (unsigned char *)pl->to_bytes(); // damgard_jurik_ciphertext_t *dd = new damgard_jurik_ciphertext_t(pl->text, 9); // damgard_jurik *dj = OramCrypto::get_crypto()->get_crypto()->ahe_sys; // unsigned char *ded = (unsigned char *)OramCrypto::get_crypto()->ahe_sys->decrypt(dd)->to_bytes(); OramBlock *select_block = oramSelector->select(block_list); unsigned char *de_blo = (unsigned char *) select_block->decrypt(); assert(de_blo[0] == i % 5 + 1); void *by = oramSelector->to_bytes(); OramSelector *oramSelector_re = new OramSelector(5, by, 1); for (int j = 0;j < 5;j++) { assert(mpz_cmp(oramSelector->select_vector[j]->text, oramSelector_re->select_vector[j]->text) == 0); } } return 0; }
c26bc463378a9ac691bf514bc1975cb5d09dcddf
02b1221113ab0c851f4bd77cfbb83721701f0ee8
/source/include/gui.hpp
f26344dd45c0140e014f577d645596b86061ab9a
[ "MIT" ]
permissive
TheLastBilly/psCast
dab1498b1eff0847846a4bae36e5994b8c111c56
b57837e84c7dbe419a255454f135d8ce029585a9
refs/heads/master
2022-12-16T03:09:34.722047
2020-09-16T17:31:15
2020-09-16T17:31:15
277,024,442
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
hpp
#pragma once #include <psp2/ctrl.h> #include <psp2/types.h> #include <vita2d.h> #include <cstring> #define PSCAST_DISPLAY_WIDTH 960 #define PSCAST_DISPLAY_HEIGHT 544 class GUI { public: enum { OK, BAD_PARAMETER, }; protected: SceCtrlData ctrl_data; SceUInt32 pressed_buttons = 0; static constexpr const size_t input_delay = 500; virtual int setup() = 0; virtual int draw() = 0; virtual void updateInput( SceCtrlData &ctrl_data ); virtual void update() { memset(&ctrl_data, 0, sizeof(ctrl_data)); sceCtrlPeekBufferNegative(0, &ctrl_data, 1); updateInput(ctrl_data); draw(); } static vita2d_font * system_font; private: static GUI * current_gui; static bool is_init; public: GUI(){} static void init() { if(is_init) return; vita2d_init(); system_font = vita2d_load_font_file("app0:system_font.tff"); is_init = true; } static void end() { if(!is_init) return; vita2d_fini(); is_init = false; } static int checkoutActiveGUI( GUI * gui ) { if(gui != nullptr) { current_gui = gui; current_gui->setup(); return OK; } return BAD_PARAMETER; } static void cycleActiveGUI() { if(current_gui != nullptr) current_gui->update(); } };
bc91149c574129f601ba010df5ab6e4b60e597f4
dedbf4be6423b374ca70cc3a120b33f95c85541e
/sources/Device/src/Hardware/VCP_d.h
94a64c351039222740641fe82b4409360d126825
[]
no_license
ghsecuritylab/G6-49
e2595ae668775ae3bc1384c838d32a356445fa72
afc559b8edffd883e095dead47f1f2271aaf8e1d
refs/heads/master
2021-02-28T18:36:14.858735
2020-03-06T16:08:55
2020-03-06T16:08:55
245,723,276
0
0
null
2020-03-07T23:48:16
2020-03-07T23:48:16
null
WINDOWS-1251
C++
false
false
876
h
#pragma once #include <usbd_def.h> class SimpleMessage; struct DVCP { static const int DEVICE_FS = 0; /// Инициализация static void Init(); static void SendData(const void *data, uint size = 0); /// Передаётся строка без завершающего символа static void SendString(char *data); /// Передача строки с символом конца строки static void SendStringEOF(char *data); static void SendByte(uint8 data); static USBD_HandleTypeDef handleUSBD; struct Handler { static void Processing(SimpleMessage *msg); }; static void SetConnectedToUSB(bool connected); static void SetCableUSBisConnected(bool connected); private: bool PrevSendingComplete(); static bool connectedToUSB; static bool cableUSBisConnected; };
b8d8abc0559a298ff7a9dc092827719c625fcfa4
40420e55ae2b25709872cac5bdf39fe250519922
/RSAction/Source/RSAction/Public/Player/SoldierSpectatorPawn.h
44a0899042802a08fa7099791928e5af26da6338
[]
no_license
magrlemon/RSActionII
2d85709f05d63f5b1c39038e9918f86989ff9e29
26ae7910afdedfdf353f6fbd98f3e4a92b21dc7f
refs/heads/master
2020-12-01T19:26:07.617189
2020-05-13T13:41:45
2020-05-13T13:41:45
230,740,815
1
1
null
null
null
null
UTF-8
C++
false
false
557
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "SoldierSpectatorPawn.generated.h" UCLASS(config = Game, Blueprintable, BlueprintType) class ASoldierSpectatorPawn : public ASpectatorPawn { GENERATED_UCLASS_BODY() // Begin ASpectatorPawn overrides /** Overridden to implement Key Bindings the match the player controls */ virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override; // End Pawn overrides // Frame rate linked look void LookUpAtRate(float Val); };
81133abc3f6673fb60e914b4897facc113acdcd0
742717902389023f89ca6fccf741a24d8702fc35
/source/code/system/ps2linux/msx.h
b762403b041b94508f022b530687c835d69d54c7
[]
no_license
stuckie/plightoftheweedunks
cc67f0b38422126672817dd2e6034636fbbe5766
17a8123ce0cb2210022bae9b045055c824d027a5
refs/heads/master
2021-01-10T03:30:47.933682
2015-10-19T20:09:13
2015-10-19T20:09:13
44,559,185
1
0
null
null
null
null
UTF-8
C++
false
false
946
h
#ifndef _AUDIO_H_ #define _AUDIO_H_ // Required for forward reference in AudioDevice class class SoundSample; // class to handle interface to the audio device class AudioDevice { public: AudioDevice(const int Which); ~AudioDevice(); int Open(const int which); void Close(void); void HandleAudio(void); void SetSoundSample(SoundSample * const Sample); int GetFragmentSize(void) const; bool silence; protected: int GetFreeFragments(void) const; SoundSample * m_Current; int m_AudioFD; int m_FragmentSize; unsigned char * m_Silence; }; // class to handle audio sample class SoundSample { public: SoundSample(char * Filename, AudioDevice * const pAD); ~SoundSample(); void Load(char * Filename); void Reset(); void Play(void); unsigned char * GetNextFragment(); protected: AudioDevice * m_pAD; unsigned char * m_Stream; long m_Location; int m_FragSize; long m_NumFragments; char m_SampleName[32]; }; #endif
5f44be134bbcc761ec6ef85843a0b5bbc121768f
61e0491fe2690501041fcc4758543d6633d577b2
/offsets.h
b4a183b1318779262382a111dfda69db9be7ff39
[]
no_license
wem092808js/aaa
751d322e88e5c1f183ab7f2483324b908bdf25fc
bec3f694ef0aedea0ae6ecaf7badd4ef5618416d
refs/heads/master
2021-01-20T09:00:30.726210
2017-05-04T12:35:17
2017-05-04T12:35:17
90,211,421
0
0
null
null
null
null
UTF-8
C++
false
false
4,093
h
#pragma once #include "Utilities.h" // Various offsets namespace Offsets { // Sets up all the shit we need void Initialise(); // Addresses of loaded game modules namespace Modules { extern DWORD Client; extern DWORD Engine; extern DWORD VGUI2; extern DWORD VGUISurface; extern DWORD Material; extern DWORD VPhysics; extern DWORD Stdlib; }; // Virtual Method Table Indexes namespace VMT { //CHL Client extern DWORD CHL_GetAllClasses; //Engine Client extern DWORD Engine_GetScreenSize; extern DWORD Engine_GetPlayerInfo; extern DWORD Engine_GetLocalPlayer; extern DWORD Engine_Time; extern DWORD Engine_GetViewAngles; extern DWORD Engine_SetViewAngles; extern DWORD Engine_GetMaxClients; extern DWORD Engine_IsConnected; extern DWORD Engine_IsInGame; extern DWORD Engine_WorldToScreenMatrix; extern DWORD Engine_ClientCmd_Unrestricted; // Panels extern DWORD Panel_GetName; extern DWORD Panel_PaintTraverse; // Surface extern DWORD Surface_DrawSetColorA; extern DWORD Surface_DrawSetColorB; extern DWORD Surface_DrawFilledRect; extern DWORD Surface_DrawOutlinedRect; extern DWORD Surface_DrawLine; extern DWORD Surface_DrawSetTextFont; extern DWORD Surface_DrawSetTextColorA; extern DWORD Surface_DrawSetTextColorB; extern DWORD Surface_DrawSetTextPos; extern DWORD Surface_DrawPrintText; extern DWORD Surface_DrawSetTextureRGBA; extern DWORD Surface_DrawSetTexture; extern DWORD Surface_CreateNewTextureID; extern DWORD Surface_FontCreate; extern DWORD Surface_SetFontGlyphSet; extern DWORD Surface_GetTextSize; extern DWORD Surface_DrawOutlinedCircle; extern DWORD Surface_SurfaceGetCursorPos; extern DWORD Surface_DrawTexturedPolygon; extern DWORD Material_GetName; extern DWORD Material_SetMaterialVarFlag; extern DWORD Material_GetMaterialVarFlag; extern DWORD Material_AlphaModulate; extern DWORD Material_ColorModulate; extern DWORD Material_IncrementReferenceCount; extern DWORD MaterialSystem_FindMaterial; extern DWORD MaterialSystem_CreateMaterial; extern DWORD ModelRender_ForcedMaterialOverride; extern DWORD ModelRender_DrawModelExecute; extern DWORD ModelInfo_GetModelName; extern DWORD ModelInfo_GetStudiomodel; extern DWORD RenderView_SetBlend; extern DWORD RenderView_SetColorModulation; // Weapon entities extern DWORD Weapon_GetSpread; }; // Addresses of engine functions to call namespace Functions { extern DWORD KeyValues_KeyValues; extern DWORD KeyValues_LoadFromBuffer; extern DWORD dwCalcPlayerView; }; }; struct COffsets { DWORD m_iHealth; DWORD m_fCameraInThirdPerson; DWORD m_vecCameraOffset; DWORD m_iTeamNum; DWORD m_bDormant; DWORD m_bGunGameImmunity; DWORD m_lifeState; DWORD m_fFlags; DWORD m_Local; DWORD m_nTickBase; DWORD m_nForceBone; DWORD m_mBoneMatrix; DWORD m_nModelIndex; DWORD m_viewPunchAngle; DWORD m_aimPunchAngle; DWORD m_vecOrigin; DWORD m_vecViewOffset; DWORD m_vecVelocity; DWORD m_szLastPlaceName; DWORD m_flNextPrimaryAttack; DWORD m_hActiveWeapon; DWORD m_fAccuracyPenalty; DWORD m_Collision; DWORD m_iShotsFired; DWORD m_iWeaponID; DWORD m_nMoveType; DWORD m_nHitboxSet; DWORD m_bHasHelmet; DWORD m_ArmorValue; DWORD m_CollisionGroup; DWORD m_iClass; DWORD m_bIsBroken; DWORD m_angEyeAngles; DWORD m_hOwnerEntity; DWORD m_flC4Blow; DWORD m_flFlashDuration; DWORD m_iGlowIndex; DWORD m_nFallbackPaintKit; DWORD m_nFallbackSeed; DWORD m_flFallbackWear; DWORD m_nFallbackStatTrak; DWORD m_AttributeManager; DWORD m_Item; DWORD m_iEntityLevel; DWORD m_iItemIDHigh; DWORD m_iItemIDLow; DWORD m_iAccountID; DWORD m_iEntityQuality; DWORD m_OriginalOwnerXuidLow; DWORD m_OriginalOwnerXuidHigh; DWORD m_iItemDefinitionIndex; DWORD m_iClip1; DWORD m_bReloadVisuallyComplete; //sigs DWORD CalcPlayerView; DWORD d3d9Device; DWORD SendPacket; DWORD GlowManager; DWORD LoadFromBufferEx; DWORD InitKeyValuesEx; DWORD ServerRankRevealAllEx; DWORD IsReadyEx; }; extern COffsets offsets; namespace Offsets { extern void GrabOffsets(); }
eaade13286b14e8ab77c3ae55decbb94bfa5bcdd
5f637b57cfc6298118d0bb7c6526c066fe553702
/tcpp_chuffed/src/NegConstraint.cpp
35ba87026e60afe73b50c76872d77e438f0112ab
[ "MIT" ]
permissive
Behrouz-Babaki/TCPP-chuffed
aef24c4c62164be529c4e4c0a562e10ee7b2ab57
d832b44690914ef4b73d71bc7e565efb98e42937
refs/heads/master
2022-12-27T05:33:00.603551
2020-09-25T03:06:25
2020-09-25T03:06:25
297,758,710
1
0
null
null
null
null
UTF-8
C++
false
false
32
cpp
../../tcpp/src/NegConstraint.cpp
9048757014072ca804ef728d72ac10c616e91dbe
3f1619529291bcebdaf9d2faa94d8e07b7b7efda
/Polybench/stencils/jacobi-2d-imper/fir_prj/classic/syn/systemc/kernel_jacobi_2d_imper.h
1b6bb29bc56d8b8f33db1f186085767d5b418f7f
[]
no_license
Victorlzd/High_Level_Synthesis_Trainee
6efb431b0de4f5ef84cc4e5bad90a24c4c9b434d
01350bb65de0fae9377aa52986a3541c27e6a9c2
refs/heads/master
2021-09-21T22:28:22.140443
2018-08-31T22:08:27
2018-08-31T22:08:27
137,374,417
0
0
null
null
null
null
UTF-8
C++
false
false
19,886
h
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2018.2 // Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved. // // =========================================================== #ifndef _kernel_jacobi_2d_imper_HH_ #define _kernel_jacobi_2d_imper_HH_ #include "systemc.h" #include "AESL_pkg.h" #include "kernel_jacobi_2d_bkb.h" #include "kernel_jacobi_2d_cud.h" #include "kernel_jacobi_2d_dEe.h" namespace ap_rtl { struct kernel_jacobi_2d_imper : public sc_module { // Port declarations 21 sc_in_clk ap_clk; sc_in< sc_logic > ap_rst; sc_in< sc_logic > ap_start; sc_out< sc_logic > ap_done; sc_out< sc_logic > ap_idle; sc_out< sc_logic > ap_ready; sc_in< sc_lv<32> > tsteps; sc_in< sc_lv<32> > n; sc_out< sc_lv<20> > A_address0; sc_out< sc_logic > A_ce0; sc_in< sc_lv<64> > A_q0; sc_out< sc_lv<20> > A_address1; sc_out< sc_logic > A_ce1; sc_out< sc_logic > A_we1; sc_out< sc_lv<64> > A_d1; sc_in< sc_lv<64> > A_q1; sc_out< sc_lv<20> > B_address0; sc_out< sc_logic > B_ce0; sc_out< sc_logic > B_we0; sc_out< sc_lv<64> > B_d0; sc_in< sc_lv<64> > B_q0; sc_signal< sc_logic > ap_var_for_const0; sc_signal< sc_lv<64> > ap_var_for_const1; // Module declarations kernel_jacobi_2d_imper(sc_module_name name); SC_HAS_PROCESS(kernel_jacobi_2d_imper); ~kernel_jacobi_2d_imper(); sc_trace_file* mVcdFile; ofstream mHdltvinHandle; ofstream mHdltvoutHandle; kernel_jacobi_2d_bkb<1,14,64,64,64>* kernel_jacobi_2d_bkb_U1; kernel_jacobi_2d_cud<1,59,64,64,64>* kernel_jacobi_2d_cud_U2; kernel_jacobi_2d_dEe<1,4,10,11,20>* kernel_jacobi_2d_dEe_U3; kernel_jacobi_2d_dEe<1,4,10,11,20>* kernel_jacobi_2d_dEe_U4; kernel_jacobi_2d_dEe<1,4,10,11,20>* kernel_jacobi_2d_dEe_U5; kernel_jacobi_2d_dEe<1,4,10,11,20>* kernel_jacobi_2d_dEe_U6; sc_signal< sc_lv<141> > ap_CS_fsm; sc_signal< sc_logic > ap_CS_fsm_state1; sc_signal< sc_lv<64> > reg_183; sc_signal< sc_logic > ap_CS_fsm_state13; sc_signal< sc_logic > ap_CS_fsm_state27; sc_signal< sc_logic > ap_CS_fsm_state41; sc_signal< sc_logic > ap_CS_fsm_state55; sc_signal< sc_lv<64> > grp_fu_174_p2; sc_signal< sc_lv<64> > reg_190; sc_signal< sc_logic > ap_CS_fsm_state69; sc_signal< sc_lv<5> > t_1_fu_202_p2; sc_signal< sc_lv<5> > t_1_reg_377; sc_signal< sc_logic > ap_CS_fsm_state2; sc_signal< sc_lv<10> > i_2_fu_214_p2; sc_signal< sc_lv<10> > i_2_reg_385; sc_signal< sc_logic > ap_CS_fsm_state3; sc_signal< sc_lv<1> > exitcond3_fu_208_p2; sc_signal< sc_lv<10> > tmp_3_fu_220_p2; sc_signal< sc_lv<10> > tmp_3_reg_391; sc_signal< sc_logic > ap_CS_fsm_state4; sc_signal< sc_lv<20> > grp_fu_350_p2; sc_signal< sc_lv<20> > tmp_1_reg_411; sc_signal< sc_logic > ap_CS_fsm_state7; sc_signal< sc_lv<20> > grp_fu_356_p2; sc_signal< sc_lv<20> > tmp_2_reg_418; sc_signal< sc_lv<20> > grp_fu_362_p2; sc_signal< sc_lv<20> > tmp_4_reg_423; sc_signal< sc_lv<10> > tmp_8_fu_242_p2; sc_signal< sc_lv<10> > tmp_8_reg_431; sc_signal< sc_logic > ap_CS_fsm_state8; sc_signal< sc_lv<1> > exitcond2_fu_236_p2; sc_signal< sc_lv<20> > tmp_7_fu_252_p2; sc_signal< sc_lv<20> > tmp_7_reg_436; sc_signal< sc_logic > ap_CS_fsm_state9; sc_signal< sc_lv<20> > tmp_9_fu_257_p2; sc_signal< sc_lv<20> > tmp_9_reg_441; sc_signal< sc_lv<20> > tmp_12_fu_262_p2; sc_signal< sc_lv<20> > tmp_12_reg_446; sc_signal< sc_lv<20> > tmp_14_fu_270_p2; sc_signal< sc_lv<20> > tmp_14_reg_451; sc_signal< sc_lv<10> > j_2_fu_275_p2; sc_signal< sc_lv<10> > j_2_reg_456; sc_signal< sc_lv<64> > tmp_18_cast_fu_281_p1; sc_signal< sc_lv<64> > tmp_18_cast_reg_462; sc_signal< sc_logic > ap_CS_fsm_state10; sc_signal< sc_lv<20> > tmp_15_fu_292_p2; sc_signal< sc_lv<20> > tmp_15_reg_477; sc_signal< sc_lv<64> > A_load_1_reg_482; sc_signal< sc_logic > ap_CS_fsm_state24; sc_signal< sc_logic > ap_CS_fsm_state38; sc_signal< sc_logic > ap_CS_fsm_state52; sc_signal< sc_logic > ap_CS_fsm_state70; sc_signal< sc_logic > ap_CS_fsm_state72; sc_signal< sc_lv<1> > exitcond1_fu_309_p2; sc_signal< sc_lv<20> > grp_fu_368_p2; sc_signal< sc_lv<20> > tmp_6_reg_515; sc_signal< sc_logic > ap_CS_fsm_state75; sc_signal< sc_lv<20> > tmp_16_fu_329_p2; sc_signal< sc_lv<20> > tmp_16_reg_523; sc_signal< sc_logic > ap_CS_fsm_state76; sc_signal< sc_lv<1> > exitcond_fu_319_p2; sc_signal< sc_lv<10> > j_3_fu_334_p2; sc_signal< sc_lv<10> > j_3_reg_528; sc_signal< sc_lv<10> > i_3_fu_340_p2; sc_signal< sc_lv<64> > tmp_23_cast_fu_346_p1; sc_signal< sc_lv<64> > tmp_23_cast_reg_538; sc_signal< sc_logic > ap_CS_fsm_state77; sc_signal< sc_lv<64> > B_load_reg_548; sc_signal< sc_logic > ap_CS_fsm_state80; sc_signal< sc_lv<64> > grp_fu_178_p2; sc_signal< sc_lv<64> > tmp_13_reg_553; sc_signal< sc_logic > ap_CS_fsm_state139; sc_signal< sc_logic > ap_CS_fsm_state140; sc_signal< sc_lv<5> > t_reg_116; sc_signal< sc_lv<10> > i_reg_127; sc_signal< sc_lv<1> > exitcond4_fu_196_p2; sc_signal< sc_lv<10> > j_reg_139; sc_signal< sc_logic > ap_CS_fsm_state71; sc_signal< sc_lv<10> > i_1_reg_151; sc_signal< sc_lv<10> > j_1_reg_163; sc_signal< sc_logic > ap_CS_fsm_state141; sc_signal< sc_lv<64> > tmp_21_cast_fu_285_p1; sc_signal< sc_lv<64> > tmp_22_cast_fu_297_p1; sc_signal< sc_lv<64> > tmp_19_cast_fu_301_p1; sc_signal< sc_lv<64> > tmp_20_cast_fu_305_p1; sc_signal< sc_logic > ap_CS_fsm_state11; sc_signal< sc_logic > ap_CS_fsm_state12; sc_signal< sc_logic > ap_CS_fsm_state25; sc_signal< sc_logic > ap_CS_fsm_state26; sc_signal< sc_logic > ap_CS_fsm_state39; sc_signal< sc_logic > ap_CS_fsm_state40; sc_signal< sc_logic > ap_CS_fsm_state53; sc_signal< sc_logic > ap_CS_fsm_state54; sc_signal< sc_logic > ap_CS_fsm_state78; sc_signal< sc_logic > ap_CS_fsm_state79; sc_signal< sc_lv<64> > grp_fu_174_p0; sc_signal< sc_lv<64> > grp_fu_174_p1; sc_signal< sc_logic > ap_CS_fsm_state14; sc_signal< sc_logic > ap_CS_fsm_state28; sc_signal< sc_logic > ap_CS_fsm_state42; sc_signal< sc_logic > ap_CS_fsm_state56; sc_signal< sc_logic > ap_CS_fsm_state81; sc_signal< sc_lv<20> > tmp_7_cast_fu_248_p1; sc_signal< sc_lv<20> > tmp_9_cast_fu_267_p1; sc_signal< sc_lv<20> > tmp_1_cast_fu_289_p1; sc_signal< sc_lv<20> > tmp_12_cast_fu_325_p1; sc_signal< sc_lv<10> > grp_fu_350_p0; sc_signal< sc_lv<11> > grp_fu_350_p1; sc_signal< sc_lv<10> > grp_fu_356_p0; sc_signal< sc_lv<11> > grp_fu_356_p1; sc_signal< sc_lv<10> > grp_fu_362_p0; sc_signal< sc_lv<11> > grp_fu_362_p1; sc_signal< sc_lv<10> > grp_fu_368_p0; sc_signal< sc_lv<11> > grp_fu_368_p1; sc_signal< sc_lv<141> > ap_NS_fsm; sc_signal< sc_lv<20> > grp_fu_350_p00; sc_signal< sc_lv<20> > grp_fu_356_p00; sc_signal< sc_lv<20> > grp_fu_362_p00; sc_signal< sc_lv<20> > grp_fu_368_p00; static const sc_logic ap_const_logic_1; static const sc_logic ap_const_logic_0; static const sc_lv<141> ap_ST_fsm_state1; static const sc_lv<141> ap_ST_fsm_state2; static const sc_lv<141> ap_ST_fsm_state3; static const sc_lv<141> ap_ST_fsm_state4; static const sc_lv<141> ap_ST_fsm_state5; static const sc_lv<141> ap_ST_fsm_state6; static const sc_lv<141> ap_ST_fsm_state7; static const sc_lv<141> ap_ST_fsm_state8; static const sc_lv<141> ap_ST_fsm_state9; static const sc_lv<141> ap_ST_fsm_state10; static const sc_lv<141> ap_ST_fsm_state11; static const sc_lv<141> ap_ST_fsm_state12; static const sc_lv<141> ap_ST_fsm_state13; static const sc_lv<141> ap_ST_fsm_state14; static const sc_lv<141> ap_ST_fsm_state15; static const sc_lv<141> ap_ST_fsm_state16; static const sc_lv<141> ap_ST_fsm_state17; static const sc_lv<141> ap_ST_fsm_state18; static const sc_lv<141> ap_ST_fsm_state19; static const sc_lv<141> ap_ST_fsm_state20; static const sc_lv<141> ap_ST_fsm_state21; static const sc_lv<141> ap_ST_fsm_state22; static const sc_lv<141> ap_ST_fsm_state23; static const sc_lv<141> ap_ST_fsm_state24; static const sc_lv<141> ap_ST_fsm_state25; static const sc_lv<141> ap_ST_fsm_state26; static const sc_lv<141> ap_ST_fsm_state27; static const sc_lv<141> ap_ST_fsm_state28; static const sc_lv<141> ap_ST_fsm_state29; static const sc_lv<141> ap_ST_fsm_state30; static const sc_lv<141> ap_ST_fsm_state31; static const sc_lv<141> ap_ST_fsm_state32; static const sc_lv<141> ap_ST_fsm_state33; static const sc_lv<141> ap_ST_fsm_state34; static const sc_lv<141> ap_ST_fsm_state35; static const sc_lv<141> ap_ST_fsm_state36; static const sc_lv<141> ap_ST_fsm_state37; static const sc_lv<141> ap_ST_fsm_state38; static const sc_lv<141> ap_ST_fsm_state39; static const sc_lv<141> ap_ST_fsm_state40; static const sc_lv<141> ap_ST_fsm_state41; static const sc_lv<141> ap_ST_fsm_state42; static const sc_lv<141> ap_ST_fsm_state43; static const sc_lv<141> ap_ST_fsm_state44; static const sc_lv<141> ap_ST_fsm_state45; static const sc_lv<141> ap_ST_fsm_state46; static const sc_lv<141> ap_ST_fsm_state47; static const sc_lv<141> ap_ST_fsm_state48; static const sc_lv<141> ap_ST_fsm_state49; static const sc_lv<141> ap_ST_fsm_state50; static const sc_lv<141> ap_ST_fsm_state51; static const sc_lv<141> ap_ST_fsm_state52; static const sc_lv<141> ap_ST_fsm_state53; static const sc_lv<141> ap_ST_fsm_state54; static const sc_lv<141> ap_ST_fsm_state55; static const sc_lv<141> ap_ST_fsm_state56; static const sc_lv<141> ap_ST_fsm_state57; static const sc_lv<141> ap_ST_fsm_state58; static const sc_lv<141> ap_ST_fsm_state59; static const sc_lv<141> ap_ST_fsm_state60; static const sc_lv<141> ap_ST_fsm_state61; static const sc_lv<141> ap_ST_fsm_state62; static const sc_lv<141> ap_ST_fsm_state63; static const sc_lv<141> ap_ST_fsm_state64; static const sc_lv<141> ap_ST_fsm_state65; static const sc_lv<141> ap_ST_fsm_state66; static const sc_lv<141> ap_ST_fsm_state67; static const sc_lv<141> ap_ST_fsm_state68; static const sc_lv<141> ap_ST_fsm_state69; static const sc_lv<141> ap_ST_fsm_state70; static const sc_lv<141> ap_ST_fsm_state71; static const sc_lv<141> ap_ST_fsm_state72; static const sc_lv<141> ap_ST_fsm_state73; static const sc_lv<141> ap_ST_fsm_state74; static const sc_lv<141> ap_ST_fsm_state75; static const sc_lv<141> ap_ST_fsm_state76; static const sc_lv<141> ap_ST_fsm_state77; static const sc_lv<141> ap_ST_fsm_state78; static const sc_lv<141> ap_ST_fsm_state79; static const sc_lv<141> ap_ST_fsm_state80; static const sc_lv<141> ap_ST_fsm_state81; static const sc_lv<141> ap_ST_fsm_state82; static const sc_lv<141> ap_ST_fsm_state83; static const sc_lv<141> ap_ST_fsm_state84; static const sc_lv<141> ap_ST_fsm_state85; static const sc_lv<141> ap_ST_fsm_state86; static const sc_lv<141> ap_ST_fsm_state87; static const sc_lv<141> ap_ST_fsm_state88; static const sc_lv<141> ap_ST_fsm_state89; static const sc_lv<141> ap_ST_fsm_state90; static const sc_lv<141> ap_ST_fsm_state91; static const sc_lv<141> ap_ST_fsm_state92; static const sc_lv<141> ap_ST_fsm_state93; static const sc_lv<141> ap_ST_fsm_state94; static const sc_lv<141> ap_ST_fsm_state95; static const sc_lv<141> ap_ST_fsm_state96; static const sc_lv<141> ap_ST_fsm_state97; static const sc_lv<141> ap_ST_fsm_state98; static const sc_lv<141> ap_ST_fsm_state99; static const sc_lv<141> ap_ST_fsm_state100; static const sc_lv<141> ap_ST_fsm_state101; static const sc_lv<141> ap_ST_fsm_state102; static const sc_lv<141> ap_ST_fsm_state103; static const sc_lv<141> ap_ST_fsm_state104; static const sc_lv<141> ap_ST_fsm_state105; static const sc_lv<141> ap_ST_fsm_state106; static const sc_lv<141> ap_ST_fsm_state107; static const sc_lv<141> ap_ST_fsm_state108; static const sc_lv<141> ap_ST_fsm_state109; static const sc_lv<141> ap_ST_fsm_state110; static const sc_lv<141> ap_ST_fsm_state111; static const sc_lv<141> ap_ST_fsm_state112; static const sc_lv<141> ap_ST_fsm_state113; static const sc_lv<141> ap_ST_fsm_state114; static const sc_lv<141> ap_ST_fsm_state115; static const sc_lv<141> ap_ST_fsm_state116; static const sc_lv<141> ap_ST_fsm_state117; static const sc_lv<141> ap_ST_fsm_state118; static const sc_lv<141> ap_ST_fsm_state119; static const sc_lv<141> ap_ST_fsm_state120; static const sc_lv<141> ap_ST_fsm_state121; static const sc_lv<141> ap_ST_fsm_state122; static const sc_lv<141> ap_ST_fsm_state123; static const sc_lv<141> ap_ST_fsm_state124; static const sc_lv<141> ap_ST_fsm_state125; static const sc_lv<141> ap_ST_fsm_state126; static const sc_lv<141> ap_ST_fsm_state127; static const sc_lv<141> ap_ST_fsm_state128; static const sc_lv<141> ap_ST_fsm_state129; static const sc_lv<141> ap_ST_fsm_state130; static const sc_lv<141> ap_ST_fsm_state131; static const sc_lv<141> ap_ST_fsm_state132; static const sc_lv<141> ap_ST_fsm_state133; static const sc_lv<141> ap_ST_fsm_state134; static const sc_lv<141> ap_ST_fsm_state135; static const sc_lv<141> ap_ST_fsm_state136; static const sc_lv<141> ap_ST_fsm_state137; static const sc_lv<141> ap_ST_fsm_state138; static const sc_lv<141> ap_ST_fsm_state139; static const sc_lv<141> ap_ST_fsm_state140; static const sc_lv<141> ap_ST_fsm_state141; static const sc_lv<32> ap_const_lv32_0; static const sc_lv<32> ap_const_lv32_C; static const sc_lv<32> ap_const_lv32_1A; static const sc_lv<32> ap_const_lv32_28; static const sc_lv<32> ap_const_lv32_36; static const sc_lv<32> ap_const_lv32_44; static const sc_lv<32> ap_const_lv32_1; static const sc_lv<32> ap_const_lv32_2; static const sc_lv<1> ap_const_lv1_0; static const sc_lv<32> ap_const_lv32_3; static const sc_lv<32> ap_const_lv32_6; static const sc_lv<32> ap_const_lv32_7; static const sc_lv<32> ap_const_lv32_8; static const sc_lv<32> ap_const_lv32_9; static const sc_lv<32> ap_const_lv32_17; static const sc_lv<32> ap_const_lv32_25; static const sc_lv<32> ap_const_lv32_33; static const sc_lv<32> ap_const_lv32_45; static const sc_lv<32> ap_const_lv32_47; static const sc_lv<32> ap_const_lv32_4A; static const sc_lv<32> ap_const_lv32_4B; static const sc_lv<1> ap_const_lv1_1; static const sc_lv<32> ap_const_lv32_4C; static const sc_lv<32> ap_const_lv32_4F; static const sc_lv<32> ap_const_lv32_8A; static const sc_lv<32> ap_const_lv32_8B; static const sc_lv<5> ap_const_lv5_0; static const sc_lv<10> ap_const_lv10_1; static const sc_lv<32> ap_const_lv32_46; static const sc_lv<32> ap_const_lv32_8C; static const sc_lv<32> ap_const_lv32_A; static const sc_lv<32> ap_const_lv32_B; static const sc_lv<32> ap_const_lv32_18; static const sc_lv<32> ap_const_lv32_19; static const sc_lv<32> ap_const_lv32_26; static const sc_lv<32> ap_const_lv32_27; static const sc_lv<32> ap_const_lv32_34; static const sc_lv<32> ap_const_lv32_35; static const sc_lv<32> ap_const_lv32_4D; static const sc_lv<32> ap_const_lv32_4E; static const sc_lv<32> ap_const_lv32_D; static const sc_lv<32> ap_const_lv32_1B; static const sc_lv<32> ap_const_lv32_29; static const sc_lv<32> ap_const_lv32_37; static const sc_lv<64> ap_const_lv64_4014000000000000; static const sc_lv<32> ap_const_lv32_50; static const sc_lv<5> ap_const_lv5_14; static const sc_lv<5> ap_const_lv5_1; static const sc_lv<10> ap_const_lv10_3E7; static const sc_lv<10> ap_const_lv10_3FF; static const sc_lv<20> ap_const_lv20_3E8; static const bool ap_const_boolean_1; // Thread declarations void thread_ap_var_for_const0(); void thread_ap_var_for_const1(); void thread_ap_clk_no_reset_(); void thread_A_address0(); void thread_A_address1(); void thread_A_ce0(); void thread_A_ce1(); void thread_A_d1(); void thread_A_we1(); void thread_B_address0(); void thread_B_ce0(); void thread_B_d0(); void thread_B_we0(); void thread_ap_CS_fsm_state1(); void thread_ap_CS_fsm_state10(); void thread_ap_CS_fsm_state11(); void thread_ap_CS_fsm_state12(); void thread_ap_CS_fsm_state13(); void thread_ap_CS_fsm_state139(); void thread_ap_CS_fsm_state14(); void thread_ap_CS_fsm_state140(); void thread_ap_CS_fsm_state141(); void thread_ap_CS_fsm_state2(); void thread_ap_CS_fsm_state24(); void thread_ap_CS_fsm_state25(); void thread_ap_CS_fsm_state26(); void thread_ap_CS_fsm_state27(); void thread_ap_CS_fsm_state28(); void thread_ap_CS_fsm_state3(); void thread_ap_CS_fsm_state38(); void thread_ap_CS_fsm_state39(); void thread_ap_CS_fsm_state4(); void thread_ap_CS_fsm_state40(); void thread_ap_CS_fsm_state41(); void thread_ap_CS_fsm_state42(); void thread_ap_CS_fsm_state52(); void thread_ap_CS_fsm_state53(); void thread_ap_CS_fsm_state54(); void thread_ap_CS_fsm_state55(); void thread_ap_CS_fsm_state56(); void thread_ap_CS_fsm_state69(); void thread_ap_CS_fsm_state7(); void thread_ap_CS_fsm_state70(); void thread_ap_CS_fsm_state71(); void thread_ap_CS_fsm_state72(); void thread_ap_CS_fsm_state75(); void thread_ap_CS_fsm_state76(); void thread_ap_CS_fsm_state77(); void thread_ap_CS_fsm_state78(); void thread_ap_CS_fsm_state79(); void thread_ap_CS_fsm_state8(); void thread_ap_CS_fsm_state80(); void thread_ap_CS_fsm_state81(); void thread_ap_CS_fsm_state9(); void thread_ap_done(); void thread_ap_idle(); void thread_ap_ready(); void thread_exitcond1_fu_309_p2(); void thread_exitcond2_fu_236_p2(); void thread_exitcond3_fu_208_p2(); void thread_exitcond4_fu_196_p2(); void thread_exitcond_fu_319_p2(); void thread_grp_fu_174_p0(); void thread_grp_fu_174_p1(); void thread_grp_fu_350_p0(); void thread_grp_fu_350_p00(); void thread_grp_fu_350_p1(); void thread_grp_fu_356_p0(); void thread_grp_fu_356_p00(); void thread_grp_fu_356_p1(); void thread_grp_fu_362_p0(); void thread_grp_fu_362_p00(); void thread_grp_fu_362_p1(); void thread_grp_fu_368_p0(); void thread_grp_fu_368_p00(); void thread_grp_fu_368_p1(); void thread_i_2_fu_214_p2(); void thread_i_3_fu_340_p2(); void thread_j_2_fu_275_p2(); void thread_j_3_fu_334_p2(); void thread_t_1_fu_202_p2(); void thread_tmp_12_cast_fu_325_p1(); void thread_tmp_12_fu_262_p2(); void thread_tmp_14_fu_270_p2(); void thread_tmp_15_fu_292_p2(); void thread_tmp_16_fu_329_p2(); void thread_tmp_18_cast_fu_281_p1(); void thread_tmp_19_cast_fu_301_p1(); void thread_tmp_1_cast_fu_289_p1(); void thread_tmp_20_cast_fu_305_p1(); void thread_tmp_21_cast_fu_285_p1(); void thread_tmp_22_cast_fu_297_p1(); void thread_tmp_23_cast_fu_346_p1(); void thread_tmp_3_fu_220_p2(); void thread_tmp_7_cast_fu_248_p1(); void thread_tmp_7_fu_252_p2(); void thread_tmp_8_fu_242_p2(); void thread_tmp_9_cast_fu_267_p1(); void thread_tmp_9_fu_257_p2(); void thread_ap_NS_fsm(); void thread_hdltv_gen(); }; } using namespace ap_rtl; #endif
a4460f33de09586088ffbe034dc5fe13dce7fa52
d86949009ead10e690c8871fd734a4f838d9c3cc
/1.cpp
97d63c7ce7d6d24be282721f9c6728e6b07e39ce
[]
no_license
saurabh300190/Me_wisedv
bbff6ba8bb7f863be0730c9d63ff620b5bb03e9b
92623f7e06c54ffd2052edf580ddea9fa5647111
refs/heads/main
2022-12-19T21:51:13.330576
2020-10-01T16:31:06
2020-10-01T16:31:06
300,342,136
0
0
null
2020-10-01T16:31:07
2020-10-01T16:12:38
C++
UTF-8
C++
false
false
50
cpp
saurabh shah wise anubhav anil jaydeep maru bhai
cf4deb3b11a817eca7036bde900b526f52a5a2fa
936ff533e5a4a130f629fe596a377ab1122121f3
/GRIT/GRIT/include/attribute_assignment/grit_edge_collapse_attribute_assignment.h
ba9c265a3ed461d6537c7750fa911182124f1bb3
[ "MIT" ]
permissive
misztal/GRIT
e9eb7671b215c3995a765581655d6a7c3096471f
6850fec967c9de7c6c501f5067d021ef5288b88e
refs/heads/master
2021-10-08T11:43:53.580211
2018-12-11T21:46:13
2018-12-11T21:46:13
105,385,278
5
1
null
null
null
null
UTF-8
C++
false
false
8,262
h
#ifndef GRIT_EDGE_COLLAPSE_ATTRIBUTE_ASSIGNMENT_H #define GRIT_EDGE_COLLAPSE_ATTRIBUTE_ASSIGNMENT_H #include <grit_interface_attribute_assignment.h> #include <grit_interface_mesh.h> #include <grit_simplex_set.h> #include <attribute_assignment/grit_copy_attribute_assignment.h> #include <utilities/grit_extract_simplices.h> #include <util_barycentric.h> #include <util_log.h> #include <algorithm> #include <map> #include <cassert> namespace grit { namespace details { /** * This is the AttributeAssignment object designed to use with the implementations * of InterfaceEdgeCollapseOperation (see mesh_operations/grit_interface_edge_collapse_operation.h). * This takes care of re-assigning labels and attributes to the target vertex of the edge collapse * operation (i.e. the vertex collapsed onto). * The attributes for new 1- and 2-simplices are copied using the look-up tables. */ template< typename types> class EdgeCollapseAttributeAssignment : public CopyAttributeAssignment<types> { protected: typedef CopyAttributeAssignment<types> base_class; typedef typename types::real_type T; typedef typename types::vector3_type V; typedef typename types::attributes_type AT; typedef typename types::attribute_manager_type AMT; typedef typename types::param_type PT; typedef typename V::value_traits VT; typedef typename AT::name_iterator name_iterator; typedef typename AT::name_vector name_vector; typedef typename base_class::simplex1_lut_type simplex1_lut_type; typedef typename base_class::simplex2_lut_type simplex2_lut_type; typedef typename base_class::label_set label_set; typedef typename base_class::label_iterator label_iterator; public: /** * Input: * @param new_simplices the set of new simplices created by the EdgeCollapseOperation * (see also InterfaceEdgeCollapseOperation::collapse()). * Should contain 1 0-simplex (the vertex which was collapsed onto), * N 1-simplices (newly inserted edges) and N+1 2-simplices (newly * inserted triangles). * @param old_simplices the set of simplices removed by the EdgeCollapseOperation. * Should contain 1 0-simplex (the collapsed vertex), N+3 1-simplices * and N+3 2-simplices (the full star of the collapsed vertex). */ void operator()( SimplexSet const & new_simplices , SimplexSet const & old_simplices , InterfaceMesh const & mesh , PT const & parameters , AT & attributes , simplex1_lut_type const & simplex1_lut , simplex2_lut_type const & simplex2_lut ) const { assert( ( new_simplices.size(0u)==1u && old_simplices.size(0u)==1u ) || !"EdgeCollapseAttributeAssignment() incorrect input"); assert( old_simplices.size(2u)-new_simplices.size(2u) == 2u || !"EdgeCollapseAttributeAssignment() incorrect input"); assert( old_simplices.size(1u)-new_simplices.size(1u) == 3u || !"EdgeCollapseAttributeAssignment() incorrect input"); assert( old_simplices.size(2u)==old_simplices.size(1u) || !"EdgeCollapseAttributeAssignment() incorrect input"); //--- The (previously existing) target vertex, for which we have to //--- update the attributes. Simplex0 const & vn = *(new_simplices.begin0()); //--- The collapsed (removed) vertex. Simplex0 const & vo = *(old_simplices.begin0()); //--- Edge collapse can produce destruction or merging of phases. //--- In such case, we need to remove or add new phases to the //--- target vertex. In case of phase self-collisions, we interpolate //--- vertex attributes between the collapsed and the target vertex. label_set labels_new, labels_rem, labels_int; compute_label_sets( vn, vo, old_simplices, mesh, parameters , labels_new, labels_rem, labels_int); name_vector const & attribute_names = attributes.simplex0_attribute_names(); //--- Here we remove destroyed labels (has to go first, become configuration exist, //--- where labels_new and labels_rem contain the same label). base_class::delete_simplex0_labels( vn, labels_rem, attributes); //--- Here we add new labels and copy the corresponding attribute values from vo { label_iterator it = labels_new.begin(); for( ; it!=labels_new.end(); ++it) { unsigned int const label = *it; name_iterator name_it = attribute_names.begin(); AMT::add_simplex0_label( vn, label, attributes); for( ; name_it!=attribute_names.end(); ++name_it) { std::string const & name = *name_it; T const val = attributes.get_attribute_value( name, vo, label); attributes.set_attribute_value( name, vn, label, val); } } } //--- Here we deal with self-collision (we interpolate between the old and new value). { label_iterator it = labels_int.begin(); for( ; it != labels_int.end(); ++it) { unsigned int const & label = *it; name_iterator name_it = attribute_names.end(); for( ; name_it != attribute_names.end(); ++name_it) { std::string const & name = *name_it; T const valn = attributes.get_attribute_value( name, vn, label); T const valo = attributes.get_attribute_value( name, vo, label); attributes.set_attribute_value( name, vn, label, VT::half()*(valo+valn)); } } } //--- Copy attributes for Simplex1 and Simplex2 objects base_class::copy_simplex1_attributes( new_simplices, attributes, simplex1_lut); base_class::copy_simplex2_attributes( new_simplices, attributes, simplex2_lut); } protected: void compute_label_sets( Simplex0 const & vn , Simplex0 const & vo , SimplexSet const & old_simplices , InterfaceMesh const & mesh , Parameters const & parameters , label_set & labels_new , label_set & labels_rem , label_set & labels_int ) const { //--- old_simplices is the star of vo. SimplexSet const Sn = mesh.star(vn); SimplexSet const X = intersection(Sn,old_simplices); SimplexSet const Dn = difference(Sn,X); SimplexSet const Do = difference(old_simplices,X); label_set const ln = base_class::compute_all_nonambient_labels( Dn, mesh, parameters); label_set const lo = base_class::compute_all_nonambient_labels( Do, mesh, parameters); label_set const lx = base_class::compute_all_nonambient_labels( X , mesh, parameters); std::set_difference( lo.begin(), lo.end(), ln.begin(), ln.end() , std::inserter( labels_new, labels_new.begin())); std::set_difference( lx.begin(), lx.end(), ln.begin(), ln.end() , std::inserter( labels_rem, labels_rem.begin())); std::set_intersection( lo.begin(), lo.end(), ln.begin(), ln.end() , std::inserter( labels_int, labels_int.begin())); } }; } // end namespace details } // end namespace grit // GRIT_EDGE_COLLAPSE_ATTRIBUTE_ASSIGNMENT_H #endif
618d9ccf5aab86dffe5333d3fa56a815b9c22a48
c2684e50a4aa6dc4535dc22cc43838947766691b
/c++/lib/set_operations.h
a8f95087be8396e3789e75d79002d884636e35ce
[]
no_license
jdf3/grepoxy
7b8f0e3aa1f0f22930076b3290092ea70dc81f35
1c4ac6a37c0eaafc3cdece1a94435591cbbd4ef7
refs/heads/master
2020-04-11T01:32:08.822020
2012-06-25T02:30:53
2012-06-25T02:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
#ifndef _SET_OPERATIONS_H #define _SET_OPERATIONS_H #include <vector> #include <stdint.h> using namespace std; typedef vector<bool> vset; /*const int intSize = sizeof(vset) * 8; const vset shifter = 1; const vset empty = 0;*/ void set_insert(int u, vset &S); void set_delete(int u, vset &S); bool in_set(int u, vset &S); /*void set_cut(int u, vset S, int arraySize); vset set_union(vset S, vset R); vset set_intersection(vset S, vset R);*/ bool not_empty(vset &S); #endif
4106752d6b9c1410458bd30fbd1f0623ed2b9dab
ae6abde6e6bf19fb1e8d054c7e081c8c5c22de5b
/polynomial1.cpp
1fe08862ba35fc218311364a9f19568aa6569693
[]
no_license
2ushar-pradhan/DataStructure-Lab-CCE20
7c2b87945e22e1b5e85c76001f932d97deafafdf
5fe0e625c1c4c5f142d9808c74c32f3e5dc2298c
refs/heads/master
2021-07-16T20:15:19.332637
2017-10-26T08:25:43
2017-10-26T08:25:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,999
cpp
#include<iostream> #include<conio.h> using namespace std; class node { int exp; int coe; node *next; public: node *create(node *,int,int); void display(node *); node *add(node *,node *); node *mul(node *,node *); }; node *first1=NULL,*first2=NULL,*first3=NULL,*first4=NULL; node * node::mul(node *f1,node *f2) { node *res=NULL; for(node *i=f1;i!=NULL;i=i->next) for(node *j=f2;j!=NULL;j=j->next) res=create(res,i->coe*j->coe,i->exp+j->exp); return(res); } node * node::create(node *f,int c,int e) { node *temp; temp=new node; temp->coe=c; temp->exp=e; temp->next=NULL; if(f==NULL) f=temp; else { node *curr; for(curr=f;curr->next!=NULL;curr=curr->next); curr->next=temp; } return(f); } void node::display(node *f) { for(node *curr=f;curr!=NULL;curr=curr->next) { cout<<curr->coe<<"^"<<curr->exp; if(curr->next!=NULL) cout<<"+"; } cout<<"\n"; } node* node::add(node *f1,node *f2) { node *res=NULL; node *a=f1,*b=f2; while((a!=NULL)&&(b!=NULL)) { if (a->exp>b->exp) { res=create(res,a->coe,a->exp); a=a->next; } else if(a->exp==b->exp) { res=create(res,a->coe+b->coe,a->exp); a=a->next; b=b->next; } else //b->exp<a->exp { res=create(res,b->coe,b->exp); b=b->next; } } while(a!=NULL) { res=create(res,a->coe,a->exp); a=a->next; } while(b!=NULL) { res=create(res,b->coe,b->exp); b=b->next; } return(res); } int main() { int n,i,e,c; node a; cout<<"how many terms in 1 polynomial\n"; cin>>n; for(i=0;i<n;i++) { cout<<"\nEnter coe: "; cin>>c; cout<<"Enter exp: "; cin>>e; first1=a.create(first1,c,e); } a.display(first1); cout<<"how many terms in 2 polynomial\n"; cin>>n; for(i=0;i<n;i++) { cout<<"\nEnter coe: "; cin>>c; cout<<"Enter exp: "; cin>>e; first2=a.create(first2,c,e); } a.display(first2); first3=a.add(first1,first2); first4=a.mul(first1,first2); cout<<"Result of addition: "; a.display(first3); cout<<endl; cout<<"Result of multiplication: "; a.display(first4); cout<<endl; }
509e637f2c06442ed94cd8503b7fad6feae2156d
1dd825971ed4ec0193445dc9ed72d10618715106
/examples/extended/eventgenerator/HepMC/MCTruth/src/MCTruthTrackingAction.cc
164cd44f707ffb6e7120926770ced0c21a667aef
[]
no_license
gfh16/Geant4
4d442e5946eefc855436f4df444c245af7d3aa81
d4cc6c37106ff519a77df16f8574b2fe4ad9d607
refs/heads/master
2021-06-25T22:32:21.104339
2020-11-02T13:12:01
2020-11-02T13:12:01
158,790,658
0
0
null
null
null
null
UTF-8
C++
false
false
5,190
cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file eventgenerator/HepMC/MCTruth/src/MCTruthTrackingAction.cc /// \brief Implementation of the MCTruthTrackingAction class // // // $Id$ // // // -------------------------------------------------------------- // GEANT 4 - MCTruthTrackingAction class // -------------------------------------------------------------- // // Author: Witold POKORSKI ([email protected]) // // -------------------------------------------------------------- // //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... #include <iostream> #include "G4Track.hh" #include "G4TrackVector.hh" #include "G4TrackingManager.hh" #include "MCTruthTrackingAction.hh" #include "MCTruthTrackInformation.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... MCTruthTrackingAction::MCTruthTrackingAction() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... MCTruthTrackingAction::~MCTruthTrackingAction() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... void MCTruthTrackingAction::PreUserTrackingAction(const G4Track* track) { fmom = G4LorentzVector(track->GetMomentum(), track->GetTotalEnergy()); if(!track->GetUserInformation()) { G4VUserTrackInformation* mcinf = new MCTruthTrackInformation; fpTrackingManager->SetUserTrackInformation(mcinf); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... void MCTruthTrackingAction::PostUserTrackingAction(const G4Track* track) { G4LorentzVector prodpos(track->GetGlobalTime() - track->GetLocalTime(), track->GetVertexPosition()); G4LorentzVector endpos(track->GetGlobalTime(), track->GetPosition()); // here (?) make all different checks to decide whether to store the particle // if (TrackToBeStored(track)) { MCTruthTrackInformation* mcinf = (MCTruthTrackInformation*) track->GetUserInformation(); MCTruthManager::GetInstance()-> AddParticle(fmom, prodpos, endpos, track->GetDefinition()->GetPDGEncoding(), track->GetTrackID(), track->GetParentID(), mcinf->GetDirectParent()); } else { // If track is not to be stored, propagate it's parent ID (stored) // to its secondaries // G4TrackVector* childrens = fpTrackingManager->GimmeSecondaries() ; for( unsigned int index = 0 ; index < childrens->size() ; ++index ) { G4Track* tr = (*childrens)[index] ; tr->SetParentID( track->GetParentID() ); // set the flag saying that the direct mother is not stored // MCTruthTrackInformation* mcinf = (MCTruthTrackInformation*) tr->GetUserInformation(); if(!mcinf) tr->SetUserInformation(mcinf = new MCTruthTrackInformation); mcinf->SetDirectParent(false); } } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo..... G4bool MCTruthTrackingAction::TrackToBeStored(const G4Track* track) { MCTruthConfig* config = MCTruthManager::GetInstance()->GetConfig(); // check energy if (fmom.e() > config->GetMinE()) return true; // particle type std::vector<G4int> types = config->GetParticleTypes(); if(std::find( types.begin(), types.end(), track->GetDefinition()->GetPDGEncoding()) != types.end()) return true; // creator process // etc... return false; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.....
dcc370df47b751e5c41ea7d90e681161eae320a7
133d0f38b3da2c51bf52bcdfa11d62978b94d031
/testAutocad/vendor/objectArx/inc/rxprotevnt.h
f292e221874ec0f3e24fe758d4d6fd53bb33b75d
[]
no_license
Aligon42/ImportIFC
850404f1e1addf848e976b0351d9e217a72f868a
594001fc0942d356eb0d0472c959195151510493
refs/heads/master
2023-08-15T08:00:14.056542
2021-07-05T13:49:28
2021-07-05T13:49:28
361,410,709
0
1
null
null
null
null
UTF-8
C++
false
false
12,208
h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // // rxprotevnt.h // // AcRxObject // AcRxProtocolReactor // AcRxProtocolReactorIterator // AcRxProtocolReactorList // AcRxProtocolReactorListIterator // AcRxProtocolReactorManager // AcRxProtocolReactorManagerFactory // // DESCRIPTION: // // The classes in this file comprise a framework for attaching reactor-like // objects to AcRx classes via the AcRx protoocol extension mechanism. Unlike // normal protocol extensions, there may be more than one object implementing // an event interface for a given event class on a single AcRx object. // // The classes in this file allow define the base reactor class which is a simple // base class for run time type identification. // // Applications derive from specific reactor classes and attach an instance of // their objects implementing the reactor to a specific AcRx class via the // AcRxprotocolReactorManager. // // The AcRxProtocolReactor framework manages the reactors as follows: // // AcRxClass // -> AcRxProtocolReactorManager (at most 1 per AcRx class) // -> AcRxProtocolReactorList (any number, // indexed by AcRxProtocolReactor class) // -> AcRxProtocolReactor (any number) // // Note that the framework does not manage the allocation/deallocation of the // reactors themselves. Applications must allocate reactors, add them a // reactor list associated with one (or more) classes. Before unloading // applications should remove the reactors from the reactor lists and free the // associated memory. Applications typically do the allocation when loaded and // deallocation when unloaded but the actual timing is left up to the // applications. #pragma once #include "rxdefs.h" #include "acadstrc.h" #pragma pack (push, 8) class AcRxProtocolReactor; class AcRxProtocolReactorIterator; class AcRxProtocolReactorList; class AcRxProtocolReactorListIterator; class AcRxProtocolReactorManager; class AcRxProtocolReactorManagerFactory; ////////////////////// AcRxProtocolReactor class ////////////////////////////// // /// <summary> /// The base class for all protocol reactors. All protocol reactor classes /// must derive from this class. /// </summary> class ADESK_NO_VTABLE AcRxProtocolReactor : public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactor); }; ////////////////////// AcRxProtocolReactorIterator class ////////////////////// // /// <summary> /// An iterator for enumerating AcRxProtocolReactors in an /// AcRxProtocolReactorList. /// </summary> /// /// <remarks> /// Instances of this class are returned by /// <c>AcRxProtocolReactorList::newIterator()</c>. /// </remarks> /// class ADESK_NO_VTABLE AcRxProtocolReactorIterator : public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactorIterator); // The AcRxClass of the AcRxProtocolReactors returned by the // iterator. /// <summary> /// Returns the AcRxClass type returned by the iterator. /// </summary> /// /// <returns> /// A pointer to the AcRxClass type. /// </returns> /// virtual AcRxClass* reactorClass () const = 0; /// <summary> /// Rewinds the iterator to the beginning of the list. /// </summary> /// virtual void start() = 0; /// <summary> /// Advances the iterator to the next item in the list. /// </summary> /// /// <returns> /// True if there are more items in the list, false if the iterator has /// reached the end of the list. /// </returns> /// virtual bool next () = 0; /// <summary> /// Determines whether the iterator has reached the end of the list. /// </summary> /// /// <returns> /// True if there are more items in the list, false if the iterator has /// reached the end of the list. /// </returns> /// virtual bool done () const = 0; /// <summary> /// Returns the AcRxProtocolReactor at the current iterator position. /// </summary> /// /// <returns> /// Returns a pointer to the AcRxProtocolReactor at the current iterator /// position. /// </returns> /// virtual AcRxProtocolReactor* object () const = 0; }; ////////////////////// AcRxProtocolReactorList class ////////////////////////// // /// <summary> /// A simple collection of AcRxProtocolReactors. /// </summary> /// /// <remarks> /// Instances of this class contain a single kind of AcRxProtocolReactor. /// Collections of this class are associated with an AcRxClass through the /// protocol reactor framework and the AcRxProtocolReactorManager class. /// </remarks> /// class ADESK_NO_VTABLE AcRxProtocolReactorList : public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactorList); /// <summary> /// Returns the AcRxClass type returned by the iterator. /// </summary> /// /// <returns> /// A pointer to the AcRxClass type. /// </returns> virtual AcRxClass* reactorClass() const = 0; /// <summary> /// Adds a reactor to the collection. /// </summary> /// /// <param name="pReactor"> /// A pointer to the reactor to add to the collection. /// </param> /// /// <returns> /// Returns Acad::eOk if successful. Returns Acad::eWrongObjectType if /// <paramref name="pReactor"/> is not a kind of <c>reactorClass()</c>. /// </returns> /// virtual Acad::ErrorStatus addReactor (AcRxProtocolReactor* pReactor) = 0; /// <summary> /// Removes a reactor from the collection. /// </summary> /// /// <param name="pReactor"> /// A pointer to the reactor to remove from the collection. /// </param> /// virtual void removeReactor(AcRxProtocolReactor* pReactor) = 0; /// <summary> /// Obtains an iterator on the contents of the list. /// </summary> /// /// <returns> /// A pointer to an AcRxProtocolReactorIterator that can be used to /// enumerate the contents of the list. /// </returns> /// /// <remarks> /// Callers are responsible for deleting the returned iterator. /// </remarks> /// virtual AcRxProtocolReactorIterator* newIterator () const = 0; }; ////////////////////// AcRxProtocolReactorListIterator class ////////////////// // /// <summary> /// An iterator for enumerating AcRxProtocolReactorLists in an /// AcRxProtocolReactorManager. /// </summary> /// /// <remarks> /// Instances of this class are returned by /// <c>AcRxProtocolReactorManager::newIterator()</c>. /// </remarks> /// class ADESK_NO_VTABLE AcRxProtocolReactorListIterator : public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactorListIterator); /// <summary> /// Rewinds the iterator to the beginning of the list. /// </summary> /// virtual void start() = 0; /// <summary> /// Advances the iterator to the next item in the list. /// </summary> /// /// <returns> /// True if there are more items in the list, false if the iterator has /// reached the end of the list. /// </returns> /// virtual bool next () = 0; /// <summary> /// Determines whether the iterator has reached the end of the list. /// </summary> /// /// <returns> /// True if there are more items in the list, false if the iterator has /// reached the end of the list. /// </returns> /// virtual bool done () const = 0; /// <summary> /// Returns the AcRxProtocolReactorList at the current iterator position. /// </summary> /// /// <returns> /// Returns a pointer to the AcRxProtocolReactorList at the current /// iterator position. /// </returns> /// virtual AcRxProtocolReactorList* object () const = 0; }; ////////////////////// AcRxProtocolReactorManager class /////////////////////// // /// <summary> /// Container class for a collection of AcRxProtocolReactorLists. /// </summary> /// /// <remarks> /// Instances of AcRxProtocolReactorManagers are associated to AcRxClasses at /// runtime using the protocol extension framework. Instances of this class /// allow multiple kinds of AcRxProtocolReactors to be associated with a single /// AcRxClass. /// </remarks> /// class ADESK_NO_VTABLE AcRxProtocolReactorManager: public AcRxObject { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactorManager); /// <summary> /// Returns an AcRxProtocolReactorList for a specific reactor class. /// </summary> /// /// <param name="pReactorClass"> /// A pointer to the AcRxClass of the reactor managed by the returned list. /// </param> /// /// <returns> /// A pointer to the AcRxProtocolReactorList. /// </returns> /// /// <remarks> /// If a list for the reactor class does not exist a new one is created and /// returned. /// </remarks> /// virtual AcRxProtocolReactorList* createReactorList ( AcRxClass* pReactorClass) = 0; /// <summary> /// Returns an iterator for all of the AcRxProtocolReactorLists instances /// contained in the manager. /// </summary> /// /// <returns> /// A pointer to a new AcRxProtocolReactorListIterator that can be used to /// enumerate the AcRxProtocolReactorList instances contained in the /// manager. /// </returns> /// /// <remarks> /// Callers are responsible for deleting the returned iterator. /// </remarks> /// virtual AcRxProtocolReactorListIterator* newIterator () const = 0; }; ////////////////////// AcRxProtocolReactorManagerFactory class //////////////// // /// <summary> /// A factory class for obtaining the single AcRxProtocolReactorManager /// associated /// </summary> /// class ADESK_NO_VTABLE AcRxProtocolReactorManagerFactory : public AcRxService { public: ACRX_DECLARE_MEMBERS(AcRxProtocolReactorManagerFactory); /// <summary> /// Returns the reactor manager for the specified AcRxClass. /// </summary> /// /// <param name="pRxClass"> /// A pointer to the AcRxClass with the associated /// AcRxProtocolReactorManager. /// </param> /// /// <returns> /// A pointer to the AcRxProtocolReactorManager associated with <paramref /// name="pRxClass"/>. /// </returns> /// /// <remarks> /// If an AcRxProtocolReactorManager is not associated with the specified /// class a new one is created and returned to the caller. /// </remarks> /// virtual AcRxProtocolReactorManager* createReactorManager ( AcRxClass* pRxClass) const = 0; }; /////////////////////// Macros //////////////////////////////////////////////// // The following macros facilitate access to framework classes. // acrxProtocolReactors macro // Returns a poitner to the global AcRxProtocolReactorManagerFactory instance. // #define acrxProtocolReactors \ AcRxProtocolReactorManagerFactory::cast(acrxServiceDictionary-> \ at(ACRX_PROTOCOL_REACTOR_MANAGER)) // ACRX_PROTOCOL_REACTOR_MANAGER_AT(acrxClass) // Returns a pointer to the AcRxProtocolReactorManager associated with the // specified acrxClass. // #define ACRX_PROTOCOL_REACTOR_MANAGER_AT(acrxClass) \ acrxProtocolReactors->createReactorManager(acrxClass) // ACRX_PROTOCOL_REACTOR_LIST(acrxClass, reactorClass) // Returns a pointer to the AcRxProtocolReactorList associated with the // specified acrxClass and containing zero or more reactorClass instances. // #define ACRX_PROTOCOL_REACTOR_LIST_AT(acrxClass, reactorClass) \ ACRX_PROTOCOL_REACTOR_MANAGER_AT(acrxClass)->createReactorList(reactorClass) #pragma pack (pop)
64bd616bd70ecb2c2011451063a2c8da85b629d2
1c45cae789f3e51ddba4a3fc75151743ec4884be
/PickingNubmers.cpp
98e0ce66f1f658da0aecdc4486e98b4ae917e7bb
[]
no_license
MMajd/HackerRank
3d339a4eb6a77bfdb217b8029197f3f7b0bb20ba
be968d1ea98f52c8259225c34af40108dcb27c61
refs/heads/master
2021-03-30T23:49:56.392209
2018-03-28T08:50:27
2018-03-28T08:50:27
124,752,584
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
/* EXPL: https://dev.to/ryhenness/lets-solve-code-challenge---picking-numbers-a32 */ #include <bits/stdc++.h> int main() { int n, *arr, *map, i, max; cin >> n; arr = (int *) malloc(sizeof(int) * n); map = (int *) malloc(sizeof(int) * n); for(i=0; i<n; i++) { cin >> arr[i]; map[arr[i]]++; } max = 0; for(i=0; i<(n-1); i++) { int t = map[i] + map[i + 1]; if(t > max) max = t; } cout << max << endl; return 0; }
[ "Muhammad@git" ]
Muhammad@git
ac4f5457a7e0114a078981a812a42589096fdd74
4141c8e6ccf34f8b57503427433feb0c7463ec56
/include/Jabc.hpp
76b925a36f289eca77febf47c2dca18209e8c25b
[ "MIT" ]
permissive
ikim-quantum/Jabc
97366d70cb2052b4dbe3075048930b1f82bce9c1
e98278ecb5daa7f239daadf573a2de36997aa644
refs/heads/main
2023-04-09T16:39:44.428483
2021-04-18T10:17:02
2021-04-18T10:17:02
356,084,552
0
0
null
null
null
null
UTF-8
C++
false
false
397
hpp
#ifndef Jabc_HPP_ #define Jabc_HPP_ #include <armadillo> using namespace arma; void transform_xlogx_mat(cx_mat &X); void transform_xlogx_vec(vec &s); int log2_int(int n); void apply_modular_op(int k, int n, cx_mat &psi); void transform_ab(int a, int b, int c, cx_mat &psi); void transform_bc(int a, int b, int c, cx_mat &psi); double Jabc(int a, int b, int c, cx_mat &psi); #endif // Jabc_HPP_
62de3f936f171c875529fecc51c1a52b799ddfb1
2f79c6b1991ef2a7e74f8f0cd6f8fd5bca40ad15
/src/impl/function-impl.h
5c15e2ef80b68bad2a8172f9d9f1380ea4841fb4
[ "Apache-2.0" ]
permissive
Vermeille/slip
6c51281d3b53a7cbbce7f393e626cc2734e16d65
9f44bd7cfafcbcd96cb7c3f5298d89e7837cb57b
refs/heads/master
2020-12-24T06:12:50.189267
2016-12-13T02:29:27
2016-12-13T02:29:27
73,168,252
1
0
null
null
null
null
UTF-8
C++
false
false
443
h
#pragma once #include "function.h" #include "context.h" #include "eval.h" #include "polymorphic.h" namespace slip { template <class F> NormalFunc<F>::NormalFunc(std::string name, F&& f) : Function(name, ManglerCaller<std::decay_t<F>>::Mangle()), fun_(std::move(f)) {} template <class F> NormalFunc<F>::NormalFunc(std::string name, std::string type, F&& f) : Function(name, type), fun_(std::move(f)) {} } // namespace slip
18c6b1ecbadbc99baf7866b467ed19227f0db389
d4f8837df785a6766fb9423b3986d3aebacd4f6f
/insert.cpp
2ce094e3827cd5af6c3816a1287833f84984bfe9
[]
no_license
Jartim00/mysql-with-small-tutorial-for-c-
d5ee236dab695f222c9a0700dc964074ff21942c
00ead161a219b25a6304bc9ce76a54cbbda4ee14
refs/heads/master
2020-12-24T07:20:08.682451
2016-06-02T18:44:07
2016-06-02T18:44:07
60,286,594
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
#include <mysql.h> #include <cstdio> #include <iostream> using namespace std; int main() { char link[150]; MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = "Your MySQL password"; char *database = "Your DATABASE"; conn = mysql_init(NULL); mysql_real_connect(conn, server, user, password, database, 0, NULL, 0); string newLink, query; cout << "Enter a link to add to the database: "; getline(cin, newLink); query = "INSERT INTO links VALUES('" + newLink + "')"; cout << query; mysql_query(conn, query.c_str());//queryText.c_str() res = mysql_use_result(conn); //printf("link\t\n"); while ((row = mysql_fetch_row(res)) != NULL) { printf("%s \t\n", row[0]); } cout << "Success!"; mysql_free_result(res); mysql_close(conn); return 0; }
116066f5bc7c249847744bdc9d10daf67286bda4
7012fa0f949bdb631ae35c39b3011307c1222c44
/common/SDAT.h
2a5222e7cfccd857089e17d96cf3ea5f84880569
[]
no_license
soneek/SDATStuff
e3999d14e2cce0d1a08a9027e543b8c6fa91477b
c256196d441b4db62351eaf5772cf280086d1033
refs/heads/master
2021-01-17T07:13:34.106296
2014-06-09T09:33:01
2014-06-09T09:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
h
/* * SDAT - SDAT structure * By Naram Qashat (CyberBotX) [[email protected]] * Last modification on 2013-03-30 * * Nintendo DS Nitro Composer (SDAT) Specification document found at * http://www.feshrine.net/hacking/doc/nds-sdat.html */ #ifndef SDAT_SDAT_H #define SDAT_SDAT_H #include "NDSStdHeader.h" #include "SYMBSection.h" #include "INFOSection.h" #include "FATSection.h" #include "SSEQ.h" #include "SBNK.h" #include "SWAR.h" #include "common.h" struct SDAT { static bool failOnMissingFiles; std::string filename; NDSStdHeader header; uint32_t SYMBOffset; uint32_t SYMBSize; uint32_t INFOOffset; uint32_t INFOSize; uint32_t FATOffset; uint32_t FATSize; uint32_t FILEOffset; uint32_t FILESize; SYMBSection symbSection; INFOSection infoSection; FATSection fatSection; bool symbSectionNeedsCleanup; uint16_t count; std::vector<std::unique_ptr<SSEQ>> SSEQs; std::vector<std::unique_ptr<SBNK>> SBNKs; std::vector<std::unique_ptr<SWAR>> SWARs; SDAT(); SDAT(const SDAT &sdat); SDAT &operator=(const SDAT &sdat); void Read(const std::string &fn, PseudoReadFile &file, bool shouldFailOnMissingFiles = true); void Write(PseudoWrite &file) const; SDAT &operator+=(const SDAT &other); void Strip(const IncOrExc &includesAndExcludes, bool verbose, bool removeExcluded = true); }; #endif
d1bc902a7c6a6ac48a6253cc9d5c74cf41fbbd53
e18edd605c300608963344043dd1c521a775b355
/Leetcode/682. 棒球比赛.cpp
4ec6a3217191ee691603fe60f3ed80fe7c8055a4
[]
no_license
SongKAY/code
bb7fa5f8b9df184581b520fc8deb19134bf2af25
14a92ff912393a8b4377173d33210a40d6c57749
refs/heads/master
2020-04-27T20:07:19.516768
2019-09-24T03:50:44
2019-09-24T03:50:44
174,646,281
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
class Solution { public: int calPoints(vector<string>& ops) { int sum = 0; if(ops.empty()) return sum; stack<int> temp; for(auto a:ops){ if(a=="C"||a=="D"||a=="+"){ if(a=="C"){ if(!temp.empty()) temp.pop(); } else if(a=="D"){ int t1 = temp.top(); t1 *= 2; temp.push(t1); } else{ int t1 = temp.top(); temp.pop(); int t2 = temp.top(); temp.pop(); temp.push(t2); temp.push(t1); temp.push(t1+t2); } } else{ temp.push(stoi(a)); } } while(!temp.empty()){ sum += temp.top(); temp.pop(); } return sum; } };
69e8d1e6407aa40acc1805869bd9ae5c3d110fc9
18916d7ee8cfee466ba6cf8f62784d0b9646fef4
/src/protocol.h
42f3d167fe42eea18d7902b1c479bbd422cec722
[ "MIT" ]
permissive
argentumproject/argentum-old
e3cfc667d2d1a0d7bef9d53fb6b3596407daa878
93e0ebd15dc14e71f33ca589ca228a2dacbb78c5
refs/heads/master
2021-06-14T18:07:00.628754
2017-03-21T04:11:40
2017-03-21T04:12:37
66,512,050
2
2
null
null
null
null
UTF-8
C++
false
false
3,704
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Copyright (c) 2011-2013 The Litecoin developers // Copyright (c) 2013-2014 The Argentum developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __cplusplus # error This header can only be compiled as C++. #endif #ifndef __INCLUDED_PROTOCOL_H__ #define __INCLUDED_PROTOCOL_H__ #include "chainparams.h" #include "netbase.h" #include "serialize.h" #include "uint256.h" #include <stdint.h> #include <string> /** Message header. * (4) message start. * (12) command. * (4) size. * (4) checksum. */ class CMessageHeader { public: CMessageHeader(); CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn); std::string GetCommand() const; bool IsValid() const; IMPLEMENT_SERIALIZE ( READWRITE(FLATDATA(pchMessageStart)); READWRITE(FLATDATA(pchCommand)); READWRITE(nMessageSize); READWRITE(nChecksum); ) // TODO: make private (improves encapsulation) public: enum { COMMAND_SIZE=12, MESSAGE_SIZE_SIZE=sizeof(int), CHECKSUM_SIZE=sizeof(int), MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE, CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE, HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE }; char pchMessageStart[MESSAGE_START_SIZE]; char pchCommand[COMMAND_SIZE]; unsigned int nMessageSize; unsigned int nChecksum; }; /** nServices flags */ enum { NODE_NETWORK = (1 << 0), NODE_BLOOM = (1 << 1), NODE_GETUTXO = (1 << 2), // not implemented, added for reference }; /** A CService with information about it as peer */ class CAddress : public CService { public: CAddress(); explicit CAddress(CService ipIn, uint64_t nServicesIn=NODE_NETWORK); void Init(); IMPLEMENT_SERIALIZE ( CAddress* pthis = const_cast<CAddress*>(this); CService* pip = (CService*)pthis; if (fRead) pthis->Init(); if (nType & SER_DISK) READWRITE(nVersion); if ((nType & SER_DISK) || (nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH))) READWRITE(nTime); READWRITE(nServices); READWRITE(*pip); ) void print() const; // TODO: make private (improves encapsulation) public: uint64_t nServices; // disk and network only unsigned int nTime; // memory only int64_t nLastTry; }; /** inv message data */ class CInv { public: CInv(); CInv(int typeIn, const uint256& hashIn); CInv(const std::string& strType, const uint256& hashIn); IMPLEMENT_SERIALIZE ( READWRITE(type); READWRITE(hash); ) friend bool operator<(const CInv& a, const CInv& b); bool IsKnownType() const; const char* GetCommand() const; std::string ToString() const; void print() const; // TODO: make private (improves encapsulation) public: int type; uint256 hash; }; enum { MSG_TX = 1, MSG_BLOCK, // Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however, // MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata. MSG_FILTERED_BLOCK, }; #endif // __INCLUDED_PROTOCOL_H__
499b8cda9c1971295e5c0164eb9e50f2f79729af
704a8690af3f97bc43ac8a49db56ed62cd6c08de
/SDK/DW_InGameMenu_Tiles_parameters.hpp
bc7cf2e78c127b217ccc58c1685ec8e0266004ed
[]
no_license
AeonLucid/SDK-DarwinProject
4d801f0a7ea6c82a7aa466a77fcc1471f5e71942
dd1c97d55e92c2d745bdf1aa36bab0569f2cf76a
refs/heads/master
2021-09-07T14:08:44.996793
2018-02-24T02:25:28
2018-02-24T02:25:28
118,212,468
1
1
null
null
null
null
UTF-8
C++
false
false
375
hpp
#pragma once // Darwin Project (open_beta_2) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "DW_InGameMenu_Tiles_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
fc775f6c6b561991226d42596cd489952fb374c1
816ffdac7463659a5efce01dcc31bbf581d16dfe
/include/Process.hpp
2f84e96551e86c1d51b53937f07fdd0fc2191d43
[ "MIT" ]
permissive
jwinarske/Vkav
5bc09824344c1b79dcf562d74e189158f09d97e1
f3acd4c6d185ddf4cf76ec91548ed84595529b16
refs/heads/master
2023-04-16T19:56:23.141102
2021-04-27T19:51:05
2021-04-27T19:51:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
453
hpp
#pragma once #ifndef SIGNAL_FUNCTIONS_HPP #define SIGNAL_FUNCTIONS_HPP struct AudioData; class Process { public: struct Settings { size_t size; float smoothingLevel; float amplitude; unsigned char channels; }; Process() = default; Process(const Settings& settings); ~Process(); Process& operator=(Process&& other) noexcept; void processSignal(AudioData& audio); private: class ProcessImpl; ProcessImpl* impl = nullptr; }; #endif
76f439ba9bd2d4864335be512d621edba81722e7
d0c6958418f7fd26b336737a9614d922a494d556
/GSHADE_SharedLibrary_Compiler/jni/gshade/util/brick.h
cfb61f905548b7b345d30254167439e2e72e6e19
[]
no_license
j7sz/PBio
ec9f857956018f1d88134614722e8287a8a0d66a
6d60c3f811d2933c7371d0d3b06dfbce5515db95
refs/heads/master
2023-02-17T20:55:40.322994
2021-01-14T14:41:56
2021-01-14T14:41:56
283,781,051
1
0
null
null
null
null
UTF-8
C++
false
false
421
h
#ifndef __brick_h__ #define __brick_h__ #include "typedefs.h" #include "crypto.h" #ifdef OTEXT_USE_GMP typedef class FixedPointExp { public: FixedPointExp(); ~FixedPointExp(); public: void powerMod(mpz_t& result, mpz_t e); void Init(mpz_t g, mpz_t p, int fieldsize); private: mpz_t m_p; mpz_t m_g; bool m_isInitialized; unsigned m_numberOfElements; mpz_t* m_table; } brickexp; #endif #endif
0ee1d5587f7f67c4646f9659c5432d4f9e95709c
d2d6aae454fd2042c39127e65fce4362aba67d97
/build/Android/Preview/app/src/main/include/Uno.Double.h
bff059249693ebf5505bebd65a137258867aee45
[]
no_license
Medbeji/Eventy
de88386ff9826b411b243d7719b22ff5493f18f5
521261bca5b00ba879e14a2992e6980b225c50d4
refs/heads/master
2021-01-23T00:34:16.273411
2017-09-24T21:16:34
2017-09-24T21:16:34
92,812,809
2
0
null
null
null
null
UTF-8
C++
false
false
1,278
h
// This file was generated based on '/Users/medbeji/Library/Application Support/Fusetools/Packages/UnoCore/0.47.13/source/uno/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{ namespace Uno{ // public intrinsic struct Double :1927 // { uStructType* Double_typeof(); void Double__Equals_fn(double* __this, uType* __type, uObject* o, bool* __retval); void Double__GetHashCode_fn(double* __this, uType* __type, int* __retval); void Double__Parse_fn(uString* str, double* __retval); void Double__ToString_fn(double* __this, uType* __type, uString** __retval); void Double__TryParse_fn(uString* str, double* res, bool* __retval); struct Double { static bool Equals(double __this, uType* __type, uObject* o) { bool __retval; return Double__Equals_fn(&__this, __type, o, &__retval), __retval; } static int GetHashCode(double __this, uType* __type) { int __retval; return Double__GetHashCode_fn(&__this, __type, &__retval), __retval; } static uString* ToString(double __this, uType* __type) { uString* __retval; return Double__ToString_fn(&__this, __type, &__retval), __retval; } static double Parse(uString* str); static bool TryParse(uString* str, double* res); }; // } }} // ::g::Uno
43e0cfaa3fbfa93a1f6bb4bf4813ca973b3d4c73
6da6423f2c6bf062f19499a74307cfe68944e28e
/Allegretto/code/main/Application.hpp
17cf4a32117f8f5f7e03340f9a78cb3ce35c8a75
[ "MIT" ]
permissive
jacmoe/allegretto
6ef5d82893acd9fd1bc62a7efbebdd6a463545a4
121c44a5e252a22756cc96e045d8df5b03dbac4e
refs/heads/main
2023-03-10T06:58:49.037082
2021-02-27T23:11:22
2021-02-27T23:11:22
339,422,919
0
0
null
null
null
null
UTF-8
C++
false
false
3,226
hpp
/*# This file is part of the # █████╗ ██╗ ██╗ ███████╗ ██████╗ ██████╗ ███████╗████████╗████████╗ ██████╗ # ██╔══██╗██║ ██║ ██╔════╝██╔════╝ ██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝██╔═══██╗ # ███████║██║ ██║ █████╗ ██║ ███╗██████╔╝█████╗ ██║ ██║ ██║ ██║ # ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║ ██║ # ██║ ██║███████╗███████╗███████╗╚██████╔╝██║ ██║███████╗ ██║ ██║ ╚██████╔╝ # ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ # project # # https://github.com/jacmoe/allegretto # # (c) 2021 Jacob Moena # # MIT License #*/ #pragma once #include <string> #include <vector> #include <memory> #include <allegro5/allegro5.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_ttf.h> #include <spdlog/spdlog.h> #include "utility/ALDeleter.hpp" #include "main/Pixelator.hpp" class Application { public: Application(); virtual ~Application(); bool init(); void run(); protected: virtual bool OnUserCreate() { return true; } virtual bool OnUserUpdate(double deltaTime) { return true; } virtual bool OnUserRender() { return true; } virtual bool OnUserPostRender() { return true; } virtual bool OnUserDestroy() { return true; } virtual bool OnUserInput() { return true; } float m_scale; int m_width; int m_height; bool m_fullscreen; bool m_show_map; bool m_show_fps; double m_average_fps; std::string m_font_name; int m_font_size; int m_font_size_title; std::unique_ptr<ALLEGRO_CONFIG, utility::ALDeleter> m_config; std::unique_ptr<ALLEGRO_TIMER, utility::ALDeleter> m_timer; std::unique_ptr<ALLEGRO_EVENT_QUEUE, utility::ALDeleter> m_queue; std::unique_ptr<ALLEGRO_DISPLAY, utility::ALDeleter> m_display; std::unique_ptr<ALLEGRO_FONT, utility::ALDeleter> m_font; std::unique_ptr<ALLEGRO_FONT, utility::ALDeleter> m_title_font; std::unique_ptr<ALLEGRO_BITMAP, utility::ALDeleter> m_display_buffer; ALLEGRO_LOCKED_REGION* m_screenlock; ALLEGRO_KEYBOARD_STATE m_keyboard_state; ALLEGRO_MOUSE_STATE m_mouse_state; std::shared_ptr<Pixelator> m_pixelator; private: std::string m_title; bool m_running; bool m_should_exit; ALLEGRO_EVENT m_event; void update_display_buffer(); void save_screenshot(); bool process_input(); void render(); };
b4b1ac0794214e3cc624bf55a48c66972e1049cf
d774ba7e4a91df899173f39c5ea03ae521546069
/ColdAPI_Steam/InterfacesEmulation/SteamRemoteStorage007.h
b8c626a7e3c338dfe0342765564b9e8c36b0ec8f
[]
no_license
kettenbruch/ColdAPI_Steam
0a401d1b624c100de3d7197fda9bdf018de6c833
334956ae0508dae50abc4da9413ba96f354a9225
refs/heads/main
2023-03-31T16:19:08.319323
2021-04-04T20:38:19
2021-04-04T20:38:19
354,637,560
1
0
null
null
null
null
UTF-8
C++
false
false
12,886
h
#pragma once #include "../public SDK/ISteamRemoteStorage007.h" #include "../Bridge.h" #include "../ColdManager.h" class SteamRemoteStorageIn007 : public ISteamRemoteStorage007 { public: bool FileWrite(const char* pchFile, const void* pvData, int32 cubData) { if (!Steam_Config::RemoteStorage) return true; if (cubData < NULL) return false; if (pvData <= NULL) return false; PublicSafe.lock(); char* ConnectedDir = (char*)ColdAPI_Storage::ConnectDirectoryToFile(pchFile); // Let's use std as more faster. std::FILE* File = std::fopen(ConnectedDir, "wb"); if (File) { std::fwrite(pvData, cubData, 1, File); std::fclose(File); ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return true; } ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return false; } int32 FileRead(const char* pchFile, void* pvData, int32 cubDataToRead) { if (!Steam_Config::RemoteStorage) return NULL; if (cubDataToRead < NULL) return NULL; if (pvData <= NULL) return NULL; PublicSafe.lock(); char* ConnectedDir = (char*)ColdAPI_Storage::ConnectDirectoryToFile(pchFile); // Let's use std as more faster. std::FILE* File = std::fopen(ConnectedDir, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); // Let's check always if the read size is not bigger than the FileSize. We'll do it with min. int32_t Min = min(cubDataToRead, FileSize); std::fread(pvData, Min, 1, File); std::fclose(File); ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return Min; } ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return NULL; } bool FileForget(const char* pchFile) { if (!Steam_Config::RemoteStorage) return false; return true; } bool FileDelete(const char* pchFile) { if (!Steam_Config::RemoteStorage) return false; PublicSafe.lock(); char* myfile = (char*)ColdAPI_Storage::ConnectDirectoryToFile(pchFile); if (GetFileAttributesA(myfile) == INVALID_FILE_ATTRIBUTES) { ColdAPI_Storage::CloseMem(myfile); PublicSafe.unlock(); return false; } bool Deleted = DeleteFileA(myfile) == TRUE; ColdAPI_Storage::CloseMem(myfile); PublicSafe.unlock(); return Deleted; } SteamAPICall_t FileShare(const char* pchFile) { return NULL; } bool SetSyncPlatforms(const char* pchFile, ERemoteStoragePlatform eRemoteStoragePlatform) { return true; } bool FileExists(const char* pchFile) { PublicSafe.lock(); // Variables bool Exists; char* ConnectedDir = (char*)ColdAPI_Storage::ConnectDirectoryToFile(pchFile); if (!Steam_Config::RemoteStorage) { ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return false; } Exists = GetFileAttributesA(ColdAPI_Storage::ConnectDirectoryToFile(pchFile)) != INVALID_FILE_ATTRIBUTES; ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return Exists; } bool FilePersisted(const char* pchFile) { if (!Steam_Config::RemoteStorage) return false; return true; } int32 GetFileSize(const char* pchFile) { if (!Steam_Config::RemoteStorage) return NULL; PublicSafe.lock(); char* myfile = (char*)ColdAPI_Storage::ConnectDirectoryToFile(pchFile); // Let's use std as more faster. std::FILE* File = std::fopen(myfile, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); std::fclose(File); ColdAPI_Storage::CloseMem(myfile); PublicSafe.unlock(); return FileSize; } ColdAPI_Storage::CloseMem(myfile); PublicSafe.unlock(); return NULL; } int64 GetFileTimestamp(const char* pchFile) { return time(NULL) - 3000; } ERemoteStoragePlatform GetSyncPlatforms(const char* pchFile) { return k_ERemoteStoragePlatformAll; } int32 GetFileCount() { if (!Steam_Config::RemoteStorage) return NULL; PublicSafe.lock(); FilesMatrix.clear(); ColdAPI_Storage::FillFileStructure(ColdAPI_Storage::GetStorageDirectory()); PublicSafe.unlock(); return FilesMatrix.size(); // Return the vector size } const char* GetFileNameAndSize(int iFile, int32* pnFileSizeInBytes) { if (!Steam_Config::RemoteStorage) return ""; PublicSafe.lock(); FilesMatrix.clear(); ColdAPI_Storage::FillFileStructure(ColdAPI_Storage::GetStorageDirectory()); if (iFile <= FilesMatrix.size()) { std::string FileName = FilesMatrix.at(iFile); char* ConnectedDir = (char*)ColdAPI_Storage::ConnectDirectoryToFile(FileName.c_str()); // Let's use std as more faster. std::FILE* File = std::fopen(ConnectedDir, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); std::fclose(File); if (pnFileSizeInBytes != NULL && pnFileSizeInBytes > NULL) *pnFileSizeInBytes = FileSize; ColdAPI_Storage::CloseMem(ConnectedDir); PublicSafe.unlock(); return FileName.c_str(); } ColdAPI_Storage::CloseMem(ConnectedDir); } PublicSafe.unlock(); return ""; } bool GetQuota(int32* pnTotalBytes, int32* puAvailableBytes) { if (pnTotalBytes <= NULL) return false; if (puAvailableBytes <= NULL) return false; *pnTotalBytes = NULL; *puAvailableBytes = INT_MAX; return true; } bool IsCloudEnabledForAccount() { return true; } bool IsCloudEnabledForApp() { return true; } void SetCloudEnabledForApp(bool bEnabled) { return; } SteamAPICall_t UGCDownload(UGCHandle_t hContent) { if (!Steam_Config::RemoteStorage) return NULL; PublicSafe.lock(); FilesMatrix.clear(); ColdAPI_Storage::FillFileStructure(ColdAPI_Storage::GetUGCDirectory()); if (FilesMatrix.size() >= hContent) { // Read the UGC File. std::string FileName = FilesMatrix.at(hContent); char* UGCConnectedDir = (char*)ColdAPI_Storage::ConnectUGCDirectoryToFile(FileName.c_str()); std::FILE* File = std::fopen(UGCConnectedDir, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); std::fclose(File); auto Response = new RemoteStorageDownloadUGCResult_t(); auto RequestID = SteamCallback::RegisterCall(true); Response->m_eResult = k_EResultOK; Response->m_hFile = hContent; Response->m_nAppID = Steam_Config::AppId; Response->m_nSizeInBytes = FileSize; std::memcpy(Response->m_pchFileName, FileName.c_str(), MAX_PATH); Response->m_ulSteamIDOwner = Steam_Config::UserID; SteamCallback::CreateNewRequest(Response, sizeof(*Response), Response->k_iCallback, RequestID); ColdAPI_Storage::CloseMem(UGCConnectedDir); PublicSafe.unlock(); return RequestID; } ColdAPI_Storage::CloseMem(UGCConnectedDir); } PublicSafe.unlock(); return NULL; } bool GetUGCDownloadProgress(UGCHandle_t hContent, uint32* puDownloadedBytes, uint32* puTotalBytes) { if (puDownloadedBytes <= NULL) return false; if (puTotalBytes <= NULL) return false; *puDownloadedBytes = 10; *puTotalBytes = 10; return true; } bool GetUGCDetails(UGCHandle_t hContent, AppId_t* pnAppID, char** ppchName, int32* pnFileSizeInBytes, CSteamID* pSteamIDOwner) { if (!Steam_Config::RemoteStorage) return false; PublicSafe.lock(); FilesMatrix.clear(); ColdAPI_Storage::FillFileStructure(ColdAPI_Storage::GetUGCDirectory()); if (FilesMatrix.size() >= hContent) { // Read the UGC File. std::string FileName = FilesMatrix.at(hContent); char* UGCConnectedDir = (char*)ColdAPI_Storage::ConnectUGCDirectoryToFile(FileName.c_str()); std::FILE* File = std::fopen(UGCConnectedDir, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); std::fclose(File); if (pnAppID != NULL && pnAppID > NULL) *pnAppID = Steam_Config::AppId; if (ppchName != NULL && ppchName > NULL) { *ppchName = (char*)std::malloc(std::strlen(FileName.c_str()) + 10); std::strcpy(*ppchName, FileName.c_str()); } if (pnFileSizeInBytes != NULL && pnFileSizeInBytes > NULL) *pnFileSizeInBytes = FileSize; if (pSteamIDOwner != NULL && pSteamIDOwner > NULL) *pSteamIDOwner = Steam_Config::UserID; ColdAPI_Storage::CloseMem(UGCConnectedDir); PublicSafe.unlock(); return true; } ColdAPI_Storage::CloseMem(UGCConnectedDir); } PublicSafe.unlock(); return false; } int32 UGCRead(UGCHandle_t hContent, void* pvData, int32 cubDataToRead) { if (!Steam_Config::RemoteStorage) return NULL; if (cubDataToRead < NULL) return NULL; if (pvData <= NULL) return NULL; PublicSafe.lock(); FilesMatrix.clear(); ColdAPI_Storage::FillFileStructure(ColdAPI_Storage::GetUGCDirectory()); if (FilesMatrix.size() >= hContent) { // Read the UGC File. std::string FileName = FilesMatrix.at(hContent); char* UGCConnectedDir = (char*)ColdAPI_Storage::ConnectUGCDirectoryToFile(FileName.c_str()); std::FILE* File = std::fopen(UGCConnectedDir, "rb"); if (File) { std::fseek(File, 0, SEEK_END); long FileSize = std::ftell(File); std::fseek(File, 0, SEEK_SET); // Let's check always if the read size is not bigger than the FileSize. We'll do it with min. int32_t Min = min(cubDataToRead, FileSize); std::fread(pvData, Min, 1, File); std::fclose(File); ColdAPI_Storage::CloseMem(UGCConnectedDir); PublicSafe.unlock(); return Min; } ColdAPI_Storage::CloseMem(UGCConnectedDir); } PublicSafe.unlock(); return NULL; } int32 GetCachedUGCCount() { return NULL; } UGCHandle_t GetCachedUGCHandle(int32 iCachedContent) { return NULL; } SteamAPICall_t PublishWorkshopFile(const char* pchFile, const char* pchPreviewFile, AppId_t nConsumerAppId, const char* pchTitle, const char* pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t* pTags, EWorkshopFileType eWorkshopFileType) { return NULL; } JobID_t CreatePublishedFileUpdateRequest(PublishedFileId_t unPublishedFileId) { return NULL; } bool UpdatePublishedFileFile(JobID_t hUpdateRequest, const char* pchFile) { return false; } bool UpdatePublishedFilePreviewFile(JobID_t hUpdateRequest, const char* pchPreviewFile) { return false; } bool UpdatePublishedFileTitle(JobID_t hUpdateRequest, const char* pchTitle) { return false; } bool UpdatePublishedFileDescription(JobID_t hUpdateRequest, const char* pchDescription) { return false; } bool UpdatePublishedFileVisibility(JobID_t hUpdateRequest, ERemoteStoragePublishedFileVisibility eVisibility) { return false; } bool UpdatePublishedFileTags(JobID_t hUpdateRequest, SteamParamStringArray_t* pTags) { return false; } SteamAPICall_t CommitPublishedFileUpdate(JobID_t hUpdateRequest) { return NULL; } SteamAPICall_t GetPublishedFileDetails(PublishedFileId_t unPublishedFileId) { return NULL; } SteamAPICall_t DeletePublishedFile(PublishedFileId_t unPublishedFileId) { return NULL; } SteamAPICall_t EnumerateUserPublishedFiles(uint32 uStartIndex) { return NULL; } SteamAPICall_t SubscribePublishedFile(PublishedFileId_t unPublishedFileId) { return NULL; } SteamAPICall_t EnumerateUserSubscribedFiles(uint32 uStartIndex) { return NULL; } SteamAPICall_t UnsubscribePublishedFile(PublishedFileId_t unPublishedFileId) { return NULL; } bool UpdatePublishedFileSetChangeDescription(JobID_t hUpdateRequest, const char* cszDescription) { return false; } SteamAPICall_t GetPublishedItemVoteDetails(PublishedFileId_t unPublishedFileId) { return NULL; } SteamAPICall_t UpdateUserPublishedItemVote(PublishedFileId_t unPublishedFileId, bool bVoteUp) { return NULL; } SteamAPICall_t GetUserPublishedItemVoteDetails(PublishedFileId_t unPublishedFileId) { return NULL; } SteamAPICall_t EnumerateUserSharedWorkshopFiles(AppId_t nAppId, CSteamID creatorSteamID, uint32 uStartIndex, SteamParamStringArray_t* pRequiredTags, SteamParamStringArray_t* pExcludedTags) { return NULL; } SteamAPICall_t PublishVideo(EWorkshopVideoProvider eVideoProvider, const char* cszVideoAccountName, const char* cszVideoIdentifier, const char* cszFileName, AppId_t nConsumerAppId, const char* cszTitle, const char* cszDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t* pTags) { return NULL; } SteamAPICall_t SetUserPublishedFileAction(PublishedFileId_t unPublishedFileId, EWorkshopFileAction eAction) { return NULL; } SteamAPICall_t EnumeratePublishedFilesByUserAction(EWorkshopFileAction eAction, uint32 uStartIndex) { return NULL; } SteamAPICall_t EnumeratePublishedWorkshopFiles(EWorkshopEnumerationType eType, uint32 uStartIndex, uint32 cDays, uint32 cCount, SteamParamStringArray_t* pTags, SteamParamStringArray_t* pUserTags) { return NULL; } };
dd9b0a9ac2e0fcf91c564ababa3079bea2964833
d4b5ac83977d2586ef72862aaba334de5c8d8579
/natlog/documentation/pcap-demo/readbin.cc
cb65a0d712c632cfa878fb4bf297e82a84662e3f
[]
no_license
fbb-git/natlog
b49563213b93b58e20d61b9a588bcd0c2d10e792
9b11ff39bcb2e6e2b939cb39408823305dd6fc62
refs/heads/master
2021-03-12T20:42:22.507846
2018-06-25T12:56:26
2018-06-25T12:56:26
41,296,617
5
3
null
null
null
null
UTF-8
C++
false
false
3,650
cc
#include "main.ih" #include <limits> // note: tcpdump only reads files when tcpdump is started by the user // owning those files. #include <iomanip> /* typedef int bpf_int32; typedef u_int bpf_u_int32; struct pcap_file_header { bpf_u_int32 magic; u_short version_major; u_short version_minor; bpf_int32 thiszone; // gmt to local correction bpf_u_int32 sigfigs; // accuracy of timestamps bpf_u_int32 snaplen; // max length saved portion of each pkt bpf_u_int32 linktype; // data link type (LINKTYPE_*) }; struct pcap_pkthdr { struct timeval ts; // time stamp bpf_u_int32 caplen; // length of portion present bpf_u_int32 len; // length this packet (off wire) }; */ struct pkthdr { uint32_t seconds; // time stamp uint32_t muSeconds; // time stamp bpf_u_int32 caplen; // length of portion present bpf_u_int32 len; // length this packet (off wire) }; size_t g_count1 = 0; size_t g_count2 = 0; size_t get(istream &in, pkthdr &hdr) { in.read(reinterpret_cast<char *>(&hdr), sizeof(pkthdr)); return in.good() ? static_cast<size_t>(hdr.seconds) : numeric_limits<size_t>::max(); } size_t curLen = 0; char *g_data = 0; size_t process(ostream &out, istream &in, pkthdr &hdr) { out.write(reinterpret_cast<char *>(&hdr), sizeof(pkthdr)); size_t length = hdr.len; // ip header length already in host // byte order. if (length > curLen) { delete[] g_data; g_data = new char[length]; curLen = length; } in.read(g_data, length); out.write(g_data, length); return get(in, hdr); } int main(int argc, char **argv) try { if (argc == 1) { cout << "option: -h: write tcpdump1's global header to the merged file\n" "arguments: tcpdump1 file, tcpdump2 file, merged file\n"; return 0; } bool writeHdr = false; if (argv[1] == "-h"s) { writeHdr = true; ++argv; } ifstream in1(argv[1]); ifstream in2(argv[2]); ofstream out(argv[3]); struct Ethernet_Header // http://en.wikipedia.org/wiki/EtherType { u_char destMac[6]; // Destination host MAC address u_char srcMac[6]; // Source host MAC address u_short ether_type; // IP? ARP? RARP? etc }; if (not writeHdr) in1.ignore(24); // skip the global headers else { g_data = new char[24]; curLen = 24; in1.read(g_data, 24); out.write(g_data, 24); } in2.ignore(24); pkthdr hdr1; pkthdr hdr2; size_t seconds1 = get(in1, hdr1); size_t seconds2 = get(in2, hdr2); while ( seconds1 != numeric_limits<size_t>::max() && seconds1 != numeric_limits<size_t>::max() ) { if (seconds1 < seconds2) { ++g_count1; seconds1 = process(out, in1, hdr1); } else if (seconds1 > seconds2) { ++g_count2; seconds2 = process(out, in2, hdr2); } else { ++g_count1; seconds1 = process(out, in1, hdr1); ++g_count2; seconds2 = process(out, in2, hdr2); } } cout << "Wrote " << g_count1 << " records from the 1st file\n" "wrote " << g_count2 << " records from the 2nd file\n"; } catch (...) { }