hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
221401a6eff107280df2b62b14a5c9d0b852a75a | 7,945 | cc | C++ | Cassie_Example/opt_two_step/periodic/c_code/src/gen/Js_ddh_LeftToeBottom_cassie.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Cassie_Example/opt_two_step/periodic/c_code/src/gen/Js_ddh_LeftToeBottom_cassie.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Cassie_Example/opt_two_step/periodic/c_code/src/gen/Js_ddh_LeftToeBottom_cassie.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | /*
* Automatically Generated from Mathematica.
* Fri 5 Nov 2021 09:03:12 GMT-04:00
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "frost/gen/Js_ddh_LeftToeBottom_cassie.hh"
#ifdef _MSC_VER
#define INLINE __forceinline /* use __forceinline (VC++ specific) */
#else
#define INLINE inline /* use standard inline */
#endif
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
INLINE double Power(double x, double y) { return pow(x, y); }
INLINE double Sqrt(double x) { return sqrt(x); }
INLINE double Abs(double x) { return fabs(x); }
INLINE double Exp(double x) { return exp(x); }
INLINE double Log(double x) { return log(x); }
INLINE double Sin(double x) { return sin(x); }
INLINE double Cos(double x) { return cos(x); }
INLINE double Tan(double x) { return tan(x); }
INLINE double ArcSin(double x) { return asin(x); }
INLINE double ArcCos(double x) { return acos(x); }
//INLINE double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
INLINE double ArcTan(double x, double y) { return atan2(y,x); }
INLINE double Sinh(double x) { return sinh(x); }
INLINE double Cosh(double x) { return cosh(x); }
INLINE double Tanh(double x) { return tanh(x); }
#define E 2.71828182845904523536029
#define Pi 3.14159265358979323846264
#define Degree 0.01745329251994329576924
INLINE double Sec(double x) { return 1/cos(x); }
INLINE double Csc(double x) { return 1/sin(x); }
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double _NotUsed;
NULL;
p_output1[0]=1;
p_output1[1]=1;
p_output1[2]=1;
p_output1[3]=1;
p_output1[4]=1;
p_output1[5]=1;
p_output1[6]=1;
p_output1[7]=1;
p_output1[8]=1;
p_output1[9]=1;
p_output1[10]=1;
p_output1[11]=1;
p_output1[12]=1;
p_output1[13]=1;
p_output1[14]=1;
p_output1[15]=1;
p_output1[16]=1;
p_output1[17]=1;
p_output1[18]=1;
p_output1[19]=1;
p_output1[20]=1;
p_output1[21]=1;
p_output1[22]=1;
p_output1[23]=1;
p_output1[24]=1;
p_output1[25]=1;
p_output1[26]=1;
p_output1[27]=1;
p_output1[28]=1;
p_output1[29]=1;
p_output1[30]=1;
p_output1[31]=1;
p_output1[32]=1;
p_output1[33]=1;
p_output1[34]=2;
p_output1[35]=2;
p_output1[36]=2;
p_output1[37]=2;
p_output1[38]=2;
p_output1[39]=2;
p_output1[40]=2;
p_output1[41]=2;
p_output1[42]=2;
p_output1[43]=2;
p_output1[44]=2;
p_output1[45]=2;
p_output1[46]=2;
p_output1[47]=2;
p_output1[48]=2;
p_output1[49]=2;
p_output1[50]=2;
p_output1[51]=2;
p_output1[52]=2;
p_output1[53]=2;
p_output1[54]=2;
p_output1[55]=2;
p_output1[56]=2;
p_output1[57]=2;
p_output1[58]=2;
p_output1[59]=2;
p_output1[60]=2;
p_output1[61]=2;
p_output1[62]=2;
p_output1[63]=2;
p_output1[64]=2;
p_output1[65]=2;
p_output1[66]=2;
p_output1[67]=2;
p_output1[68]=3;
p_output1[69]=3;
p_output1[70]=3;
p_output1[71]=3;
p_output1[72]=3;
p_output1[73]=3;
p_output1[74]=3;
p_output1[75]=3;
p_output1[76]=3;
p_output1[77]=3;
p_output1[78]=3;
p_output1[79]=3;
p_output1[80]=3;
p_output1[81]=3;
p_output1[82]=3;
p_output1[83]=3;
p_output1[84]=3;
p_output1[85]=3;
p_output1[86]=3;
p_output1[87]=3;
p_output1[88]=3;
p_output1[89]=3;
p_output1[90]=3;
p_output1[91]=3;
p_output1[92]=3;
p_output1[93]=3;
p_output1[94]=3;
p_output1[95]=3;
p_output1[96]=3;
p_output1[97]=3;
p_output1[98]=3;
p_output1[99]=4;
p_output1[100]=4;
p_output1[101]=4;
p_output1[102]=4;
p_output1[103]=4;
p_output1[104]=4;
p_output1[105]=4;
p_output1[106]=4;
p_output1[107]=4;
p_output1[108]=4;
p_output1[109]=4;
p_output1[110]=4;
p_output1[111]=4;
p_output1[112]=4;
p_output1[113]=4;
p_output1[114]=4;
p_output1[115]=4;
p_output1[116]=4;
p_output1[117]=4;
p_output1[118]=4;
p_output1[119]=4;
p_output1[120]=4;
p_output1[121]=4;
p_output1[122]=4;
p_output1[123]=4;
p_output1[124]=4;
p_output1[125]=4;
p_output1[126]=4;
p_output1[127]=4;
p_output1[128]=5;
p_output1[129]=5;
p_output1[130]=5;
p_output1[131]=5;
p_output1[132]=5;
p_output1[133]=5;
p_output1[134]=5;
p_output1[135]=5;
p_output1[136]=5;
p_output1[137]=5;
p_output1[138]=5;
p_output1[139]=5;
p_output1[140]=5;
p_output1[141]=5;
p_output1[142]=5;
p_output1[143]=5;
p_output1[144]=5;
p_output1[145]=5;
p_output1[146]=5;
p_output1[147]=5;
p_output1[148]=5;
p_output1[149]=5;
p_output1[150]=5;
p_output1[151]=5;
p_output1[152]=5;
p_output1[153]=5;
p_output1[154]=1;
p_output1[155]=4;
p_output1[156]=5;
p_output1[157]=6;
p_output1[158]=7;
p_output1[159]=8;
p_output1[160]=9;
p_output1[161]=10;
p_output1[162]=11;
p_output1[163]=12;
p_output1[164]=13;
p_output1[165]=21;
p_output1[166]=24;
p_output1[167]=25;
p_output1[168]=26;
p_output1[169]=27;
p_output1[170]=28;
p_output1[171]=29;
p_output1[172]=30;
p_output1[173]=31;
p_output1[174]=32;
p_output1[175]=33;
p_output1[176]=41;
p_output1[177]=44;
p_output1[178]=45;
p_output1[179]=46;
p_output1[180]=47;
p_output1[181]=48;
p_output1[182]=49;
p_output1[183]=50;
p_output1[184]=51;
p_output1[185]=52;
p_output1[186]=53;
p_output1[187]=61;
p_output1[188]=2;
p_output1[189]=4;
p_output1[190]=5;
p_output1[191]=6;
p_output1[192]=7;
p_output1[193]=8;
p_output1[194]=9;
p_output1[195]=10;
p_output1[196]=11;
p_output1[197]=12;
p_output1[198]=13;
p_output1[199]=22;
p_output1[200]=24;
p_output1[201]=25;
p_output1[202]=26;
p_output1[203]=27;
p_output1[204]=28;
p_output1[205]=29;
p_output1[206]=30;
p_output1[207]=31;
p_output1[208]=32;
p_output1[209]=33;
p_output1[210]=42;
p_output1[211]=44;
p_output1[212]=45;
p_output1[213]=46;
p_output1[214]=47;
p_output1[215]=48;
p_output1[216]=49;
p_output1[217]=50;
p_output1[218]=51;
p_output1[219]=52;
p_output1[220]=53;
p_output1[221]=62;
p_output1[222]=3;
p_output1[223]=5;
p_output1[224]=6;
p_output1[225]=7;
p_output1[226]=8;
p_output1[227]=9;
p_output1[228]=10;
p_output1[229]=11;
p_output1[230]=12;
p_output1[231]=13;
p_output1[232]=23;
p_output1[233]=25;
p_output1[234]=26;
p_output1[235]=27;
p_output1[236]=28;
p_output1[237]=29;
p_output1[238]=30;
p_output1[239]=31;
p_output1[240]=32;
p_output1[241]=33;
p_output1[242]=43;
p_output1[243]=45;
p_output1[244]=46;
p_output1[245]=47;
p_output1[246]=48;
p_output1[247]=49;
p_output1[248]=50;
p_output1[249]=51;
p_output1[250]=52;
p_output1[251]=53;
p_output1[252]=63;
p_output1[253]=5;
p_output1[254]=6;
p_output1[255]=7;
p_output1[256]=8;
p_output1[257]=9;
p_output1[258]=10;
p_output1[259]=11;
p_output1[260]=12;
p_output1[261]=13;
p_output1[262]=24;
p_output1[263]=25;
p_output1[264]=26;
p_output1[265]=27;
p_output1[266]=28;
p_output1[267]=29;
p_output1[268]=30;
p_output1[269]=31;
p_output1[270]=32;
p_output1[271]=33;
p_output1[272]=44;
p_output1[273]=45;
p_output1[274]=46;
p_output1[275]=47;
p_output1[276]=49;
p_output1[277]=50;
p_output1[278]=51;
p_output1[279]=52;
p_output1[280]=53;
p_output1[281]=64;
p_output1[282]=4;
p_output1[283]=5;
p_output1[284]=6;
p_output1[285]=7;
p_output1[286]=8;
p_output1[287]=9;
p_output1[288]=10;
p_output1[289]=11;
p_output1[290]=12;
p_output1[291]=13;
p_output1[292]=24;
p_output1[293]=25;
p_output1[294]=26;
p_output1[295]=27;
p_output1[296]=28;
p_output1[297]=29;
p_output1[298]=30;
p_output1[299]=31;
p_output1[300]=32;
p_output1[301]=33;
p_output1[302]=44;
p_output1[303]=45;
p_output1[304]=46;
p_output1[305]=47;
p_output1[306]=48;
p_output1[307]=65;
}
void frost::gen::Js_ddh_LeftToeBottom_cassie(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
| 21.130319 | 83 | 0.663436 | prem-chand |
22145a726afc6e780537042e0710486590beb861 | 1,810 | cpp | C++ | src/algebra/curves/edwards/edwards_pp.cpp | amiller/libsnark | d34b477ed9c0e36f74c78946012658bdecde0c00 | [
"MIT"
] | null | null | null | src/algebra/curves/edwards/edwards_pp.cpp | amiller/libsnark | d34b477ed9c0e36f74c78946012658bdecde0c00 | [
"MIT"
] | null | null | null | src/algebra/curves/edwards/edwards_pp.cpp | amiller/libsnark | d34b477ed9c0e36f74c78946012658bdecde0c00 | [
"MIT"
] | null | null | null | /** @file
*****************************************************************************
* @author This file is part of libsnark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#include "algebra/curves/edwards/edwards_pp.hpp"
namespace libsnark {
template<>
void init_public_params<edwards_pp>()
{
init_edwards_params();
}
template<>
edwards_GT final_exponentiation<edwards_pp>(const edwards_Fq6 &elt)
{
return edwards_final_exponentiation(elt);
}
template<>
edwards_G1_precomp precompute_G1<edwards_pp>(const edwards_G1 &P)
{
return edwards_precompute_G1(P);
}
template<>
edwards_G2_precomp precompute_G2<edwards_pp>(const edwards_G2 &Q)
{
return edwards_precompute_G2(Q);
}
template<>
edwards_Fq6 miller_loop<edwards_pp>(const edwards_G1_precomp &prec_P,
const edwards_G2_precomp &prec_Q)
{
return edwards_miller_loop(prec_P, prec_Q);
}
template<>
edwards_Fq6 double_miller_loop<edwards_pp>(const edwards_G1_precomp &prec_P1,
const edwards_G2_precomp &prec_Q1,
const edwards_G1_precomp &prec_P2,
const edwards_G2_precomp &prec_Q2)
{
return edwards_double_miller_loop(prec_P1, prec_Q1, prec_P2, prec_Q2);
}
template<>
edwards_Fq6 pairing<edwards_pp>(const edwards_G1 &P,
const edwards_G2 &Q)
{
return edwards_pairing(P, Q);
}
template<>
edwards_Fq6 reduced_pairing<edwards_pp>(const edwards_G1 &P,
const edwards_G2 &Q)
{
return edwards_reduced_pairing(P, Q);
}
} // libsnark
| 27.014925 | 79 | 0.599448 | amiller |
2214a8bab85388c389cbc2c0f8a6122974a0e905 | 2,153 | cpp | C++ | src/Emulators/nestopiaue/core/board/NstBoardJalecoJf17.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 34 | 2021-05-29T07:04:17.000Z | 2022-03-10T20:16:03.000Z | src/Emulators/nestopiaue/core/board/NstBoardJalecoJf17.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-25T13:05:21.000Z | 2022-01-19T17:35:17.000Z | src/Emulators/nestopiaue/core/board/NstBoardJalecoJf17.cpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-24T18:37:41.000Z | 2022-02-06T23:06:02.000Z | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include "NstBoard.hpp"
#include "../NstSoundPlayer.hpp"
#include "NstBoardJalecoJf17.hpp"
namespace Nes
{
namespace Core
{
namespace Boards
{
namespace Jaleco
{
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("s", on)
#endif
Jf17::Jf17(const Context& c)
:
Board (c),
sound (Sound::Player::Create(*c.apu,c.chips,L"D7756C",board == Type::JALECO_JF17 ? Sound::Player::GAME_MOERO_PRO_TENNIS : Sound::Player::GAME_UNKNOWN,32))
{
}
Jf17::~Jf17()
{
Sound::Player::Destroy( sound );
}
void Jf17::SubReset(bool)
{
Map( 0x8000U, 0xFFFFU, &Jf17::Poke_8000 );
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
NES_POKE_AD(Jf17,8000)
{
data = GetBusData(address,data);
if (data & 0x40)
{
ppu.Update();
chr.SwapBank<SIZE_8K,0x0000>( data & 0xF );
}
if (data & 0x80)
prg.SwapBank<SIZE_16K,0x0000>( data & 0xF );
if (sound && (data & 0x30) == 0x20)
sound->Play( address & 0x1F );
}
}
}
}
}
| 26.256098 | 159 | 0.570831 | slajerek |
2214d19b7d70c44ade25603a62fff62bdda90e63 | 3,584 | cc | C++ | tests/test_sha256.cc | lichray/macrofree-demo | dabe03b3be4f0d5e05f4bb28cf253619ee223ad5 | [
"BSD-2-Clause"
] | 3 | 2019-10-15T01:42:33.000Z | 2019-11-15T05:12:28.000Z | tests/test_sha256.cc | lichray/macrofree-demo | dabe03b3be4f0d5e05f4bb28cf253619ee223ad5 | [
"BSD-2-Clause"
] | null | null | null | tests/test_sha256.cc | lichray/macrofree-demo | dabe03b3be4f0d5e05f4bb28cf253619ee223ad5 | [
"BSD-2-Clause"
] | null | null | null | #include <doctest/doctest.h>
#include <macrofree_demo/sha256.h>
#include <macrofree_demo/sha256_implementations.h>
#include <string_view>
using namespace macrofree_demo;
using namespace std::literals;
TYPE_TO_STRING(sha256_openssl);
TYPE_TO_STRING(sha256_cng);
SCENARIO_TEMPLATE_DEFINE ("feed sha256 inputs", T, test_sha256)
{
auto h2 = sha256(std::in_place_type<T>);
GIVEN ("a sha256 function in initial state")
{
auto h = sha256(std::in_place_type<T>);
WHEN ("we feed no input")
{
THEN ("it gives a known message digest")
{
REQUIRE(h.hexdigest() == "e3b0c44298fc1c149afbf4c8996fb92427ae"
"41e4649b934ca495991b7852b855");
}
AND_THEN ("the message digest is that of an empty string")
{
h2.update("");
REQUIRE(h.digest() == h2.digest());
}
}
WHEN ("we feed some input")
{
h.update("Atelier Ryza");
THEN ("the message digest is not as same as that of no input")
{
REQUIRE(h.digest() != h2.digest());
}
AND_THEN ("nor as same as that of a different input")
{
h2.update("Ever Darkness & the Secret Hideout");
REQUIRE(h.digest() != h2.digest());
}
}
WHEN ("we feed multiple inputs")
{
h.update("macrofree");
h.update("-");
h.update("demo");
THEN ("the input is as-if concatenated")
{
h2.update("macrofree-demo");
REQUIRE(h.digest() == h2.digest());
}
}
WHEN ("we feed input with embedded zero")
{
h.update("Re:\0 - Starting Life in Another World"sv);
THEN ("it gives a known message digest")
{
REQUIRE(h.hexdigest() == "c3e6cddc055c28268d52b9046db8b3d28a81"
"912c434b17d25514507db0eef6d0");
}
AND_THEN ("the message is not treated as truncated")
{
h2.update("Re:"sv);
REQUIRE(h.digest() != h2.digest());
}
}
}
}
TEST_CASE_TEMPLATE_APPLY(test_sha256, sha256_implementations);
SCENARIO_TEMPLATE_DEFINE ("retrieve sha256 message digest multiple times", T,
test_sha256_multiple)
{
auto h2 = sha256(std::in_place_type<T>);
GIVEN ("a sha256 function in initial state")
{
auto h = sha256(std::in_place_type<T>);
WHEN ("we've accessed its message digest")
{
auto md = h.digest();
THEN ("we can access it again and get the same result")
{
REQUIRE(h.digest() == md);
}
}
WHEN ("we've feed some input and accessed its message digest")
{
h.update("macrofree");
h.update("-");
auto md = h.digest();
THEN ("we can add more input and get the whole result")
{
h.update("demo");
h2.update("macrofree-demo"sv);
REQUIRE(h.digest() == h2.digest());
}
AND_THEN ("the intermediate result was correct")
{
h2.update("macrofree-"sv);
REQUIRE(md == h2.digest());
}
}
}
}
TEST_CASE_TEMPLATE_APPLY(test_sha256_multiple, sha256_implementations);
| 26.352941 | 79 | 0.504743 | lichray |
22221e66f35f6c6059c1ade5dbd101fcbb4c4b47 | 514 | cpp | C++ | SourceCode/Chapter 15/GradedActivity Version 3/PassFailActivity.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | 1 | 2019-04-09T18:29:38.000Z | 2019-04-09T18:29:38.000Z | SourceCode/Chapter 15/PassFailActivity/PassFailActivity.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | SourceCode/Chapter 15/PassFailActivity/PassFailActivity.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | #include "PassFailActivity.h"
//******************************************************
// Member function PassFailActivity::getLetterGrade *
// This function returns 'P' if the score is passing, *
// otherwise it returns 'F'. *
//******************************************************
char PassFailActivity::getLetterGrade() const
{
char letterGrade;
if (score >= minPassingScore)
letterGrade = 'P';
else
letterGrade = 'F';
return letterGrade;
} | 27.052632 | 56 | 0.480545 | aceiro |
2224fa53d15ae417f12d204ef9c7acb15b06e6b5 | 2,224 | hpp | C++ | include/gridtools/boundaries/direction.hpp | tehrengruber/gridtools | 92bbbf65174d440c28a33babffde41b46ed943de | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/boundaries/direction.hpp | tehrengruber/gridtools | 92bbbf65174d440c28a33babffde41b46ed943de | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/boundaries/direction.hpp | tehrengruber/gridtools | 92bbbf65174d440c28a33babffde41b46ed943de | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
/**
@file
@brief definition of direction in a 3D cartesian grid
*/
namespace gridtools {
namespace boundaries {
/** \ingroup Boundary-Conditions
* @{
*/
/**
@brief Enum defining the directions in a discrete Cartesian grid
*/
enum sign { any_ = -2, minus_ = -1, zero_, plus_ };
/** \ingroup Boundary-Conditions
@brief Class defining a direction in a cartesian 3D grid.
The directions correspond to the following:
- all the three template parameters are either plus or minus: identifies a node on the cell
\verbatim
e.g. direction<minus_, plus_, minus_> corresponds to:
.____.
/ /|
o____. |
| | . z
| |/ x__/
.____. |
y
\endverbatim
- there is one zero parameter: identifies one edge
\verbatim
e.g. direction<zero_, plus_, minus_> corresponds to:
.____.
/ /|
.####. |
| | .
| |/
.____.
\endverbatim
- there are 2 zero parameters: identifies one face
\verbatim
e.g. direction<zero_, zero_, minus_> corresponds to:
.____.
/ /|
.____. |
|####| .
|####|/
.####.
\endverbatim
- the case in which all three are zero does not belong to the boundary and is excluded.
\tparam I_ Orientation in the I dimension
\tparam J_ Orientation in the J dimension
\tparam K_ Orientation in the K dimension
*/
template <sign I_, sign J_, sign K_>
struct direction {
static constexpr sign i = I_;
static constexpr sign j = J_;
static constexpr sign k = K_;
};
} // namespace boundaries
} // namespace gridtools
| 28.151899 | 102 | 0.503597 | tehrengruber |
2226718a81a4b52ad987ff20dcc7882042d03526 | 424 | cpp | C++ | _includes/leet022/leet022_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | _includes/leet022/leet022_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | 8 | 2019-12-19T04:46:05.000Z | 2022-02-26T03:45:22.000Z | _includes/leet022/leet022_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
helper("",n,0,res);
return res;
}
void helper(string cur, int left, int right,vector<string>& res){
if(!left&&!right) res.push_back(cur);
else{
if(left>0) helper(cur+"(",left-1,right+1,res);
if(right>0) helper(cur+")",left,right-1,res);
}
}
};
| 26.5 | 72 | 0.537736 | mingdaz |
2227f9972117dce06a1507be79c5659f570d265c | 360 | cpp | C++ | SimCore/model/Chip/Chip.cpp | kino-6/BuiltInSystemSimulator | 63d447f89c0c9166b93a96844d2d103f9d00a4b2 | [
"Apache-2.0"
] | null | null | null | SimCore/model/Chip/Chip.cpp | kino-6/BuiltInSystemSimulator | 63d447f89c0c9166b93a96844d2d103f9d00a4b2 | [
"Apache-2.0"
] | null | null | null | SimCore/model/Chip/Chip.cpp | kino-6/BuiltInSystemSimulator | 63d447f89c0c9166b93a96844d2d103f9d00a4b2 | [
"Apache-2.0"
] | null | null | null | #include "Chip.h"
SFR g_sfr;
Chip::Chip(void) {
this->Reset();
}
Chip::~Chip(void) {
}
void Chip::Main(void) {
this->fetch_sfr();
this->sfr.TMR += 1;
this->reflect_sfr();
}
void Chip::reflect_sfr(void) {
g_sfr = this->sfr;
}
void Chip::fetch_sfr(void) {
this->sfr = g_sfr;
}
void Chip::Reset(void) {
this->sfr = { 0 };
g_sfr = this->sfr;
} | 10.285714 | 30 | 0.591667 | kino-6 |
22285afe5975218c2971ec1b925c6f10700cb402 | 5,913 | cpp | C++ | src/map/generator/modules/Water.cpp | Yukkurigame/Yukkuri | 3c8440b6b4e4d14cf6eec5685504839e4e714036 | [
"MIT"
] | 2 | 2017-05-15T19:28:37.000Z | 2018-03-31T01:10:19.000Z | src/map/generator/modules/Water.cpp | Yukkurigame/Yukkuri | 3c8440b6b4e4d14cf6eec5685504839e4e714036 | [
"MIT"
] | null | null | null | src/map/generator/modules/Water.cpp | Yukkurigame/Yukkuri | 3c8440b6b4e4d14cf6eec5685504839e4e714036 | [
"MIT"
] | null | null | null | /*
* Water.cpp
*
* Created on: 13.04.2013
*/
#include "map/generator/modules/Water.h"
#include "debug.h"
#include "hacks.h"
namespace MapWater
{
void redistributeMoisture( list< Corner* >& );
void calculateWatersheds( );
void createRivers( );
void assignCornerMoisture( );
void assignPolygonMoisture( );
MapProto* proto;
GeneratorModule module = { &init, &clean, &process };
}
void MapWater::init( )
{
proto = NULL;
}
void MapWater::process( MapProto* pr )
{
proto = pr;
Debug::debug( Debug::MAP, "Assign moisture...\n" );
// Determine watersheds: for every corner, where does it flow
// out into the ocean?
calculateWatersheds();
// Create rivers.
createRivers();
// Determine moisture at corners, starting at rivers
// and lakes, but not oceans. Then redistribute
// moisture to cover the entire range evenly from 0.0
// to 1.0. Then assign polygon moisture as the average
// of the corner moisture.
assignCornerMoisture();
list< Corner* > cnrs = MapGenerator::landCorners( proto );
redistributeMoisture( cnrs );
assignPolygonMoisture();
}
void MapWater::clean( )
{
proto = NULL;
}
GeneratorModule* MapWater::get_module()
{
return &module;
}
bool compareMoisture( const Corner* a, const Corner* b )
{
return a->moisture < b->moisture;
}
/**
* Change the overall distribution of moisture to be evenly distributed.
*/
void MapWater::redistributeMoisture( list< Corner* >& locations )
{
locations.sort( compareMoisture );
float length = locations.count;
int index = 0;
ITER_LIST( Corner*, locations ){
double m = (double)index / length;
it->data->moisture = m;
index++;
}
}
/**
* Calculate the watershed of every land point. The watershed is
* the last downstream land point in the downslope graph.
* TODO: watersheds are currently calculated on corners, but it'd
* be more useful to compute them on polygon centers so that every
* polygon can be marked as being in one watershed.
*/
void MapWater::calculateWatersheds( )
{
// Initially the watershed pointer points downslope one step.
Corner* q;
FOREACH1( q, proto->corners ) {
q->watershed = q;
if( !q->ocean && !q->coast )
q->watershed = q->downslope;
}
// Follow the downslope pointers to the coast. Limit to 100
// iterations although most of the time with NUM_POINTS=2000 it
// only takes 20 iterations because most points are not far from
// a coast. TODO: can run faster by looking at
// p.watershed.watershed instead of p.downslope.watershed.
for( int i = 0, changed = 0; i < 100; ++i, changed = 0 ){
Corner* q;
FOREACH1( q, proto->corners ) {
if( !q->ocean && !q->coast && !q->watershed->coast ){
Corner* r = q->downslope->watershed;
//Corner* r = q->downslope->watershed;
if( !r->ocean )
q->watershed = r;
changed++;
}
}
if( !changed )
break;
}
// How big is each watershed?
FOREACH1( q, proto->corners ) {
Corner* r = q->watershed;
r->watershed_size++;
}
int min_watershed = 20;
for( int i = 0, changed = 0; i < 100; ++i, changed = 0 ){
FOREACH1( q, proto->corners ) {
if( q->watershed->watershed_size > min_watershed )
continue;
ITER_LIST( Corner*, q->adjacent ){
Corner* r = it->data->watershed;
if( r->watershed_size > min_watershed ){
q->watershed = r->watershed;
changed = true;
break;
}
}
}
if( !changed )
break;
}
}
/**
* Create rivers along edges. Pick a random corner point, then
* move downslope. Mark the edges and corners as rivers.
*/
void MapWater::createRivers( )
{
int length = proto->corners.size();
if( !length )
return;
list< Corner* > river_sources;
for( int i = 0; i < GENERATOR_SIZE / 2; i++ ){
// FIXME: this place prevents from usnig list for corners
Corner* q = proto->corners[proto->mapRandom.nextInt( 0, length - 1 )];
if( q->ocean || q->elevation < 0.3 || q->elevation > 0.9 )
continue;
river_sources.push(q);
// Bias rivers to go west: if (q.downslope.x > q.x) continue;
while( !q->coast ){
if( q == q->downslope )
break;
Edge* edge = MapGenerator::lookupEdgeFromCorner( q, q->downslope );
edge->river++;
q->river++;
q->downslope->river++; // TODO: fix double count
q = q->downslope;
}
}
// Make all rivers end at lakes or another rivers
while( river_sources.count > 0 ){
Corner* source = river_sources.pop();
Corner* q = source;
while( !q->coast && q != q->downslope && q->downslope->river )
q = q->downslope;
if( q->coast )
continue;
if( q->river > 3 )
q->downslope->touches.head->data->water = true;
// TODO: connect to another rivers
}
}
/**
* Calculate moisture. Freshwater sources spread moisture: rivers
* and lakes (not oceans). Saltwater sources have moisture but do
* not spread it (we set it at the end, after propagation).
*/
void MapWater::assignCornerMoisture( )
{
list< Corner* > queue;
// Fresh water
Corner* q;
FOREACH1( q, proto->corners ) {
if( ( q->water || q->river > 0 ) && !q->ocean ){
q->moisture =
q->river > 0 ? std::min( 3.0, 0.2 * (double)q->river ) : 1.0;
queue.push_back( q );
}else{
q->moisture = 0.0;
}
}
while( queue.count > 0 ){
Corner* q = queue.pop();
ITER_LIST( Corner*, q->adjacent ){
Corner* r = it->data;
double newMoisture = q->moisture * 0.9;
if( newMoisture > r->moisture ){
r->moisture = newMoisture;
queue.push_back( r );
}
}
}
// Salt water
FOREACH1( q, proto->corners ) {
if( q->ocean || q->coast )
q->moisture = 1.0;
}
}
/**
* Polygon moisture is the average of the moisture at corners
*/
void MapWater::assignPolygonMoisture( )
{
Center* p;
FOREACH1( p, proto->centers ) {
double sumMoisture = 0.0;
double count = p->corners.count;
ITER_LIST( Corner*, p->corners ){
Corner* q = it->data;
if( q->moisture > 1.0 )
q->moisture = 1.0;
sumMoisture += q->moisture;
}
p->moisture = sumMoisture / count;
}
}
| 22.655172 | 72 | 0.643666 | Yukkurigame |
222860ac5e12896f94c5162e06f71dbb82925e31 | 4,386 | cpp | C++ | extsamp/company.cpp | OS2World/DEV-SAMPLES-SOM-IBM | 083a80ccf1c7afe2518f3cbf90998ccc5cf44391 | [
"BSD-3-Clause"
] | null | null | null | extsamp/company.cpp | OS2World/DEV-SAMPLES-SOM-IBM | 083a80ccf1c7afe2518f3cbf90998ccc5cf44391 | [
"BSD-3-Clause"
] | null | null | null | extsamp/company.cpp | OS2World/DEV-SAMPLES-SOM-IBM | 083a80ccf1c7afe2518f3cbf90998ccc5cf44391 | [
"BSD-3-Clause"
] | null | null | null | /*
*
* 25H7912 (C) COPYRIGHT International Business Machines Corp. 1992,1996,1996
* All Rights Reserved
* Licensed Materials - Property of IBM
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
*
*
* DISCLAIMER OF WARRANTIES.
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard or IBM
* product and is provided to you solely for the purpose of assisting
* you in the development of your applications. The code is provided
* "AS IS". IBM MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
* THIS CODE. IBM shall not be liable for any damages arising out of
* your use of the sample code, even if they have been advised of the
* possibility of such damages.
*
* DISTRIBUTION.
* This sample code can be freely distributed, copied, altered, and
* incorporated into other software, provided that it bears the above
* Copyright notice and DISCLAIMER intact.
*
*/
#ifndef lint
static char *sccsid = "%Z% %I% %W% %G% %U% [%H% %T%]";
#endif
/*
* COMPANY.CPP
*
* NOTE
* Please read the README file before inspecting this code. It provides
* a context to enhance your understanding of how the Externalization
* Service can be used to your advantage.
*
* DESCRIPTION:
*
* This program creates a company object on an object server named
* objServer. The object is created their because it is the only
* server that has the VeryBigCo interface registered with it. This
* company object is processed by the clients (client1 and client2)
* packaged with this sample.
*
* COMPANY ALGORITHM -- main()
* 1. Create remote object
* 2. Bind the object to a name. This allows clients to use the
* Name Service to resolve a reference to the object by using the name.
* end algorithm
*/
#include <iostream.h>
#include <somd.xh>
#include <somnm.xh> // Usage binding for Name Service
#include "util.hpp" // Utilities for the samples
#include "samobj.xh" // Usage bindings of the sample object
void main(int argc, char **argv) {
Environment *ev = somGetGlobalEnvironment();
OESSample_VeryBigCo * companyObj, *tmpCo;
SOM_InitEnvironment(ev); // Setup for processing
SOMD_Init(ev);
tmpCo = (OESSample_VeryBigCo *) (void *)
somdCreate(ev, "OESSample::VeryBigCo", FALSE);
checkException(ev, "Company -- Creating the company object");
companyObj = (OESSample_VeryBigCo *) (void *)
tmpCo->init_for_object_creation(ev);
checkException(ev, "Company -- Initializing the company object");
((SOMDObject *)tmpCo)->release(ev);
checkException(ev,
"Company -- Dis-associating pointer from company object storage");
companyObj->populate(ev);
somPrintf("******* REMOTE OBJECT CREATED ON THE OBJSERVER ********\n");
ExtendedNaming_ExtendedNamingContext *nameContext;
char *kind = "object interface"; // Define the name
char *id = "Dept45"; // for the Department
CosNaming_NameComponent nameComponent = {id, kind}; // 45 object that is
CosNaming_Name name = { 1, 1, &nameComponent }; // embedded in companyObj
nameContext = (ExtendedNaming_ExtendedNamingContext*)
SOMD_ORBObject->resolve_initial_references(ev, "NameService");
checkException(ev, "Company -- Fetch reference to root naming context");
// Register the Department 45 object with the Naming Server.
nameContext->bind(ev, &name, (SOMObject*) ((void *) companyObj->_get_dept45(ev)) );
if (ev->_major == USER_EXCEPTION) {
if(strcmp(ev->exception._exception_name, "::CosNaming::NamingContext::AlreadyBound") == 0) {
somExceptionFree(ev);
nameContext->unbind(ev, &name);
nameContext->bind(ev, &name, (SOMObject*) ((void *) companyObj->_get_dept45(ev)) );
}
else {
somPrintf("Department 45 object bind failed\n");
exit(1);
}
}
somPrintf("******* REMOTE OBJECT REGISTERED WITH THE NAME SERVER ********\n");
somPrintf("******* You may now run client1 and/or client2 ********\n");
}
| 37.487179 | 98 | 0.676471 | OS2World |
222a48a800ee9eae152891fa0360f5c680a2fb93 | 3,441 | cpp | C++ | CPP_Files/Button.cpp | Yaters/Knightmare | 4440fafb910054cc70bc2d01994435011226061f | [
"MIT"
] | null | null | null | CPP_Files/Button.cpp | Yaters/Knightmare | 4440fafb910054cc70bc2d01994435011226061f | [
"MIT"
] | null | null | null | CPP_Files/Button.cpp | Yaters/Knightmare | 4440fafb910054cc70bc2d01994435011226061f | [
"MIT"
] | null | null | null | #include "Button.h"
Button::Button() {
size = glm::vec2(0, 0);
pos = glm::vec2(0, 0);
charSize = 0;
stringSize = glm::vec2(0,0);
boxTitle = "Button";
}
//Basic constructor sets values
Button::Button(std::string text, glm::vec2 size, glm::vec2 pos, GLfloat charSize): text(text) {
this->size = size;
this->pos = pos;
this->charSize = charSize;
StringSize();
boxTitle = "Button";
}
Button::Button(std::string text, glm::vec2 size, glm::vec2 pos, GLfloat charSize, TextMode mode) : text(text) {
this->mode = mode;
this->size = size;
this->pos = pos;
this->charSize = charSize;
StringSize();
boxTitle = "Button";
}
void Button::setTextColor(glm::vec3 mainColor) {
this->textColor = mainColor;
}
void Button::setTextColor(glm::vec3 mainColor, glm::vec3 outsideColor) {
this->textColor = mainColor;
this->textOutsideColor = outsideColor;
}
void Button::setTextOutsideColor(glm::vec3 outsideColor) {
this->textOutsideColor = outsideColor;
}
void Button::StringSize() {
std::string::const_iterator c;
FontGlyph ch;
GLfloat sizeX = 0;
GLfloat sizeY = 0;
GLfloat scale = charSize / 10.f;
GLint num = 0;
GLfloat avgHeight = 0;
// / 10.f is from random downsize in string draw method
for (c = this->text.begin(); c != this->text.end(); c++, num++) {
ch = Resource_manager::GetFont("Arial").getGlyph((unsigned char) *c);
sizeX += ch.Advance * scale; //TODO: Make the size (here and in draw string) dynamic w/ button size
//Alright, here's the deal. X works perfectly. For y, I have no clue what to do.
//This is not exact. In fact, it's probaby mathematical nonsense. But it gets the
//ballpark, so I'm happy. I'm sorry all you OCD people out there
GLfloat test = ch.Size.y * scale + ch.Bearing.y * scale;
test *= -1;
avgHeight += test;
}
avgHeight /= (float)num;
sizeY = avgHeight;
this->stringSize = glm::vec2(sizeX, sizeY);
}
//Basic draw function, draws the button texture with the given size and pos
//If the mouse is in the button, changes the button color and updates isSelected
//Will need to update once text feature is up and running
void Button::Draw(glm::vec2 cursorPos, SpriteRender* renderer) {
//This pos is top left, string pos is bottom left
// - - - - - - - - - - - - - - - - - - - - -
//| LABEL |
// - - - - - - - - - - - - - - - - - - - - -
glm::vec2 stringPos = this->pos;
stringPos.y += (this->size.y + this->stringSize.y) / 2.f;
stringPos.x += (this->size.x - this->stringSize.x) / 2.f;
if (!Collider::checkPointRecCol(cursorPos, *this)) {
//Normal button blue words if not selected
renderer->DrawSprite(Resource_manager::GetTexture(boxTitle), pos, size, glm::vec2(0, -1), glm::vec4(1, 1, 1, 1));
//renderer->DrawString(text, "Arial", stringPos, this->charSize, glm::vec3(0.0, 0.0, 1.0)); //Draw blue if selected
renderer->DrawString(text, "Arial", stringPos, this->charSize, this->textColor, this->textOutsideColor, this->mode);
isSelected = GL_FALSE;
} else {
//Blue button Red words if not selected
renderer->DrawSprite(Resource_manager::GetTexture(boxTitle), pos, size, glm::vec2(0, -1), glm::vec4(0.5, 0.5, 1.0, 1.0));
//renderer->DrawString(text, "Arial", stringPos, this->charSize, glm::vec3(0.540, 0.062, 0.109)); //Draw blue if selected
renderer->DrawString(text, "Arial", stringPos, this->charSize, 1.0f - this->textColor, 1.0f - this->textOutsideColor, this->mode);
isSelected = GL_TRUE;
}
}
| 36.606383 | 132 | 0.66347 | Yaters |
222afb49735bd5360b8912299595a6f41c97423e | 632 | cxx | C++ | deps/src/cmake-3.9.3/Source/cmProperty.cxx | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2018-12-15T20:03:51.000Z | 2018-12-15T20:03:51.000Z | deps/src/cmake-3.9.3/Source/cmProperty.cxx | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | deps/src/cmake-3.9.3/Source/cmProperty.cxx | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1 | 2020-10-21T17:46:28.000Z | 2020-10-21T17:46:28.000Z | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmProperty.h"
#include "cmConfigure.h"
void cmProperty::Set(const char* value)
{
this->Value = value;
this->ValueHasBeenSet = true;
}
void cmProperty::Append(const char* value, bool asString)
{
if (!this->Value.empty() && *value && !asString) {
this->Value += ";";
}
this->Value += value;
this->ValueHasBeenSet = true;
}
const char* cmProperty::GetValue() const
{
if (this->ValueHasBeenSet) {
return this->Value.c_str();
}
return CM_NULLPTR;
}
| 21.793103 | 77 | 0.675633 | shreyasvj25 |
222f8e1a3a058234efb038ca7dec8660bb15a64a | 1,350 | cpp | C++ | karum/DeleteList.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | karum/DeleteList.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | karum/DeleteList.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdlib>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){}
Node(int d){
data=d;
next=NULL;
}
Node *insertElement(Node *head,int d){
Node *np=new Node(d);
Node *tmp=head;
if(head==NULL)
return np;
else
while(tmp->next)
tmp=tmp->next;
tmp->next=np;
return head;
}
void deleteList(Node *head){
while(head->next!=NULL){
Node *t=head;
cout<<"Freeing "<<t->data<<".\n";
head=head->next;
free(t);
}
cout<<"Freeing "<<head->data<<".\n";
free(head);
cout<<"The list is empty now.\n";
}
};
int main()
{
int n,p;
Node np;
Node *head=NULL;
cout<<"Enter the size of linked list: ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"\nEnter element "<<i+1<<": ";
cin>>p;
head=np.insertElement(head,p);
}
np.deleteList(head);
}
| 21.774194 | 60 | 0.36 | shivanib01 |
223813ee934ea1341d589681143541d4a7bb278f | 3,391 | cc | C++ | chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/policy/dlp/dlp_content_manager_browsertest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 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/chromeos/policy/dlp/dlp_content_manager.h"
#include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/window.h"
#include "ui/gfx/geometry/rect.h"
namespace policy {
namespace {
const DlpContentRestrictionSet kScreenshotRestricted(
DlpContentRestriction::kScreenshot);
} // namespace
class DlpContentManagerBrowserTest : public InProcessBrowserTest {
public:
DlpContentManagerBrowserTest() {}
};
IN_PROC_BROWSER_TEST_F(DlpContentManagerBrowserTest, ScreenshotsRestricted) {
DlpContentManager* manager = DlpContentManager::Get();
ui_test_utils::NavigateToURL(browser(), GURL("https://example.com"));
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
aura::Window* root_window =
browser()->window()->GetNativeWindow()->GetRootWindow();
ScreenshotArea fullscreen = ScreenshotArea::CreateForAllRootWindows();
ScreenshotArea window = ScreenshotArea::CreateForWindow(root_window);
const gfx::Rect web_contents_rect = web_contents->GetContainerBounds();
gfx::Rect out_rect(web_contents_rect);
out_rect.Offset(web_contents_rect.width(), web_contents_rect.height());
gfx::Rect in_rect(web_contents_rect);
in_rect.Offset(web_contents_rect.width() / 2, web_contents_rect.height() / 2);
ScreenshotArea partial_out =
ScreenshotArea::CreateForPartialWindow(root_window, out_rect);
ScreenshotArea partial_in =
ScreenshotArea::CreateForPartialWindow(root_window, in_rect);
EXPECT_FALSE(manager->IsScreenshotRestricted(fullscreen));
EXPECT_FALSE(manager->IsScreenshotRestricted(window));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_in));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_out));
manager->OnConfidentialityChanged(web_contents, kScreenshotRestricted);
EXPECT_TRUE(manager->IsScreenshotRestricted(fullscreen));
EXPECT_TRUE(manager->IsScreenshotRestricted(window));
EXPECT_TRUE(manager->IsScreenshotRestricted(partial_in));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_out));
web_contents->WasHidden();
manager->OnVisibilityChanged(web_contents);
EXPECT_FALSE(manager->IsScreenshotRestricted(fullscreen));
EXPECT_TRUE(manager->IsScreenshotRestricted(window));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_in));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_out));
web_contents->WasShown();
manager->OnVisibilityChanged(web_contents);
EXPECT_TRUE(manager->IsScreenshotRestricted(fullscreen));
EXPECT_TRUE(manager->IsScreenshotRestricted(window));
EXPECT_TRUE(manager->IsScreenshotRestricted(partial_in));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_out));
manager->OnWebContentsDestroyed(web_contents);
EXPECT_FALSE(manager->IsScreenshotRestricted(fullscreen));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_in));
EXPECT_FALSE(manager->IsScreenshotRestricted(partial_out));
}
} // namespace policy
| 42.3875 | 80 | 0.800944 | mghgroup |
22384a03b4c6699403f1350e64369b30f18ea33a | 29,186 | cpp | C++ | system/txn.cpp | zhanhaozhao/sigmod21-wkdb | b06868448125363e15a0887abafaaced8908696b | [
"Apache-2.0"
] | 1 | 2020-09-28T07:54:27.000Z | 2020-09-28T07:54:27.000Z | system/txn.cpp | zhanhaozhao/sigmod21-wkdb | b06868448125363e15a0887abafaaced8908696b | [
"Apache-2.0"
] | null | null | null | system/txn.cpp | zhanhaozhao/sigmod21-wkdb | b06868448125363e15a0887abafaaced8908696b | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016 Massachusetts Institute of Technology
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 "helper.h"
#include "txn.h"
#include "row.h"
#include "wl.h"
#include "query.h"
#include "thread.h"
#include "mem_alloc.h"
#include "occ.h"
#include "row_occ.h"
#include "table.h"
#include "catalog.h"
#include "index_btree.h"
#include "index_hash.h"
#include "msg_queue.h"
#include "pool.h"
#include "message.h"
#include "ycsb_query.h"
#include "tpcc_query.h"
#include "pps_query.h"
#include "array.h"
#include "maat.h"
#include "wkdb.h"
void TxnStats::init() {
starttime=0;
wait_starttime=get_sys_clock();
total_process_time=0;
process_time=0;
total_local_wait_time=0;
local_wait_time=0;
total_remote_wait_time=0;
remote_wait_time=0;
total_twopc_time=0;
twopc_time=0;
write_cnt = 0;
abort_cnt = 0;
total_work_queue_time = 0;
work_queue_time = 0;
total_cc_block_time = 0;
cc_block_time = 0;
total_cc_time = 0;
cc_time = 0;
total_work_queue_cnt = 0;
work_queue_cnt = 0;
total_msg_queue_time = 0;
msg_queue_time = 0;
total_abort_time = 0;
clear_short();
}
void TxnStats::clear_short() {
work_queue_time_short = 0;
cc_block_time_short = 0;
cc_time_short = 0;
msg_queue_time_short = 0;
process_time_short = 0;
network_time_short = 0;
}
void TxnStats::reset() {
wait_starttime=get_sys_clock();
total_process_time += process_time;
process_time = 0;
total_local_wait_time += local_wait_time;
local_wait_time = 0;
total_remote_wait_time += remote_wait_time;
remote_wait_time = 0;
total_twopc_time += twopc_time;
twopc_time = 0;
write_cnt = 0;
total_work_queue_time += work_queue_time;
work_queue_time = 0;
total_cc_block_time += cc_block_time;
cc_block_time = 0;
total_cc_time += cc_time;
cc_time = 0;
total_work_queue_cnt += work_queue_cnt;
work_queue_cnt = 0;
total_msg_queue_time += msg_queue_time;
msg_queue_time = 0;
clear_short();
}
void TxnStats::abort_stats(uint64_t thd_id) {
total_process_time += process_time;
total_local_wait_time += local_wait_time;
total_remote_wait_time += remote_wait_time;
total_twopc_time += twopc_time;
total_work_queue_time += work_queue_time;
total_msg_queue_time += msg_queue_time;
total_cc_block_time += cc_block_time;
total_cc_time += cc_time;
total_work_queue_cnt += work_queue_cnt;
assert(total_process_time >= process_time);
INC_STATS(thd_id,lat_s_rem_work_queue_time,total_work_queue_time);
INC_STATS(thd_id,lat_s_rem_msg_queue_time,total_msg_queue_time);
INC_STATS(thd_id,lat_s_rem_cc_block_time,total_cc_block_time);
INC_STATS(thd_id,lat_s_rem_cc_time,total_cc_time);
INC_STATS(thd_id,lat_s_rem_process_time,total_process_time);
}
void TxnStats::commit_stats(uint64_t thd_id, uint64_t txn_id, uint64_t batch_id, uint64_t timespan_long, uint64_t timespan_short) {
total_process_time += process_time;
total_local_wait_time += local_wait_time;
total_remote_wait_time += remote_wait_time;
total_twopc_time += twopc_time;
total_work_queue_time += work_queue_time;
total_msg_queue_time += msg_queue_time;
total_cc_block_time += cc_block_time;
total_cc_time += cc_time;
total_work_queue_cnt += work_queue_cnt;
assert(total_process_time >= process_time);
#if CC_ALG == CALVIN
INC_STATS(thd_id,lat_s_loc_work_queue_time,work_queue_time);
INC_STATS(thd_id,lat_s_loc_msg_queue_time,msg_queue_time);
INC_STATS(thd_id,lat_s_loc_cc_block_time,cc_block_time);
INC_STATS(thd_id,lat_s_loc_cc_time,cc_time);
INC_STATS(thd_id,lat_s_loc_process_time,process_time);
// latency from start of transaction at this node
PRINT_LATENCY("lat_l %ld %ld %ld %f %f %f %f %f %f\n"
, txn_id
, batch_id
, total_work_queue_cnt
, (double) timespan_long / BILLION
, (double) total_work_queue_time / BILLION
, (double) total_msg_queue_time / BILLION
, (double) total_cc_block_time / BILLION
, (double) total_cc_time / BILLION
, (double) total_process_time / BILLION
);
#else
// latency from start of transaction
if (IS_LOCAL(txn_id)) {
INC_STATS(thd_id,lat_l_loc_work_queue_time,total_work_queue_time);
INC_STATS(thd_id,lat_l_loc_msg_queue_time,total_msg_queue_time);
INC_STATS(thd_id,lat_l_loc_cc_block_time,total_cc_block_time);
INC_STATS(thd_id,lat_l_loc_cc_time,total_cc_time);
INC_STATS(thd_id,lat_l_loc_process_time,total_process_time);
INC_STATS(thd_id,lat_l_loc_abort_time,total_abort_time);
INC_STATS(thd_id,lat_s_loc_work_queue_time,work_queue_time);
INC_STATS(thd_id,lat_s_loc_msg_queue_time,msg_queue_time);
INC_STATS(thd_id,lat_s_loc_cc_block_time,cc_block_time);
INC_STATS(thd_id,lat_s_loc_cc_time,cc_time);
INC_STATS(thd_id,lat_s_loc_process_time,process_time);
INC_STATS(thd_id,lat_short_work_queue_time,work_queue_time_short);
INC_STATS(thd_id,lat_short_msg_queue_time,msg_queue_time_short);
INC_STATS(thd_id,lat_short_cc_block_time,cc_block_time_short);
INC_STATS(thd_id,lat_short_cc_time,cc_time_short);
INC_STATS(thd_id,lat_short_process_time,process_time_short);
INC_STATS(thd_id,lat_short_network_time,network_time_short);
}
else {
INC_STATS(thd_id,lat_l_rem_work_queue_time,total_work_queue_time);
INC_STATS(thd_id,lat_l_rem_msg_queue_time,total_msg_queue_time);
INC_STATS(thd_id,lat_l_rem_cc_block_time,total_cc_block_time);
INC_STATS(thd_id,lat_l_rem_cc_time,total_cc_time);
INC_STATS(thd_id,lat_l_rem_process_time,total_process_time);
}
if (IS_LOCAL(txn_id)) {
PRINT_LATENCY("lat_s %ld %ld %f %f %f %f %f %f\n"
, txn_id
, work_queue_cnt
, (double) timespan_short / BILLION
, (double) work_queue_time / BILLION
, (double) msg_queue_time / BILLION
, (double) cc_block_time / BILLION
, (double) cc_time / BILLION
, (double) process_time / BILLION
);
/*
PRINT_LATENCY("lat_l %ld %ld %ld %f %f %f %f %f %f %f\n"
, txn_id
, total_work_queue_cnt
, abort_cnt
, (double) timespan_long / BILLION
, (double) total_work_queue_time / BILLION
, (double) total_msg_queue_time / BILLION
, (double) total_cc_block_time / BILLION
, (double) total_cc_time / BILLION
, (double) total_process_time / BILLION
, (double) total_abort_time / BILLION
);
*/
}
else {
PRINT_LATENCY("lat_rs %ld %ld %f %f %f %f %f %f\n"
, txn_id
, work_queue_cnt
, (double) timespan_short / BILLION
, (double) total_work_queue_time / BILLION
, (double) total_msg_queue_time / BILLION
, (double) total_cc_block_time / BILLION
, (double) total_cc_time / BILLION
, (double) total_process_time / BILLION
);
}
/*
if (!IS_LOCAL(txn_id) || timespan_short < timespan_long) {
// latency from most recent start or restart of transaction
PRINT_LATENCY("lat_s %ld %ld %f %f %f %f %f %f\n"
, txn_id
, work_queue_cnt
, (double) timespan_short / BILLION
, (double) work_queue_time / BILLION
, (double) msg_queue_time / BILLION
, (double) cc_block_time / BILLION
, (double) cc_time / BILLION
, (double) process_time / BILLION
);
}
*/
#endif
if (!IS_LOCAL(txn_id)) {
return;
}
INC_STATS(thd_id,txn_total_process_time,total_process_time);
INC_STATS(thd_id,txn_process_time,process_time);
INC_STATS(thd_id,txn_total_local_wait_time,total_local_wait_time);
INC_STATS(thd_id,txn_local_wait_time,local_wait_time);
INC_STATS(thd_id,txn_total_remote_wait_time,total_remote_wait_time);
INC_STATS(thd_id,txn_remote_wait_time,remote_wait_time);
INC_STATS(thd_id,txn_total_twopc_time,total_twopc_time);
INC_STATS(thd_id,txn_twopc_time,twopc_time);
if(write_cnt > 0) {
INC_STATS(thd_id,txn_write_cnt,1);
}
if(abort_cnt > 0) {
INC_STATS(thd_id,unique_txn_abort_cnt,1);
}
}
void Transaction::init() {
timestamp = UINT64_MAX;
start_timestamp = UINT64_MAX;
end_timestamp = UINT64_MAX;
txn_id = UINT64_MAX;
batch_id = UINT64_MAX;
DEBUG_M("Transaction::init array insert_rows\n");
insert_rows.init(g_max_items_per_txn + 10);
DEBUG_M("Transaction::reset array accesses\n");
accesses.init(MAX_ROW_PER_TXN);
reset(0);
}
void Transaction::reset(uint64_t thd_id) {
release_accesses(thd_id);
accesses.clear();
//release_inserts(thd_id);
insert_rows.clear();
write_cnt = 0;
row_cnt = 0;
twopc_state = START;
rc = RCOK;
}
void Transaction::release_accesses(uint64_t thd_id) {
for(uint64_t i = 0; i < accesses.size(); i++) {
access_pool.put(thd_id,accesses[i]);
}
}
void Transaction::release_inserts(uint64_t thd_id) {
for(uint64_t i = 0; i < insert_rows.size(); i++) {
row_t * row = insert_rows[i];
#if CC_ALG != MAAT && CC_ALG != OCC && CC_ALG != WOOKONG
DEBUG_M("TxnManager::cleanup row->manager free\n");
mem_allocator.free(row->manager, 0);
#endif
row->free_row();
DEBUG_M("Transaction::release insert_rows free\n")
row_pool.put(thd_id,row);
}
}
void Transaction::release(uint64_t thd_id) {
DEBUG("Transaction release\n");
release_accesses(thd_id);
DEBUG_M("Transaction::release array accesses free\n")
accesses.release();
release_inserts(thd_id);
DEBUG_M("Transaction::release array insert_rows free\n")
insert_rows.release();
}
void TxnManager::init(uint64_t thd_id, Workload * h_wl) {
uint64_t prof_starttime = get_sys_clock();
if(!txn) {
DEBUG_M("Transaction alloc\n");
txn_pool.get(thd_id,txn);
}
INC_STATS(get_thd_id(),mtx[15],get_sys_clock()-prof_starttime);
prof_starttime = get_sys_clock();
//txn->init();
if(!query) {
DEBUG_M("TxnManager::init Query alloc\n");
qry_pool.get(thd_id,query);
}
INC_STATS(get_thd_id(),mtx[16],get_sys_clock()-prof_starttime);
//query->init();
//reset();
sem_init(&rsp_mutex, 0, 1);
return_id = UINT64_MAX;
this->h_wl = h_wl;
#if CC_ALG == MAAT
uncommitted_writes = new std::set<uint64_t>();
uncommitted_writes_y = new std::set<uint64_t>();
uncommitted_reads = new std::set<uint64_t>();
#endif
#if CC_ALG == CALVIN
phase = CALVIN_RW_ANALYSIS;
locking_done = false;
calvin_locked_rows.init(MAX_ROW_PER_TXN);
#endif
txn_ready = true;
twopl_wait_start = 0;
txn_stats.init();
}
// reset after abort
void TxnManager::reset() {
lock_ready = false;
lock_ready_cnt = 0;
locking_done = true;
ready_part = 0;
rsp_cnt = 0;
aborted = false;
return_id = UINT64_MAX;
twopl_wait_start = 0;
//ready = true;
// MaaT & WKDB
greatest_write_timestamp = 0;
greatest_read_timestamp = 0;
commit_timestamp = 0;
#if CC_ALG == MAAT
uncommitted_writes->clear();
uncommitted_writes_y->clear();
uncommitted_reads->clear();
#endif
#if CC_ALG == CALVIN
phase = CALVIN_RW_ANALYSIS;
locking_done = false;
calvin_locked_rows.clear();
#endif
assert(txn);
assert(query);
txn->reset(get_thd_id());
// Stats
txn_stats.reset();
}
void
TxnManager::release() {
uint64_t prof_starttime = get_sys_clock();
qry_pool.put(get_thd_id(),query);
INC_STATS(get_thd_id(),mtx[0],get_sys_clock()-prof_starttime);
query = NULL;
prof_starttime = get_sys_clock();
txn_pool.put(get_thd_id(),txn);
INC_STATS(get_thd_id(),mtx[1],get_sys_clock()-prof_starttime);
txn = NULL;
#if CC_ALG == MAAT
delete uncommitted_writes;
delete uncommitted_writes_y;
delete uncommitted_reads;
#endif
#if CC_ALG == CALVIN
calvin_locked_rows.release();
#endif
txn_ready = true;
}
void TxnManager::reset_query() {
#if WORKLOAD == YCSB
((YCSBQuery*)query)->reset();
#elif WORKLOAD == TPCC
((TPCCQuery*)query)->reset();
#elif WORKLOAD == PPS
((PPSQuery*)query)->reset();
#endif
}
RC TxnManager::commit() {
DEBUG("Commit %ld\n",get_txn_id());
release_locks(RCOK);
#if CC_ALG == MAAT
time_table.release(get_thd_id(),get_txn_id());
#endif
#if CC_ALG == WOOKONG
wkdb_time_table.release(get_thd_id(),get_txn_id());
#endif
commit_stats();
#if LOGGING
LogRecord * record = logger.createRecord(get_txn_id(),L_NOTIFY,0,0);
if(g_repl_cnt > 0) {
msg_queue.enqueue(get_thd_id(),Message::create_message(record,LOG_MSG),g_node_id + g_node_cnt + g_client_node_cnt);
}
logger.enqueueRecord(record);
return WAIT;
#endif
return Commit;
}
RC TxnManager::abort() {
if(aborted)
return Abort;
DEBUG("Abort %ld\n",get_txn_id());
txn->rc = Abort;
INC_STATS(get_thd_id(),total_txn_abort_cnt,1);
txn_stats.abort_cnt++;
if(IS_LOCAL(get_txn_id())) {
INC_STATS(get_thd_id(), local_txn_abort_cnt, 1);
} else {
INC_STATS(get_thd_id(), remote_txn_abort_cnt, 1);
txn_stats.abort_stats(get_thd_id());
}
aborted = true;
release_locks(Abort);
#if CC_ALG == MAAT
//assert(time_table.get_state(get_txn_id()) == MAAT_ABORTED);
time_table.release(get_thd_id(),get_txn_id());
#endif
#if CC_ALG == WOOKONG
//assert(time_table.get_state(get_txn_id()) == MAAT_ABORTED);
wkdb_time_table.release(get_thd_id(),get_txn_id());
#endif
uint64_t timespan = get_sys_clock() - txn_stats.restart_starttime;
if (IS_LOCAL(get_txn_id()) && warmup_done) {
INC_STATS_ARR(get_thd_id(),start_abort_commit_latency, timespan);
}
/*
// latency from most recent start or restart of transaction
PRINT_LATENCY("lat_s %ld %ld 0 %f %f %f %f %f %f 0.0\n"
, get_txn_id()
, txn_stats.work_queue_cnt
, (double) timespan / BILLION
, (double) txn_stats.work_queue_time / BILLION
, (double) txn_stats.msg_queue_time / BILLION
, (double) txn_stats.cc_block_time / BILLION
, (double) txn_stats.cc_time / BILLION
, (double) txn_stats.process_time / BILLION
);
*/
//commit_stats();
return Abort;
}
RC TxnManager::start_abort() {
txn->rc = Abort;
DEBUG("%ld start_abort\n",get_txn_id());
if(query->partitions_touched.size() > 1) {
send_finish_messages();
abort();
return Abort;
}
return abort();
}
RC TxnManager::start_commit() {
RC rc = RCOK;
DEBUG("%ld start_commit RO?%d multi-part?%d \n",get_txn_id(),query->readonly(),is_multi_part());
if(is_multi_part()) {
if(!query->readonly() || CC_ALG == OCC || CC_ALG == MAAT) {
// send prepare messages
send_prepare_messages();
rc = WAIT_REM;
} else {
send_finish_messages();
rsp_cnt = 0;
rc = commit();
}
} else { // is not multi-part
rc = validate();
if(rc == RCOK)
rc = commit();
else
start_abort();
}
return rc;
}
void TxnManager::send_prepare_messages() {
rsp_cnt = query->partitions_touched.size() - 1;
DEBUG("%ld Send PREPARE messages to %d\n",get_txn_id(),rsp_cnt);
for(uint64_t i = 0; i < query->partitions_touched.size(); i++) {
if(GET_NODE_ID(query->partitions_touched[i]) == g_node_id) {
continue;
}
msg_queue.enqueue(get_thd_id(),Message::create_message(this,RPREPARE),GET_NODE_ID(query->partitions_touched[i]));
}
}
void TxnManager::send_finish_messages() {
rsp_cnt = query->partitions_touched.size() - 1;
assert(IS_LOCAL(get_txn_id()));
DEBUG("%ld Send FINISH messages to %d\n",get_txn_id(),rsp_cnt);
for(uint64_t i = 0; i < query->partitions_touched.size(); i++) {
if(GET_NODE_ID(query->partitions_touched[i]) == g_node_id) {
continue;
}
msg_queue.enqueue(get_thd_id(),Message::create_message(this,RFIN),GET_NODE_ID(query->partitions_touched[i]));
}
}
int TxnManager::received_response(RC rc) {
assert(txn->rc == RCOK || txn->rc == Abort);
if(txn->rc == RCOK)
txn->rc = rc;
#if CC_ALG == CALVIN
++rsp_cnt;
#else
--rsp_cnt;
#endif
return rsp_cnt;
}
bool TxnManager::waiting_for_response() {
return rsp_cnt > 0;
}
bool TxnManager::is_multi_part() {
return query->partitions_touched.size() > 1;
//return query->partitions.size() > 1;
}
void TxnManager::commit_stats() {
uint64_t commit_time = get_sys_clock();
uint64_t timespan_short = commit_time - txn_stats.restart_starttime;
uint64_t timespan_long = commit_time - txn_stats.starttime;
INC_STATS(get_thd_id(),total_txn_commit_cnt,1);
if(!IS_LOCAL(get_txn_id()) && CC_ALG != CALVIN) {
INC_STATS(get_thd_id(),remote_txn_commit_cnt,1);
txn_stats.commit_stats(get_thd_id(),get_txn_id(),get_batch_id(), timespan_long, timespan_short);
return;
}
INC_STATS(get_thd_id(),txn_cnt,1);
INC_STATS(get_thd_id(),local_txn_commit_cnt,1);
INC_STATS(get_thd_id(), txn_run_time, timespan_long);
if(query->partitions_touched.size() > 1) {
INC_STATS(get_thd_id(),multi_part_txn_cnt,1);
INC_STATS(get_thd_id(),multi_part_txn_run_time,timespan_long);
} else {
INC_STATS(get_thd_id(),single_part_txn_cnt,1);
INC_STATS(get_thd_id(),single_part_txn_run_time,timespan_long);
}
/*if(cflt) {
INC_STATS(get_thd_id(),cflt_cnt_txn,1);
}*/
txn_stats.commit_stats(get_thd_id(),get_txn_id(),get_batch_id(),timespan_long, timespan_short);
#if CC_ALG == CALVIN
return;
#endif
INC_STATS_ARR(get_thd_id(),start_abort_commit_latency, timespan_short);
INC_STATS_ARR(get_thd_id(),last_start_commit_latency, timespan_short);
INC_STATS_ARR(get_thd_id(),first_start_commit_latency, timespan_long);
assert(query->partitions_touched.size() > 0);
INC_STATS(get_thd_id(),parts_touched,query->partitions_touched.size());
INC_STATS(get_thd_id(),part_cnt[query->partitions_touched.size()-1],1);
for(uint64_t i = 0 ; i < query->partitions_touched.size(); i++) {
INC_STATS(get_thd_id(),part_acc[query->partitions_touched[i]],1);
}
}
void TxnManager::register_thread(Thread * h_thd) {
this->h_thd = h_thd;
#if CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC
this->active_part = GET_PART_ID_FROM_IDX(get_thd_id());
#endif
}
void TxnManager::set_txn_id(txnid_t txn_id) {
txn->txn_id = txn_id;
}
txnid_t TxnManager::get_txn_id() {
return txn->txn_id;
}
Workload * TxnManager::get_wl() {
return h_wl;
}
uint64_t TxnManager::get_thd_id() {
if(h_thd)
return h_thd->get_thd_id();
else
return 0;
}
BaseQuery * TxnManager::get_query() {
return query;
}
void TxnManager::set_query(BaseQuery * qry) {
query = qry;
}
void TxnManager::set_timestamp(ts_t timestamp) {
txn->timestamp = timestamp;
}
ts_t TxnManager::get_timestamp() {
return txn->timestamp;
}
void TxnManager::set_start_timestamp(uint64_t start_timestamp) {
txn->start_timestamp = start_timestamp;
}
ts_t TxnManager::get_start_timestamp() {
return txn->start_timestamp;
}
uint64_t TxnManager::incr_lr() {
//ATOM_ADD(this->rsp_cnt,i);
uint64_t result;
sem_wait(&rsp_mutex);
result = ++this->lock_ready_cnt;
sem_post(&rsp_mutex);
return result;
}
uint64_t TxnManager::decr_lr() {
//ATOM_SUB(this->rsp_cnt,i);
uint64_t result;
sem_wait(&rsp_mutex);
result = --this->lock_ready_cnt;
sem_post(&rsp_mutex);
return result;
}
uint64_t TxnManager::incr_rsp(int i) {
//ATOM_ADD(this->rsp_cnt,i);
uint64_t result;
sem_wait(&rsp_mutex);
result = ++this->rsp_cnt;
sem_post(&rsp_mutex);
return result;
}
uint64_t TxnManager::decr_rsp(int i) {
//ATOM_SUB(this->rsp_cnt,i);
uint64_t result;
sem_wait(&rsp_mutex);
result = --this->rsp_cnt;
sem_post(&rsp_mutex);
return result;
}
void TxnManager::release_last_row_lock() {
assert(txn->row_cnt > 0);
row_t * orig_r = txn->accesses[txn->row_cnt-1]->orig_row;
access_t type = txn->accesses[txn->row_cnt-1]->type;
orig_r->return_row(RCOK, type, this, NULL);
//txn->accesses[txn->row_cnt-1]->orig_row = NULL;
}
void TxnManager::cleanup_row(RC rc, uint64_t rid) {
access_t type = txn->accesses[rid]->type;
if (type == WR && rc == Abort && CC_ALG != MAAT) {
type = XP;
}
// Handle calvin elsewhere
#if CC_ALG != CALVIN
#if ISOLATION_LEVEL != READ_UNCOMMITTED
row_t * orig_r = txn->accesses[rid]->orig_row;
if (ROLL_BACK && type == XP &&
(CC_ALG == DL_DETECT ||
CC_ALG == NO_WAIT ||
CC_ALG == WAIT_DIE ||
CC_ALG == HSTORE ||
CC_ALG == HSTORE_SPEC
))
{
orig_r->return_row(rc,type, this, txn->accesses[rid]->orig_data);
} else {
#if ISOLATION_LEVEL == READ_COMMITTED
if(type == WR) {
orig_r->return_row(rc,type, this, txn->accesses[rid]->data);
}
#else
orig_r->return_row(rc,type, this, txn->accesses[rid]->data);
#endif
}
#endif
#if ROLL_BACK && (CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE || CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC)
if (type == WR) {
//printf("free 10 %ld\n",get_txn_id());
txn->accesses[rid]->orig_data->free_row();
DEBUG_M("TxnManager::cleanup row_t free\n");
row_pool.put(get_thd_id(),txn->accesses[rid]->orig_data);
if(rc == RCOK) {
INC_STATS(get_thd_id(),record_write_cnt,1);
++txn_stats.write_cnt;
}
}
#endif
#endif
txn->accesses[rid]->data = NULL;
}
void TxnManager::cleanup(RC rc) {
#if CC_ALG == OCC && MODE == NORMAL_MODE
occ_man.finish(rc,this);
#endif
ts_t starttime = get_sys_clock();
uint64_t row_cnt = txn->accesses.get_count();
assert(txn->accesses.get_count() == txn->row_cnt);
//assert((WORKLOAD == YCSB && row_cnt <= g_req_per_query) || (WORKLOAD == TPCC && row_cnt <= g_max_items_per_txn*2 + 3));
DEBUG("Cleanup %ld %ld\n",get_txn_id(),row_cnt);
for (int rid = row_cnt - 1; rid >= 0; rid --) {
cleanup_row(rc,rid);
}
#if CC_ALG == CALVIN
// cleanup locked rows
for (uint64_t i = 0; i < calvin_locked_rows.size(); i++) {
row_t * row = calvin_locked_rows[i];
row->return_row(rc,RD,this,row);
}
#endif
if (rc == Abort) {
txn->release_inserts(get_thd_id());
txn->insert_rows.clear();
INC_STATS(get_thd_id(), abort_time, get_sys_clock() - starttime);
}
}
RC TxnManager::get_lock(row_t * row, access_t type) {
if (calvin_locked_rows.contains(row)) {
return RCOK;
}
calvin_locked_rows.add(row);
RC rc = row->get_lock(type, this);
if(rc == WAIT) {
INC_STATS(get_thd_id(), txn_wait_cnt, 1);
}
return rc;
}
RC TxnManager::get_row(row_t * row, access_t type, row_t *& row_rtn) {
uint64_t starttime = get_sys_clock();
uint64_t timespan;
RC rc = RCOK;
DEBUG_M("TxnManager::get_row access alloc\n");
Access * access;
access_pool.get(get_thd_id(),access);
//uint64_t row_cnt = txn->row_cnt;
//assert(txn->accesses.get_count() - 1 == row_cnt);
this->last_row = row;
this->last_type = type;
rc = row->get_row(type, this, access->data);
if (rc == Abort || rc == WAIT) {
row_rtn = NULL;
DEBUG_M("TxnManager::get_row(abort) access free\n");
access_pool.put(get_thd_id(),access);
timespan = get_sys_clock() - starttime;
INC_STATS(get_thd_id(), txn_manager_time, timespan);
INC_STATS(get_thd_id(), txn_conflict_cnt, 1);
//cflt = true;
#if DEBUG_TIMELINE
printf("CONFLICT %ld %ld\n",get_txn_id(),get_sys_clock());
#endif
return rc;
}
access->type = type;
access->orig_row = row;
#if ROLL_BACK && (CC_ALG == DL_DETECT || CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE || CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC)
if (type == WR) {
//printf("alloc 10 %ld\n",get_txn_id());
uint64_t part_id = row->get_part_id();
DEBUG_M("TxnManager::get_row row_t alloc\n")
row_pool.get(get_thd_id(),access->orig_data);
access->orig_data->init(row->get_table(), part_id, 0);
access->orig_data->copy(row);
assert(access->orig_data->get_schema() == row->get_schema());
// ARIES-style physiological logging
#if LOGGING
//LogRecord * record = logger.createRecord(LRT_UPDATE,L_UPDATE,get_txn_id(),part_id,row->get_table()->get_table_id(),row->get_primary_key());
LogRecord * record = logger.createRecord(get_txn_id(),L_UPDATE,row->get_table()->get_table_id(),row->get_primary_key());
if(g_repl_cnt > 0) {
msg_queue.enqueue(get_thd_id(),Message::create_message(record,LOG_MSG),g_node_id + g_node_cnt + g_client_node_cnt);
}
logger.enqueueRecord(record);
#endif
}
#endif
++txn->row_cnt;
if (type == WR)
++txn->write_cnt;
txn->accesses.add(access);
timespan = get_sys_clock() - starttime;
INC_STATS(get_thd_id(), txn_manager_time, timespan);
row_rtn = access->data;
if(CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC || CC_ALG == CALVIN)
assert(rc == RCOK);
return rc;
}
RC TxnManager::get_row_post_wait(row_t *& row_rtn) {
assert(CC_ALG != HSTORE && CC_ALG != HSTORE_SPEC);
uint64_t starttime = get_sys_clock();
row_t * row = this->last_row;
access_t type = this->last_type;
assert(row != NULL);
DEBUG_M("TxnManager::get_row_post_wait access alloc\n")
Access * access;
access_pool.get(get_thd_id(),access);
row->get_row_post_wait(type,this,access->data);
access->type = type;
access->orig_row = row;
#if ROLL_BACK && (CC_ALG == DL_DETECT || CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE)
if (type == WR) {
uint64_t part_id = row->get_part_id();
//printf("alloc 10 %ld\n",get_txn_id());
DEBUG_M("TxnManager::get_row_post_wait row_t alloc\n")
row_pool.get(get_thd_id(),access->orig_data);
access->orig_data->init(row->get_table(), part_id, 0);
access->orig_data->copy(row);
}
#endif
++txn->row_cnt;
if (type == WR)
++txn->write_cnt;
txn->accesses.add(access);
uint64_t timespan = get_sys_clock() - starttime;
INC_STATS(get_thd_id(), txn_manager_time, timespan);
this->last_row_rtn = access->data;
row_rtn = access->data;
return RCOK;
}
void TxnManager::insert_row(row_t * row, table_t * table) {
if (CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC)
return;
assert(txn->insert_rows.size() < MAX_ROW_PER_TXN);
txn->insert_rows.add(row);
}
itemid_t *
TxnManager::index_read(INDEX * index, idx_key_t key, int part_id) {
uint64_t starttime = get_sys_clock();
itemid_t * item;
index->index_read(key, item, part_id, get_thd_id());
uint64_t t = get_sys_clock() - starttime;
INC_STATS(get_thd_id(), txn_index_time, t);
//txn_time_idx += t;
return item;
}
itemid_t *
TxnManager::index_read(INDEX * index, idx_key_t key, int part_id, int count) {
uint64_t starttime = get_sys_clock();
itemid_t * item;
index->index_read(key, count, item, part_id);
uint64_t t = get_sys_clock() - starttime;
INC_STATS(get_thd_id(), txn_index_time, t);
//txn_time_idx += t;
return item;
}
RC TxnManager::validate() {
#if MODE != NORMAL_MODE
return RCOK;
#endif
if (CC_ALG != OCC && CC_ALG != MAAT && CC_ALG != WOOKONG) {
return RCOK;
}
RC rc = RCOK;
uint64_t starttime = get_sys_clock();
if(CC_ALG == OCC && rc == RCOK)
rc = occ_man.validate(this);
if(CC_ALG == MAAT && rc == RCOK) {
rc = maat_man.validate(this);
// Note: home node must be last to validate
if(IS_LOCAL(get_txn_id()) && rc == RCOK) {
rc = maat_man.find_bound(this);
}
}
if(CC_ALG == WOOKONG && rc == RCOK) {
rc = wkdb_man.validate(this);
// Note: home node must be last to validate
if(IS_LOCAL(get_txn_id()) && rc == RCOK) {
rc = wkdb_man.find_bound(this);
}
}
INC_STATS(get_thd_id(),txn_validate_time,get_sys_clock() - starttime);
return rc;
}
RC
TxnManager::send_remote_reads() {
assert(CC_ALG == CALVIN);
#if !YCSB_ABORT_MODE && WORKLOAD == YCSB
return RCOK;
#endif
assert(query->active_nodes.size() == g_node_cnt);
for(uint64_t i = 0; i < query->active_nodes.size(); i++) {
if(i == g_node_id)
continue;
if(query->active_nodes[i] == 1) {
DEBUG("(%ld,%ld) send_remote_read to %ld\n",get_txn_id(),get_batch_id(),i);
msg_queue.enqueue(get_thd_id(),Message::create_message(this,RFWD),i);
}
}
return RCOK;
}
bool TxnManager::calvin_exec_phase_done() {
bool ready = (phase == CALVIN_DONE) && (get_rc() != WAIT);
if(ready) {
DEBUG("(%ld,%ld) calvin exec phase done!\n",txn->txn_id,txn->batch_id);
}
return ready;
}
bool TxnManager::calvin_collect_phase_done() {
bool ready = (phase == CALVIN_COLLECT_RD) && (get_rsp_cnt() == calvin_expected_rsp_cnt);
if(ready) {
DEBUG("(%ld,%ld) calvin collect phase done!\n",txn->txn_id,txn->batch_id);
}
return ready;
}
void TxnManager::release_locks(RC rc) {
uint64_t starttime = get_sys_clock();
cleanup(rc);
uint64_t timespan = (get_sys_clock() - starttime);
INC_STATS(get_thd_id(), txn_cleanup_time, timespan);
}
| 28.698132 | 145 | 0.681902 | zhanhaozhao |
22386e73c247825f89ce2ead691d0f9f15e97948 | 3,536 | hpp | C++ | Include/Events/Receiver.hpp | igorlev91/DemoEngine | 8aaef0d3504826c9dcabe0a826a54613fca81c87 | [
"Apache-2.0"
] | null | null | null | Include/Events/Receiver.hpp | igorlev91/DemoEngine | 8aaef0d3504826c9dcabe0a826a54613fca81c87 | [
"Apache-2.0"
] | null | null | null | Include/Events/Receiver.hpp | igorlev91/DemoEngine | 8aaef0d3504826c9dcabe0a826a54613fca81c87 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Common/Debug.hpp"
#include "Events/Dispatcher.hpp"
#include "Events/Delegate.hpp"
// Forward declarations.
namespace Common
{
template<typename Type>
class DispatcherBase;
template<typename Type>
class ReceiverInvoker;
}
/*
Receiver
Invokes a delegate after receiving a signal from a dispatcher.
Single receiver instance can be subscribed to only one dispatcher.
See Dispatcher template class for more information.
*/
namespace Common
{
template<typename Type>
class Receiver;
template<typename ReturnType, typename... Arguments>
class Receiver<ReturnType(Arguments...)> : public Delegate<ReturnType(Arguments...)>
{
public:
// Friend declarations.
friend DispatcherBase<ReturnType(Arguments...)>;
friend ReceiverInvoker<ReturnType(Arguments...)>;
public:
// Constructor.
Receiver() :
m_dispatcher(nullptr),
m_previous(nullptr),
m_next(nullptr)
{
}
// Destructor.
virtual ~Receiver()
{
// Unsubscribe from the dispatcher.
this->Unsubscribe();
}
// Disallow copying.
Receiver(const Receiver& other) = delete;
Receiver& operator=(const Receiver& other) = delete;
// Move operations.
Receiver(Receiver&& other) :
Receiver()
{
// Call the assignment operator.
*this = std::move(other);
}
Receiver& operator=(Receiver&& other)
{
// Swap class members.
std::swap(m_dispatcher, other.m_dispatcher);
std::swap(m_previous, other.m_previous);
std::swap(m_next, other.m_next);
// Do not swap the underlying delegate.
// We only want to swap the dispatcher subscription.
return *this;
}
// Subscribes to a dispatcher.
bool Subscribe(DispatcherBase<ReturnType(Arguments...)>& dispatcher, bool unsubscribeReceiver = true)
{
return dispatcher.Subscribe(*this, unsubscribeReceiver);
}
// Unsubscribes from the current dispatcher.
void Unsubscribe()
{
if(m_dispatcher != nullptr)
{
m_dispatcher->Unsubscribe(*this);
ASSERT(m_dispatcher == nullptr, "Dispatcher did not unsubscribe this receiver properly!");
ASSERT(m_previous == nullptr, "Dispatcher did not unsubscribe this receiver properly!");
ASSERT(m_next == nullptr, "Dispatcher did not unsubscribe this receiver properly!");
}
}
private:
// Receives an event and invokes a bound function.
ReturnType Receive(Arguments... arguments)
{
ASSERT(m_dispatcher, "Invoked a receiver without it being subscribed!");
return this->Invoke(std::forward<Arguments>(arguments)...);
}
// Make derived invoke method private.
// We do not want other classes calling this.
ReturnType Invoke(Arguments... arguments)
{
return Delegate<ReturnType(Arguments...)>::Invoke(std::forward<Arguments>(arguments)...);
}
private:
// Intrusive double linked list element.
DispatcherBase<ReturnType(Arguments...)>* m_dispatcher;
Receiver<ReturnType(Arguments...)>* m_previous;
Receiver<ReturnType(Arguments...)>* m_next;
};
}
| 29.22314 | 109 | 0.595871 | igorlev91 |
22453f62f0865c998d1e6f2b5ba708fbfa6b2622 | 4,965 | cpp | C++ | example/distances.cpp | mjtrautmann/AnalyticalGeometry | 86213d68c5ecfc1b0743ab90b91f4e1cb42f7ca9 | [
"MIT"
] | null | null | null | example/distances.cpp | mjtrautmann/AnalyticalGeometry | 86213d68c5ecfc1b0743ab90b91f4e1cb42f7ca9 | [
"MIT"
] | null | null | null | example/distances.cpp | mjtrautmann/AnalyticalGeometry | 86213d68c5ecfc1b0743ab90b91f4e1cb42f7ca9 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2022 mjtrautmann
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
#include "../src/AnalyticalGeometry.h"
#include <iostream>
#include <cstdlib>
int main()
{
std::cout << "Exmples for Analytical Geometry Library" << std::endl;
{
analyticalgeom::Coordinate p0(0, 1, 0);
analyticalgeom::Coordinate p1(2, 1, 0);
analyticalgeom::Coordinate p2(1, 2, 1);
analyticalgeom::Coordinate p3(1, 2, 1.00001);
analyticalgeom::Coordinate p4(1, 2, 1.0000001);
std::cout << "The distance between " << p0 << " and " << p1 << " is " << (p1 - p0).length() << std::endl;
std::cout << "The distance between " << p0 << " and " << p2 << " is " << (p2-p0).length() << std::endl << std::endl;
std::cout << "The points " << p2 << " and " << p3 << " are " << ((p2==p3)? " identical " : " different ") << std::endl;
std::cout << "The points " << p2 << " and " << p4 << " are " << ((p2==p4)? " identical " : " different ") << std::endl;
analyticalgeom::Line line(p0, p1);
std::cout << "The line through point " << p0 << " and " << p1 << " is " << line << std::endl;
std::cout << "The projection of point " << p2 << " on line " << line << " is point " << analyticalgeom::AnalyticalGeometry::projection(line, p2) << std::endl;
std::cout << "The shortest distance between line " << line << " and point " << p2 << " is " << analyticalgeom::AnalyticalGeometry::distance(line, p2) << std::endl << std::endl;
analyticalgeom::Plane plane(p0, p1, p2);
std::cout << "The points " << p0 << ", " << p1 << " and " << p2 << " form the plane " << plane << std::endl;
std::cout << "The projection of " << p3 << " on the plane " << plane << " is " << analyticalgeom::AnalyticalGeometry::projection(plane, p3) << std::endl;
std::cout << "The distance between point " << p3 << " and plane " << plane << " is " << analyticalgeom::AnalyticalGeometry::distance(plane, p3) << std::endl << std::endl;
analyticalgeom::Plane plane2(p0 + plane.n(), plane.n());
std::cout << "The plane " << plane << " shifted in normal direction by 1 unit produces the plane " << plane2 << std::endl;
std::cout << "The planes are " << (analyticalgeom::AnalyticalGeometry::isParallel(plane, plane2) ? std::string("parallel") : std::string("not parallel")) << std::endl;
analyticalgeom::Plane plane3(p0, p1, p3);
std::cout << acrossb(plane.n(), plane3.n()) << std::endl;
std::cout << "The planes " << plane << " and " << plane3 << " are " << (analyticalgeom::AnalyticalGeometry::isParallel(plane, plane3) ? std::string("parallel") : std::string("not parallel")) << std::endl;
analyticalgeom::Plane plane4(p0, p1, p4);
std::cout << acrossb(plane.n(), plane4.n()) << std::endl;
std::cout << "The planes " << plane << " and " << plane4 << " are " << (analyticalgeom::AnalyticalGeometry::isParallel(plane, plane4) ? std::string("parallel") : std::string("not parallel")) << std::endl;
}
std::cout << std::endl << std::endl;
{
analyticalgeom::Coordinate2D p0(0, 1);
analyticalgeom::Coordinate2D p1(2, 1);
analyticalgeom::Coordinate2D p2(1, 2);
analyticalgeom::Coordinate2D p3(1, 2.01);
std::cout << "The distance between " << p0 << " and " << p1 << " is " << (p1 - p0).length() << std::endl;
std::cout << "The distance between " << p0 << " and " << p2 << " is " << (p2-p0).length() << std::endl << std::endl;
analyticalgeom::Line2D line(p0, p1);
std::cout << "The line through point " << p0 << " and " << p1 << " is " << line << std::endl;
std::cout << "The projection of point " << p2 << " on line " << line << " is point " << analyticalgeom::AnalyticalGeometry::projection(line, p2) << std::endl;
std::cout << "The shortest distance between line " << line << " and point " << p2 << " is " << analyticalgeom::AnalyticalGeometry::distance(line, p2) << std::endl << std::endl;
}
return 0;
} | 56.420455 | 207 | 0.622961 | mjtrautmann |
22470115de1902158dd1566b554579148025e1b7 | 1,925 | cpp | C++ | tests/unit/typegen_implicit.cpp | joyliu37/coreir | d7e68a1f17b8925965180e08dd5ecf9397bc057e | [
"BSD-3-Clause"
] | null | null | null | tests/unit/typegen_implicit.cpp | joyliu37/coreir | d7e68a1f17b8925965180e08dd5ecf9397bc057e | [
"BSD-3-Clause"
] | null | null | null | tests/unit/typegen_implicit.cpp | joyliu37/coreir | d7e68a1f17b8925965180e08dd5ecf9397bc057e | [
"BSD-3-Clause"
] | null | null | null | #include "coreir.h"
using namespace std;
using namespace CoreIR;
int main() {
Context* c = newContext();
Namespace* g = c->getGlobal();
//Declare an implicit TypeGenerator
TypeGen* tg = TypeGenImplicit::make(
g,
"add_type", //name for the typegen
{{"width",c->Int()}} //generater parameters
);
Generator* add = g->newGeneratorDecl("add",tg,{{"width",c->Int()}});
{
Module* m5 = add->getModule(
{{"width",Const::make(c,5)}},
c->Record({
{"in0",c->BitIn()->Arr(5)},
{"in1",c->BitIn()->Arr(5)},
{"out",c->Bit()->Arr(5)}
})
);
ModuleDef* def = m5->newModuleDef();
def->addInstance("i0","coreir.add",{{"width",Const::make(c,5)}});
def->connect("self","i0");
}
{
Module* m9 = add->getModule(
{{"width",Const::make(c,9)}},
c->Record({
{"in0",c->BitIn()->Arr(9)},
{"in1",c->BitIn()->Arr(9)},
{"out",c->Bit()->Arr(9)}
})
);
ModuleDef* def = m9->newModuleDef();
def->addInstance("i0","coreir.add",{{"width",Const::make(c,9)}});
def->connect("self","i0");
}
// Define Add12 Module
Module* top = g->newModuleDecl("top",c->Record());
ModuleDef* def = top->newModuleDef();
def->addInstance("add5","global.add",{{"width",Const::make(c,5)}});
def->addInstance("add9","global.add",{{"width",Const::make(c,9)}});
top->setDef(def);
top->print();
cout << "Checking saving and loading postgen" << endl;
if (!saveToFile(g, "_typegen_implicit.json",top)) {
cout << "Could not save to json!!" << endl;
c->die();
}
deleteContext(c);
c = newContext();
top = nullptr;
if (!loadFromFile(c,"_typegen_implicit.json", &top)) {
cout << "Could not Load from json!!" << endl;
c->die();
}
ASSERT(top, "Could not load top: typegen_implicit");
top->print();
c->runPasses({"rungenerators","flatten"});
top->print();
}
| 23.765432 | 71 | 0.54961 | joyliu37 |
2249453ec0f3b2c4062157997d230cd6a0a13a14 | 1,965 | cc | C++ | stack/basic_calculator.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | stack/basic_calculator.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | stack/basic_calculator.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <stack>
#include <string>
#include <cctype>
#include <iostream>
#include <cassert>
using namespace std;
class Solution {
public:
int calculate(string s) {
stack<int> signs;
// signs record the predefine sign: signs*1()
signs.push(1);
// treat a as (a)
int sign = 1;
int accum = 0;
int num = 0;
s.push_back(')');
for (auto c : s) {
if (c == '+' || c == '-') {
accum += num * sign * signs.top();
sign = c == '+' ? 1 : -1;
num = 0;
} else if (c == '(') {
// flip signs if neccesary
signs.push(sign * signs.top());
sign = 1;
} else if (c == ')') {
// calcuate the result if necessary
accum += num * sign * signs.top();
signs.pop();
sign = 1;
num = 0;
} else if (isdigit(c)) {
num = num * 10 + c - '0';
} else if (c == ' ') {
continue;
} else {
// unreachable
return 0;
}
}
return accum;
}
};
int main() {
vector<string> test_cases = {
"0",
"10",
"5+2-3",
"8-(3+5)+(3+2)",
"(10)+2",
"1-(100+3-2+4-3)",
"10+32-(3+2-4+44-33)+(22+3-21+3)-(3232+333-222)+3-32-21-2",
" 30",
"(3-(2-(5-(9-(4)))))"
};
vector<int> results = {
0,
10,
4,
5,
12,
-101,
-3358,
30,
1
};
Solution s;
for (int i = 0; i < static_cast<int>(test_cases.size()); ++i) {
// cout << "calculated: " << s.calculate(test_cases[i]) << ", real: " <<results[i] << endl;
assert(s.calculate(test_cases[i]) == results[i]);
}
cout << "You Passed" << endl;
return 0;
}
| 23.392857 | 99 | 0.384733 | windscope |
224ade0e0f904ae17016aff23a2c3b0951c699de | 6,158 | cc | C++ | chainerx_cc/chainerx/array_body.cc | tkerola/chainer | 572f6eef2c3f1470911ac08332c2b5c3440edf44 | [
"MIT"
] | 1 | 2021-02-26T10:27:25.000Z | 2021-02-26T10:27:25.000Z | chainerx_cc/chainerx/array_body.cc | hitsgub/chainer | 20d4d70f5cdacc1f24f243443f5bebc2055c8f8e | [
"MIT"
] | null | null | null | chainerx_cc/chainerx/array_body.cc | hitsgub/chainer | 20d4d70f5cdacc1f24f243443f5bebc2055c8f8e | [
"MIT"
] | 2 | 2019-07-16T00:24:47.000Z | 2021-02-26T10:27:27.000Z | #include "chainerx/array_body.h"
#include <algorithm>
#include <cstdint>
#include <memory>
#include <utility>
#include "chainerx/array.h"
#include "chainerx/array_body_leak_detection.h"
#include "chainerx/array_node.h"
#include "chainerx/backward.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/graph.h"
#include "chainerx/macro.h"
namespace chainerx {
namespace internal {
std::shared_ptr<ArrayBody> CreateArrayBody(
const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset) {
// Trick to use make_shared with private ctor
struct ArrayBodyWithPublicCtor : ArrayBody {
ArrayBodyWithPublicCtor(
const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset)
: ArrayBody{shape, strides, dtype, device, std::move(data), offset} {}
};
std::shared_ptr<ArrayBody> array_body =
std::make_shared<ArrayBodyWithPublicCtor>(shape, strides, dtype, device, std::move(data), offset);
if (internal::ArrayBodyLeakTracker* tracker = internal::ArrayBodyLeakDetectionScope::GetGlobalTracker()) {
// TODO(niboshi): Make thread-safe
(*tracker)(array_body);
}
return array_body;
}
std::shared_ptr<ArrayBody> CreateArrayBody(ArrayBody::Params params) {
return CreateArrayBody(params.shape, params.strides, params.dtype, params.device, std::move(params.data), params.offset);
}
const std::shared_ptr<ArrayNode> ArrayBody::kNullArrayNode{nullptr};
ArrayBody::ArrayBody(
const Shape& shape, // NOLINT(modernize-pass-by-value)
const Strides& strides, // NOLINT(modernize-pass-by-value)
Dtype dtype,
Device& device,
std::shared_ptr<void> data,
int64_t offset)
: shape_{shape}, strides_{strides}, dtype_{dtype}, device_{device}, data_{std::move(data)}, offset_{offset} {}
ArrayBody::ArrayBody(Params params)
: ArrayBody{params.shape, params.strides, params.dtype, params.device, std::move(params.data), params.offset} {}
const std::shared_ptr<ArrayNode>& ArrayBody::AddNode(const std::shared_ptr<ArrayBody>& body, std::shared_ptr<ArrayNode> array_node) {
body->AssertConsistency();
// The body must be either unset (the array node is being created normally) or dead (the body is being replaced with a fabricated one,
// as a retained output of backward)
CHAINERX_ASSERT(array_node->weak_body().expired());
auto it = std::find_if(body->nodes_.begin(), body->nodes_.end(), [&array_node](const std::shared_ptr<ArrayNode>& existing_node) {
return existing_node->backprop_id() == array_node->backprop_id();
});
if (it != body->nodes_.end()) {
return *it; // Do nothing and return the existing ArrayNode if found for this graph.
}
// Connect the new backprop ID and the existing backprop IDs in this array body.
for (const std::shared_ptr<ArrayNode>& existing_array_node : body->nodes_) {
existing_array_node->device().context().ConnectBackpropIds(existing_array_node->backprop_id(), array_node->backprop_id());
}
array_node->weak_body_ = body;
body->nodes_.emplace_back(std::move(array_node));
body->grads_.emplace_back(std::make_unique<nonstd::optional<Array>>(nonstd::nullopt));
body->AssertConsistency();
return body->nodes_.back();
}
const std::shared_ptr<ArrayNode>& ArrayBody::CreateArrayNode(const std::shared_ptr<ArrayBody>& body, const BackpropId& backprop_id) {
CHAINERX_ASSERT(GetKind(body->dtype()) == DtypeKind::kFloat);
return AddNode(body, std::make_shared<ArrayNode>(body->shape_, body->dtype_, body->device_, backprop_id));
}
void ArrayBody::AssertConsistency() const {
if (CHAINERX_DEBUG) {
// Array with integral dtypes can neither have array nodes nor gradients.
if (GetKind(dtype()) != DtypeKind::kFloat) {
CHAINERX_ASSERT(nodes_.empty());
CHAINERX_ASSERT(grads_.empty());
}
CHAINERX_ASSERT(nodes_.size() == grads_.size());
for (size_t i = 0; i < nodes_.size(); ++i) {
const std::shared_ptr<ArrayNode>& array_node = nodes_[i];
const nonstd::optional<Array>& grad = *grads_[i];
CHAINERX_ASSERT(array_node != nullptr);
CHAINERX_ASSERT(this == array_node->weak_body().lock().get());
if (grad.has_value()) {
CHAINERX_ASSERT(internal::GetArrayBody(*grad) != nullptr);
CHAINERX_ASSERT(grad->shape() == array_node->shape());
CHAINERX_ASSERT(grad->dtype() == array_node->dtype());
CHAINERX_ASSERT(&grad->device() == &array_node->device());
}
}
}
}
nonstd::optional<size_t> ArrayBody::GetNodeIndex(const BackpropId& backprop_id) const {
for (size_t i = 0; i < nodes_.size(); ++i) {
if (nodes_[i]->backprop_id() == backprop_id) {
return i;
}
}
return nonstd::nullopt;
}
void ArrayBody::SetGrad(Array grad, const BackpropId& backprop_id) {
nonstd::optional<Array>* target_grad = GetGrad(backprop_id);
CHAINERX_ASSERT(target_grad != nullptr);
internal::SetGrad(*target_grad, std::move(grad), shape_, dtype_, device_);
}
void ArrayBody::ClearGrad(const BackpropId& backprop_id) {
nonstd::optional<Array>* grad = GetGrad(backprop_id);
CHAINERX_ASSERT(grad != nullptr);
grad->reset();
}
template <typename ThisPtr, typename ReturnType>
ReturnType ArrayBody::GetGradImpl(ThisPtr this_ptr, const BackpropId& backprop_id) {
nonstd::optional<size_t> i = this_ptr->GetNodeIndex(backprop_id);
if (!i.has_value()) {
return nullptr;
}
CHAINERX_ASSERT(*i < this_ptr->grads_.size());
return this_ptr->grads_[*i].get();
}
template nonstd::optional<Array>* ArrayBody::GetGradImpl<ArrayBody*, nonstd::optional<Array>*>(ArrayBody*, const BackpropId&);
template const nonstd::optional<Array>* ArrayBody::GetGradImpl<const ArrayBody*, const nonstd::optional<Array>*>(
const ArrayBody*, const BackpropId&);
} // namespace internal
} // namespace chainerx
| 40.248366 | 138 | 0.683014 | tkerola |
224e8bd287ec00157d536cc395b5589a0d0d0fe7 | 2,412 | cc | C++ | src/cpu/backend.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/cpu/backend.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/cpu/backend.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | #include "backend.h"
#ifdef CT2_WITH_MKL
# include <mkl.h>
#endif
#include "ctranslate2/utils.h"
#include "cpu_info.h"
namespace ctranslate2 {
namespace cpu {
#ifdef CT2_WITH_MKL
static inline bool mkl_has_fast_int_gemm() {
# if __INTEL_MKL__ > 2019 || (__INTEL_MKL__ == 2019 && __INTEL_MKL_UPDATE__ >= 5)
// Intel MKL 2019.5 added optimized integers GEMM for SSE4.2 and AVX (in addition to
// the existing AVX2 and AVX512), so it is virtually optimized for all target platforms.
return true;
# else
return mkl_cbwr_get_auto_branch() >= MKL_CBWR_AVX2;
# endif
}
#endif
static bool mayiuse_mkl_init() {
const std::string use_mkl_env = read_string_from_env("CT2_USE_MKL");
if (use_mkl_env.empty()) {
#ifdef CT2_WITH_MKL
return cpu_is_intel();
#else
return false;
#endif
} else {
const bool use_mkl = string_to_bool(use_mkl_env);
#ifndef CT2_WITH_MKL
if (use_mkl)
throw std::invalid_argument("This CTranslate2 binary was not compiled with Intel MKL");
#endif
return use_mkl;
}
}
bool mayiuse_mkl() {
static const bool mayiuse = mayiuse_mkl_init();
return mayiuse;
}
std::string gemm_backend_to_str(GemmBackend gemm_backend) {
switch (gemm_backend) {
case GemmBackend::MKL:
return "MKL";
case GemmBackend::DNNL:
return "DNNL";
default:
return "NONE";
}
}
GemmBackend get_gemm_backend(ComputeType compute_type) {
#ifdef CT2_WITH_DNNL
if (!mayiuse_mkl()) {
if (compute_type != ComputeType::INT16)
return GemmBackend::DNNL;
else
return GemmBackend::NONE;
}
#endif
#ifdef CT2_WITH_MKL
if (compute_type == ComputeType::FLOAT || mkl_has_fast_int_gemm()) {
return GemmBackend::MKL;
}
#endif
return GemmBackend::NONE;
}
bool has_gemm_backend(ComputeType compute_type) {
return get_gemm_backend(compute_type) != GemmBackend::NONE;
}
bool prefer_u8s8s32_gemm() {
const auto gemm_s8_backend = get_gemm_backend(ComputeType::INT8);
return gemm_s8_backend == cpu::GemmBackend::MKL || gemm_s8_backend == cpu::GemmBackend::DNNL;
}
bool should_pack_gemm_weights() {
static const bool should_pack = read_bool_from_env("CT2_USE_EXPERIMENTAL_PACKED_GEMM");
return should_pack;
}
}
}
| 25.935484 | 99 | 0.660862 | aj7tesh |
224f46a12acd0c706f28ddfe9f6303cc7363e10d | 7,332 | cpp | C++ | src/mapclear.cpp | SenhorGatinho/kale | a4e1819c568c3925cd7e94a8b06608e1c233ebf9 | [
"MIT"
] | 32 | 2015-03-02T05:40:42.000Z | 2022-02-21T04:13:02.000Z | src/mapclear.cpp | SenhorGatinho/kale | a4e1819c568c3925cd7e94a8b06608e1c233ebf9 | [
"MIT"
] | null | null | null | src/mapclear.cpp | SenhorGatinho/kale | a4e1819c568c3925cd7e94a8b06608e1c233ebf9 | [
"MIT"
] | 3 | 2017-02-03T05:01:51.000Z | 2022-01-10T01:38:13.000Z | #include "mapclear.h"
#include "romfile.h"
#include "level.h"
#include <cstdint>
#include <cstdio>
#include <QSpinBox>
std::vector<QRect> mapClearData[7][16];
const romaddr_t ptrMapClearL = {0x12, 0x9C7E};
const romaddr_t ptrMapClearH = {0x12, 0x9CEE};
const uint ptrMapClearB = 0x12;
const romaddr_t mapClearStart = {0x12, 0x9D5E};
void loadMapClearData(ROMFile& rom, uint map, uint width) {
for (uint level = 0; level < 16; level++) {
mapClearData[map][level].clear();
uint8_t bytes[4] = {0};
romaddr_t addr = rom.readShortPointer(ptrMapClearL, ptrMapClearH, ptrMapClearB,
(map * 16) + level);
if (!addr.addr) continue;
do {
rom.readBytes(addr, 4, bytes);
addr.addr += 4;
uint screen = bytes[0] & 0xF;
uint x = (screen % width * SCREEN_WIDTH) + (bytes[1] & 0xF);
uint y = (screen / width * SCREEN_HEIGHT) + (bytes[1] >> 4);
mapClearData[map][level].push_back(QRect(x, y, bytes[2], bytes[3]));
} while (bytes[0] < 0x80);
}
}
void saveMapClearData(ROMFile& rom, const leveldata_t *levelData, uint num) {
romaddr_t addr = mapClearStart;
// get address to write clear data to based on how many rects were written
// for previous levels
for (uint map = 0; map < num; map++)
for (uint level = 0; level < 0x10; level++)
addr.addr += 4 * mapClearData[map][level].size();
for (uint level = 0; level < 0x10; level++) {
std::vector<QRect>& rects = mapClearData[num][level];
if (!rects.size()) {
rom.writeToShortPointer(ptrMapClearL, ptrMapClearH, {0, 0}, 0, NULL, num * 16 + level);
continue;
}
rom.writeToShortPointer(ptrMapClearL, ptrMapClearH, addr, 0, NULL, num * 16 + level);
uint numRects = rects.size();
for (std::vector<QRect>::const_iterator i = rects.begin(); i != rects.end(); i++) {
uint8_t bytes[4];
// byte 0: screen
bytes[0] = (i->y() / SCREEN_HEIGHT * levelData->header.screensH)
+ (i->x() / SCREEN_WIDTH);
// and last rect flag
if (--numRects == 0)
bytes[0] |= 0x80;
// byte 1: Y/X coords
bytes[1] = ((i->y() % SCREEN_HEIGHT) << 4) | (i->x() % SCREEN_WIDTH);
// bytes 2-3: width/height
bytes[2] = i->width();
bytes[3] = i->height();
// write it
rom.writeBytes(addr, 4, bytes);
addr.addr += 4;
}
}
}
MapClearDelegate::MapClearDelegate(QObject *parent) :
QItemDelegate(parent)
{}
QWidget* MapClearDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem&, const QModelIndex& index) const {
QSpinBox *editor = new QSpinBox(parent);
int col = index.column();
editor->setMinimum(0);
switch (col) {
case MapClearModel::columnX:
editor->setMaximum(16 * SCREEN_WIDTH - 1);
break;
case MapClearModel::columnY:
editor->setMaximum(16 * SCREEN_HEIGHT - 1);
break;
default:
editor->setMaximum(255);
break;
}
return editor;
}
void MapClearDelegate::setEditorData(QWidget *editor, const QModelIndex& index) const {
int val = index.model()->data(index).toInt();
QSpinBox *box = static_cast<QSpinBox*>(editor);
box->setValue(val);
}
void MapClearDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex& index) const {
QSpinBox *box = static_cast<QSpinBox*>(editor);
box->interpretText();
model->setData(index, box->value());
}
void MapClearDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem& option, const QModelIndex &) const {
editor->setGeometry(option.rect);
}
MapClearModel::MapClearModel(QObject *parent) :
QAbstractTableModel(parent),
level(0),
rects(NULL)
{}
int MapClearModel::rowCount(const QModelIndex&) const {
// return number of rects for this stage
if (rects)
return rects->size();
return 0;
}
int MapClearModel::columnCount(const QModelIndex&) const {
return 4;
}
Qt::ItemFlags MapClearModel::flags(const QModelIndex&) const {
return Qt::ItemIsEnabled
| Qt::ItemIsSelectable
| Qt::ItemIsEditable;
}
QVariant MapClearModel::data(const QModelIndex& index, int role) const {
switch (role) {
case Qt::DisplayRole:
if (!rects)
return 0;
int col = index.column();
int row = index.row();
QRect rect = rects->at(row);
switch (col) {
case columnX:
return rect.x();
case columnY:
return rect.y();
case columnWidth:
return rect.width();
case columnHeight:
return rect.height();
default:
return QVariant();
}
break;
}
return QVariant();
}
QVariant MapClearModel::headerData(int section, Qt::Orientation orientation, int role) const {
switch (role) {
case Qt::DisplayRole:
if (orientation == Qt::Horizontal) {
switch (section) {
case columnX:
return QString("X");
case columnY:
return QString("Y");
case columnWidth:
return QString("Width");
case columnHeight:
return QString("Height");
default:
return QVariant();
}
} else {
return section + 1;
}
break;
}
return QVariant();
}
bool MapClearModel::setData(const QModelIndex &index, const QVariant &value, int role) {
if (role == Qt::EditRole) {
int row = index.row();
int col = index.column();
QRect& rect = rects->at(row);
bool ok;
uint val = value.toUInt(&ok);
if (!ok) return false;
switch (col) {
case columnX:
rect.moveLeft(val);
break;
case columnY:
rect.moveTop(val);
break;
case columnWidth:
rect.setWidth(val);
break;
case columnHeight:
rect.setHeight(val);
break;
default:
return false;
}
emit dataChanged(index, index);
return true;
}
return false;
}
bool MapClearModel::insertRow(int row, const QModelIndex &parent) {
if (rects && (uint)row < rects->size()) {
beginInsertRows(parent, row, row);
rects->insert(rects->begin() + row, QRect());
endInsertRows();
return true;
} else if (rects) {
beginInsertRows(parent, row, row);
rects->push_back(QRect());
endInsertRows();
return true;
}
return false;
}
bool MapClearModel::removeRow(int row, const QModelIndex &parent) {
if (rects && (uint)row < rects->size()) {
beginRemoveRows(parent, row, row);
rects->erase(rects->begin() + row);
endRemoveRows();
return true;
}
return false;
}
void MapClearModel::setRects(std::vector<QRect> *newRects) {
if (newRects) {
beginResetModel();
rects = newRects;
endResetModel();
}
}
| 25.109589 | 125 | 0.563557 | SenhorGatinho |
2254e220fb9dcba2d2970100b007d57cf6fe7e40 | 4,801 | cpp | C++ | src/World.cpp | aebarber/LD41 | 9501e3bd4de5e617a36f4065f4e6ab3f898abe4c | [
"MIT"
] | null | null | null | src/World.cpp | aebarber/LD41 | 9501e3bd4de5e617a36f4065f4e6ab3f898abe4c | [
"MIT"
] | null | null | null | src/World.cpp | aebarber/LD41 | 9501e3bd4de5e617a36f4065f4e6ab3f898abe4c | [
"MIT"
] | null | null | null | #include "../include/World.hpp"
World::World () {
m_grassTexture.loadFromImage(*aw::AssetStore::getImage("grass"));
m_gravelTexture.loadFromImage(*aw::AssetStore::getImage("gravel"));
m_waterTexture.loadFromImage(*aw::AssetStore::getImage("water"));
m_mudTexture.loadFromImage(*aw::AssetStore::getImage("mud"));
m_bushTexture.loadFromImage(*aw::AssetStore::getImage("bush"));
m_treeTexture.loadFromImage(*aw::AssetStore::getImage("tree"));
m_mountainTexture.loadFromImage(*aw::AssetStore::getImage("mountain"));
m_grassPrinter = sf::Sprite(m_grassTexture);
m_gravelPrinter = sf::Sprite(m_gravelTexture);
m_waterPrinter = sf::Sprite(m_waterTexture);
m_mudPrinter = sf::Sprite(m_mudTexture);
m_bushPrinter = sf::Sprite(m_bushTexture);
m_treePrinter = sf::Sprite(m_treeTexture);
m_mountainPrinter = sf::Sprite(m_mountainTexture);
m_player = std::make_unique<Player>(this);
generateTerrain();
}
Player* World::getPlayer () {
return m_player.get();
}
void setCamera (double x, double y) {
m_cameraX = x;
m_cameraY = y;
}
void moveCamera (double x, double y) {
m_cameraX += x;
m_cameraY += y;
}
void World::render () {
auto size = Window::getContext()->getSize();
double centerX = size.x * 0.5;
double centerY = size.y * 0.5;
double topLeftCoordinateX = cameraX - centerX;
double topLeftCoordinateY = cameraY - centerY;
double bottomRightCoordinateX = cameraX + centerX;
double bottomRightCoordinateY = cameraY + centerY;
auto topLeftTileX = static_cast<unsigned int>(topLeftCoordinateX / 32.0);
auto topLeftTileY = static_cast<unsigned int>(topLeftCoordinateY / 32.0);
auto bottomRightTileX = static_cast<unsigned int>(bottomRightCoordinateX / 32.0);
auto bottomRightTileY = static_cast<unsigned int>(bottomRightCoordinateY / 32.0);
double topLeftTileTopLeftCoordinateX = static_cast<double>(topLeftCoordinateX) * 32.0;
double topLeftTileTopLeftCoordinateY = static_cast<double>(topLeftCoordinateY) * 32.0;
for (unsigned int y = topLeftTileY; y < bottomRightTileY; ++y) {
for (unsigned int x = topLeftTileX; x < bottomRightTileX; ++x) {
switch (m_tilePlane.get(x, y)) {
case TileType::Grass:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Gravel:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Water:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Mud:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Bush:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Tree:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Mountain:\
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Player:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Enemy:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
case TileType::Target:
m_grassSprite.setPosition(topLeftTileTopLeftCoordinateX - topLeftCoordinateX + (32 * (x - topLeftTileX)), topLeftTileTopLeftCoordinateY - topLeftCoordinateY + (32 * (y - topLeftTileY)));
default:
break;
}
}
}
}
| 42.486726 | 206 | 0.676317 | aebarber |
225e95d5ffaf77e76ad6478fe5bc386ae7f65369 | 626 | cpp | C++ | main.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | 3 | 2019-02-23T18:20:24.000Z | 2019-02-23T18:30:18.000Z | main.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | null | null | null | main.cpp | ArionasMC/TicTacToe | 998585ca415c7d263eeb73e43840fbf98d9a4c99 | [
"Apache-2.0"
] | null | null | null | #include "SDL.h"
#include "Game.h"
#include <iostream>
using namespace std;
Game *game = NULL;
int main(int argc, char *argv[])
{
const int FPS = 60;
const int frameDelay = 1000 / FPS;
Uint32 frameStart;
int frameTime;
game = new Game();
game->init("Tic Tac Toe", 800, 600, false);
while (game->running())
{
frameStart = SDL_GetTicks();
game->handleEvents();
game->update();
game->render();
frameTime = SDL_GetTicks() - frameStart;
if(frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
game->clean();
return 0;
}
| 16.473684 | 47 | 0.58147 | ArionasMC |
2263755966a7c0b1957e2537bbd6211cdab7d85a | 3,413 | cpp | C++ | sources/applications/livertmpdissector/src/rawtcpappprotocolhandler.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 3 | 2020-07-30T19:41:00.000Z | 2020-10-28T12:52:37.000Z | sources/applications/livertmpdissector/src/rawtcpappprotocolhandler.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | null | null | null | sources/applications/livertmpdissector/src/rawtcpappprotocolhandler.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 2 | 2020-05-11T03:19:00.000Z | 2021-07-07T17:40:47.000Z | /**
##########################################################################
# If not stated otherwise in this file or this component's LICENSE
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# 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 "rawtcpappprotocolhandler.h"
#include "protocols/baseprotocol.h"
#include "session.h"
#include "livertmpdissectorapplication.h"
#include "protocolfactory.h"
#include "application/clientapplicationmanager.h"
using namespace app_livertmpdissector;
RawTcpAppProtocolHandler::RawTcpAppProtocolHandler(Variant &configuration)
: BaseAppProtocolHandler(configuration) {
}
RawTcpAppProtocolHandler::~RawTcpAppProtocolHandler() {
}
void RawTcpAppProtocolHandler::RegisterProtocol(BaseProtocol *pProtocol) {
Variant ¶meters = pProtocol->GetCustomParameters();
if (parameters.HasKeyChain(V_BOOL, true, 1, "isOutbound")&&((bool)parameters["isOutbound"])) {
} else {
if (!CreateSession(pProtocol)) {
FATAL("Unable to create session");
pProtocol->EnqueueForDelete();
}
}
}
void RawTcpAppProtocolHandler::UnRegisterProtocol(BaseProtocol *pProtocol) {
if (pProtocol == NULL)
return;
Session *pSession = Session::GetSession(
pProtocol->GetCustomParameters()["sessionId"]);
if (pSession != NULL)
delete pSession;
}
bool RawTcpAppProtocolHandler::SignalProtocolCreated(BaseProtocol *pProtocol, Variant ¶meters) {
if (pProtocol == NULL)
return false;
BaseClientApplication *pApp = ClientApplicationManager::FindAppById(parameters["appId"]);
if (pApp == NULL) {
pProtocol->EnqueueForDelete();
FATAL("Application not found");
return false;
}
Session *pSession = Session::GetSession(parameters["sessionId"]);
if (pSession == NULL) {
pProtocol->EnqueueForDelete();
FATAL("Session not found");
return false;
}
pProtocol->SetOutboundConnectParameters(parameters);
pProtocol->SetApplication(pApp);
pSession->OutboundProtocolId(pProtocol);
return true;
}
bool RawTcpAppProtocolHandler::CreateSession(BaseProtocol *pInbound) {
Session *pSession = new Session(_configuration, GetApplication());
Variant ¶meters = pInbound->GetCustomParameters();
parameters["sessionId"] = pSession->GetId();
pSession->InboundProtocolId(pInbound);
LiveRTMPDissectorApplication *pApp = (LiveRTMPDissectorApplication *) GetApplication();
Variant connectParams;
connectParams["appId"] = pApp->GetId();
connectParams["sessionId"] = pSession->GetId();
connectParams["isOutbound"] = (bool)true;
vector<uint64_t> chain = ProtocolFactoryManager::ResolveProtocolChain("rawTcp");
if (chain.size() == 0) {
FATAL("Unable to resolve protocol chain rawTcp");
return false;
}
return TCPConnector<RawTcpAppProtocolHandler>::Connect(
pApp->GetTargetIp(),
pApp->GetTargetPort(),
chain,
connectParams
);
}
| 30.20354 | 100 | 0.726047 | rdkcmf |
226737397de0b16688a5798449b86f3abf42e80d | 6,083 | cpp | C++ | Algorithm/arcsim/adaptiveCloth/constraint.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 32 | 2016-12-13T05:49:12.000Z | 2022-02-04T06:15:47.000Z | Algorithm/arcsim/adaptiveCloth/constraint.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 2 | 2019-07-30T02:01:16.000Z | 2020-03-12T15:06:51.000Z | Algorithm/arcsim/adaptiveCloth/constraint.cpp | dolphin-li/ClothDesigner | 82b186d6db320b645ac67a4d32d7746cc9bdd391 | [
"MIT"
] | 18 | 2017-11-16T13:37:06.000Z | 2022-03-11T08:13:46.000Z | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "constraint.hpp"
#include "cloth\LevelSet3D.h"
#include "magic.hpp"
using namespace std;
namespace arcsim
{
double EqCon::value(int *sign)
{
if (sign) *sign = 0;
return dot(n, node->x - x);
}
MeshGrad EqCon::gradient() { MeshGrad grad; grad[node] = n; return grad; }
MeshGrad EqCon::project() { return MeshGrad(); }
double EqCon::energy(double value) { return stiff*sq(value) / 2.; }
double EqCon::energy_grad(double value) { return stiff*value; }
double EqCon::energy_hess(double value) { return stiff; }
MeshGrad EqCon::friction(double dt, MeshHess &jac) { return MeshGrad(); }
double GlueCon::value(int *sign)
{
if (sign) *sign = 0;
return dot(n, nodes[1]->x - nodes[0]->x);
}
MeshGrad GlueCon::gradient()
{
MeshGrad grad;
grad[nodes[0]] = -n;
grad[nodes[1]] = n;
return grad;
}
MeshGrad GlueCon::project() { return MeshGrad(); }
double GlueCon::energy(double value) { return stiff*sq(value) / 2.; }
double GlueCon::energy_grad(double value) { return stiff*value; }
double GlueCon::energy_hess(double value) { return stiff; }
MeshGrad GlueCon::friction(double dt, MeshHess &jac) { return MeshGrad(); }
double IneqCon::value(int *sign)
{
if (sign)
*sign = 1;
double d = 0;
for (int i = 0; i < 4; i++)
d += w[i] * dot(n, nodes[i]->x);
d -= arcsim::magic.repulsion_thickness;
return d;
}
MeshGrad IneqCon::gradient()
{
MeshGrad grad;
for (int i = 0; i < 4; i++)
grad[nodes[i]] = w[i] * n;
return grad;
}
MeshGrad IneqCon::project()
{
double d = value() + arcsim::magic.repulsion_thickness - arcsim::magic.projection_thickness;
if (d >= 0)
return MeshGrad();
double inv_mass = 0;
for (int i = 0; i < 4; i++)
if (free[i])
inv_mass += sq(w[i]) / nodes[i]->m;
MeshGrad dx;
for (int i = 0; i < 4; i++)
if (free[i])
dx[nodes[i]] = -(w[i] / nodes[i]->m) / inv_mass*n*d;
return dx;
}
double violation(double value) { return std::max(-value, 0.); }
double IneqCon::energy(double value)
{
double v = violation(value);
return stiff*v*v*v / arcsim::magic.repulsion_thickness / 6;
}
double IneqCon::energy_grad(double value)
{
return -stiff*sq(violation(value)) / arcsim::magic.repulsion_thickness / 2;
}
double IneqCon::energy_hess(double value)
{
return stiff*violation(value) / arcsim::magic.repulsion_thickness;
}
MeshGrad IneqCon::friction(double dt, MeshHess &jac)
{
if (mu == 0)
return MeshGrad();
double fn = abs(energy_grad(value()));
if (fn == 0)
return MeshGrad();
Vec3 v = Vec3(0);
double inv_mass = 0;
for (int i = 0; i < 4; i++)
{
v += w[i] * nodes[i]->v;
if (free[i])
inv_mass += sq(w[i]) / nodes[i]->m;
}
Mat3x3 T = Mat3x3(1) - outer(n, n);
double vt = norm(T*v);
double f_by_v = std::min(mu*fn / vt, 1 / (dt*inv_mass));
// double f_by_v = mu*fn/max(vt, 1e-1);
MeshGrad force;
for (int i = 0; i < 4; i++)
{
if (free[i])
{
force[nodes[i]] = -w[i] * f_by_v*T*v;
for (int j = 0; j < 4; j++)
{
if (free[j])
{
jac[make_pair(nodes[i], nodes[j])] = -w[i] * w[j] * f_by_v*T;
}
}
}
}
return force;
}
/////////////////////////////////////////////////////////////////////////////
double IneqConLvSet::value(int *sign)
{
if (sign)
*sign = 1;
double d = obj->globalValue(node->x[0], node->x[1], node->x[2]);
d -= arcsim::magic.repulsion_thickness;
return d;
}
MeshGrad IneqConLvSet::gradient()
{
MeshGrad grad;
grad[node] = n;
return grad;
}
MeshGrad IneqConLvSet::project()
{
double d = value() + arcsim::magic.repulsion_thickness - arcsim::magic.projection_thickness;
if (d >= 0)
return MeshGrad();
double inv_mass = 0;
if (free)
inv_mass += 1 / node->m;
MeshGrad dx;
if (free)
{
dx[node] = -(1 / node->m) / inv_mass*n*d;
}
return dx;
}
double IneqConLvSet::energy(double value)
{
double v = violation(value);
return stiff*v*v*v / arcsim::magic.repulsion_thickness / 6;
}
double IneqConLvSet::energy_grad(double value)
{
return -stiff*sq(violation(value)) / arcsim::magic.repulsion_thickness / 2;
}
double IneqConLvSet::energy_hess(double value)
{
return stiff*violation(value) / arcsim::magic.repulsion_thickness;
}
MeshGrad IneqConLvSet::friction(double dt, MeshHess &jac)
{
if (mu == 0)
return MeshGrad();
double fn = abs(energy_grad(value()));
if (fn == 0)
return MeshGrad();
Vec3 v = Vec3(0);
double inv_mass = 0;
v += node->v;
if (free)
inv_mass += 1 / node->m;
Mat3x3 T = Mat3x3(1) - outer(n, n);
double vt = norm(T*v);
double f_by_v = std::min(mu*fn / vt, 1 / (dt*inv_mass));
// double f_by_v = mu*fn/max(vt, 1e-1);
MeshGrad force;
if (free)
{
force[node] = -f_by_v*T*v;
jac[make_pair(node, node)] = -f_by_v*T;
}
return force;
}
} | 27.278027 | 94 | 0.644583 | dolphin-li |
226b322b2b0aae123a65e38fa7bb009e25e34675 | 44,252 | cpp | C++ | EasyCpp/Net/Curl.cpp | Thalhammer/EasyCpp | 6b9886fecf0aa363eaf03741426fd3462306c211 | [
"MIT"
] | 3 | 2018-02-06T05:12:41.000Z | 2020-05-12T20:57:32.000Z | EasyCpp/Net/Curl.cpp | Thalhammer/EasyCpp | 6b9886fecf0aa363eaf03741426fd3462306c211 | [
"MIT"
] | 41 | 2016-07-11T12:19:10.000Z | 2017-08-08T07:43:12.000Z | EasyCpp/Net/Curl.cpp | Thalhammer/EasyCpp | 6b9886fecf0aa363eaf03741426fd3462306c211 | [
"MIT"
] | 2 | 2019-08-02T10:24:36.000Z | 2020-09-11T01:45:12.000Z | #include "Curl.h"
#include <curl/curl.h>
#include <string>
#include <stdexcept>
#include <map>
#include <cstring>
#include "../StringAlgorithm.h"
// Fix for missing macro in old versions
#ifndef CURL_AT_LEAST_VERSION
#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|z)
#define CURL_AT_LEAST_VERSION(x,y,z) \
(LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
#endif
namespace EasyCpp
{
namespace Net
{
Curl::Curl()
{
_handle = curl_easy_init();
_error_buffer = (char*)malloc(CURL_ERROR_SIZE);
reset();
}
Curl::~Curl()
{
std::unique_lock<std::mutex> lck(_handle_lock);
curl_easy_cleanup(_handle);
free(_error_buffer);
}
void Curl::perform()
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_perform(_handle));
}
bool Curl::receive(void * buffer, size_t buflen, size_t & bytes_read)
{
std::unique_lock<std::mutex> lck(_handle_lock);
CURLcode code = curl_easy_recv(_handle, buffer, buflen, &bytes_read);
if (code == CURLE_AGAIN)
return false;
checkCode(code);
return true;
}
bool Curl::send(void * buffer, size_t buflen, size_t & bytes_send)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_send(_handle, buffer, buflen, &bytes_send));
return true;
}
bool Curl::wait(bool recv, uint64_t timeout_ms)
{
curl_socket_t sock = getActiveSocket();
struct timeval tv;
fd_set infd, outfd, errfd;
int res;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
FD_ZERO(&infd);
FD_ZERO(&outfd);
FD_ZERO(&errfd);
FD_SET(sock, &errfd); /* always check for error */
if (recv) {
FD_SET(sock, &infd);
}
else {
FD_SET(sock, &outfd);
}
/* select() returns the number of signalled sockets or -1 */
res = select(sock + 1, &infd, &outfd, &errfd, &tv);
return res != 0;
}
void Curl::reset()
{
{
std::unique_lock<std::mutex> lck(_handle_lock);
curl_easy_reset(_handle);
}
setOption(CURLOPT_NOSIGNAL, true);
setOption(CURLOPT_ERRORBUFFER, _error_buffer);
memset(_error_buffer, 0x00, CURL_ERROR_SIZE);
}
void Curl::setOption(CurlOption option, void * val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_setopt(_handle, (CURLoption)option, val));
}
void Curl::setOption(CurlOption option, bool val)
{
setOption(option, (long)(val ? 1 : 0));
}
void Curl::setOption(CurlOption option, long val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_setopt(_handle, (CURLoption)option, val));
}
void Curl::setOption(CurlOption option, long long val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_setopt(_handle, (CURLoption)option, val));
}
void Curl::setOption(CurlOption option, const std::string & val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_setopt(_handle, (CURLoption)option, val.c_str()));
}
void Curl::getInfo(CurlInfo info, long & val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_getinfo(_handle, (CURLINFO)info, &val));
}
void Curl::getInfo(CurlInfo info, std::string & val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
char* ptr = nullptr;
checkCode(curl_easy_getinfo(_handle, (CURLINFO)info, &ptr));
if (ptr != nullptr)
val = std::string(ptr);
}
void Curl::getInfo(CurlInfo info, std::vector<std::string>& val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
struct curl_slist* slist = nullptr;
checkCode(curl_easy_getinfo(_handle, (CURLINFO)info, &slist));
val = fromSList(slist);
curl_slist_free_all(slist);
}
void Curl::getInfo(CurlInfo info, double & val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_getinfo(_handle, (CURLINFO)info, &val));
}
void Curl::getInfo(CurlInfo info, void ** val)
{
std::unique_lock<std::mutex> lck(_handle_lock);
checkCode(curl_easy_getinfo(_handle, (CURLINFO)info, val));
}
void Curl::setVerbose(bool v)
{
setOption(CURLOPT_VERBOSE, v);
}
void Curl::setHeader(bool v)
{
setOption(CURLOPT_HEADER, v);
}
void Curl::setNoProgress(bool v)
{
setOption(CURLOPT_NOPROGRESS, v);
}
void Curl::setWildcardMatch(bool v)
{
setOption(CURLOPT_WILDCARDMATCH, v);
}
void Curl::setURL(const std::string & url)
{
setOption(CURLOPT_URL, url);
}
void Curl::setURL(const URI & uri)
{
setURL(uri.str());
}
void Curl::setPathAsIs(bool v)
{
#if CURL_AT_LEAST_VERSION(7,42,0)
setOption(CURLOPT_PATH_AS_IS, v);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setProtocols(const std::string & protocols)
{
setOption(CURLOPT_PROTOCOLS, getProtocolMask(protocols));
}
void Curl::setRedirectProtocols(const std::string & protocols)
{
setOption(CURLOPT_REDIR_PROTOCOLS, getProtocolMask(protocols));
}
void Curl::setDefaultProtocol(const std::string & protocol)
{
#if CURL_AT_LEAST_VERSION(7,45,0)
setOption(CURLOPT_DEFAULT_PROTOCOL, protocol);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setProxy(const std::string & proxy)
{
setOption(CURLOPT_PROXY, proxy);
}
void Curl::setProxyPort(uint16_t port)
{
setOption(CURLOPT_PROXYPORT, (long)port);
}
void Curl::setProxyType(ProxyType type)
{
long ctype;
switch (type)
{
case ProxyType::HTTP: ctype = CURLPROXY_HTTP; break;
case ProxyType::HTTP_1_0: ctype = CURLPROXY_HTTP_1_0; break;
case ProxyType::SOCKS4: ctype = CURLPROXY_SOCKS4; break;
case ProxyType::SOCKS4A: ctype = CURLPROXY_SOCKS4A; break;
case ProxyType::SOCKS5: ctype = CURLPROXY_SOCKS5; break;
case ProxyType::SOCKS5_HOSTNAME: ctype = CURLPROXY_SOCKS5_HOSTNAME; break;
default:
ctype = CURLPROXY_HTTP; break;
}
setOption(CURLOPT_PROXYTYPE, ctype);
}
void Curl::setNoProxy(const std::string & hosts)
{
setOption(CURLOPT_NOPROXY, hosts);
}
void Curl::setHTTPProxyTunnel(bool v)
{
setOption(CURLOPT_HTTPPROXYTUNNEL, v);
}
void Curl::setConnectTo(const std::vector<std::string>& list)
{
#if CURL_AT_LEAST_VERSION(7,49,0)
setOption(CURLOPT_CONNECT_TO, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_connect_to = toSList(list);
}
setOption(CURLOPT_CONNECT_TO, _slist_connect_to.get());
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setSocks5GSSAPINegotiationProtection(bool v)
{
setOption(CURLOPT_SOCKS5_GSSAPI_NEC, v);
}
void Curl::setProxyServiceName(const std::string & service)
{
#if CURL_AT_LEAST_VERSION(7,43,0)
setOption(CURLOPT_PROXY_SERVICE_NAME, service);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setAuthenticationServiceName(const std::string & name)
{
#if CURL_AT_LEAST_VERSION(7,43,0)
setOption(CURLOPT_SERVICE_NAME, name);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setInterface(const std::string & str)
{
if (str != "")
setOption(CURLOPT_INTERFACE, str);
else setOption(CURLOPT_INTERFACE, nullptr);
}
void Curl::setLocalPort(uint16_t port)
{
setOption(CURLOPT_LOCALPORT, (long)port);
}
void Curl::setLocalPortRange(uint16_t range)
{
setOption(CURLOPT_LOCALPORTRANGE, (long)range);
}
void Curl::setDNSCacheTimeout(long timeout)
{
setOption(CURLOPT_DNS_CACHE_TIMEOUT, timeout);
}
void Curl::setBufferSize(long size)
{
setOption(CURLOPT_BUFFERSIZE, size);
}
void Curl::setPort(uint16_t port)
{
setOption(CURLOPT_PORT, (long)port);
}
void Curl::setTCPFastOpen(bool v)
{
#if defined(CURLOPT_TCP_FASTOPEN)
setOption(CURLOPT_TCP_FASTOPEN, v);
#else
throw std::runtime_error("Not supported by this CURL version");
#endif
}
void Curl::setTCPNoDelay(bool v)
{
setOption(CURLOPT_TCP_NODELAY, v);
}
void Curl::setAddressScope(long scope)
{
setOption(CURLOPT_ADDRESS_SCOPE, scope);
}
void Curl::setTCPKeepAlive(bool v)
{
setOption(CURLOPT_TCP_KEEPALIVE, v);
}
void Curl::setTCPKeepAliveIdleTime(long time)
{
setOption(CURLOPT_TCP_KEEPIDLE, time);
}
void Curl::setTCPKeepAliveInterval(long time)
{
setOption(CURLOPT_TCP_KEEPINTVL, time);
}
void Curl::setUnixSocketPath(const std::string & path)
{
#if CURL_AT_LEAST_VERSION(7,40,0)
if (path == "")
setOption(CURLOPT_UNIX_SOCKET_PATH, nullptr);
else setOption(CURLOPT_UNIX_SOCKET_PATH, path);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setNETRC(bool read, bool required)
{
if (read)
{
if (required)
setOption(CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED);
else setOption(CURLOPT_NETRC, (long)CURL_NETRC_OPTIONAL);
}
else setOption(CURLOPT_NETRC, (long)CURL_NETRC_IGNORED);
}
void Curl::setNETRCFilename(const std::string & name)
{
setOption(CURLOPT_NETRC_FILE, name);
}
void Curl::setUsername(const std::string & user)
{
setOption(CURLOPT_USERNAME, user);
}
void Curl::setPassword(const std::string & pass)
{
setOption(CURLOPT_PASSWORD, pass);
}
void Curl::setProxyUsername(const std::string & user)
{
setOption(CURLOPT_PROXYUSERNAME, user);
}
void Curl::setProxyPassword(const std::string & password)
{
setOption(CURLOPT_PROXYPASSWORD, password);
}
void Curl::setLoginOptions(const std::string & options)
{
setOption(CURLOPT_LOGIN_OPTIONS, options);
}
void Curl::setHTTPAuth(const std::string & methods)
{
long bitmask = 0;
for (const std::string& str : stringSplit(" ", methods))
{
if (str == "basic") bitmask |= CURLAUTH_BASIC;
else if (str == "digest") bitmask |= CURLAUTH_DIGEST;
else if (str == "digest_ie") bitmask |= CURLAUTH_DIGEST_IE;
else if (str == "negotiate") bitmask |= CURLAUTH_NEGOTIATE;
else if (str == "gssnegotiate") bitmask |= CURLAUTH_GSSNEGOTIATE;
else if (str == "ntlm") bitmask |= CURLAUTH_NTLM;
else if (str == "ntlm_wb") bitmask |= CURLAUTH_NTLM_WB;
else if (str == "any") bitmask |= CURLAUTH_ANY;
else if (str == "anysafe") bitmask |= CURLAUTH_ANYSAFE;
else if (str == "only") bitmask |= CURLAUTH_ONLY;
}
setOption(CURLOPT_HTTPAUTH, bitmask);
}
void Curl::setTLSAuthUsername(const std::string & user)
{
setOption(CURLOPT_TLSAUTH_USERNAME, user);
}
void Curl::setTLSAuthPassword(const std::string & pass)
{
setOption(CURLOPT_TLSAUTH_PASSWORD, pass);
}
void Curl::setTLSAuthType(const std::string & type)
{
setOption(CURLOPT_TLSAUTH_TYPE, type);
}
void Curl::setProxyAuth(const std::string & methods)
{
long bitmask = 0;
for (const std::string& str : stringSplit(" ", methods))
{
if (str == "basic") bitmask |= CURLAUTH_BASIC;
else if (str == "digest") bitmask |= CURLAUTH_DIGEST;
else if (str == "digest_ie") bitmask |= CURLAUTH_DIGEST_IE;
else if (str == "negotiate") bitmask |= CURLAUTH_NEGOTIATE;
else if (str == "gssnegotiate") bitmask |= CURLAUTH_GSSNEGOTIATE;
else if (str == "ntlm") bitmask |= CURLAUTH_NTLM;
else if (str == "ntlm_wb") bitmask |= CURLAUTH_NTLM_WB;
else if (str == "any") bitmask |= CURLAUTH_ANY;
else if (str == "anysafe") bitmask |= CURLAUTH_ANYSAFE;
else if (str == "only") bitmask |= CURLAUTH_ONLY;
}
setOption(CURLOPT_PROXYAUTH, bitmask);
}
void Curl::setSASLIR(bool v)
{
setOption(CURLOPT_SASL_IR, v);
}
void Curl::setXOAuth2Bearer(const std::string & token)
{
setOption(CURLOPT_XOAUTH2_BEARER, token);
}
void Curl::setWriteFunction(std::function<uint64_t(char*, uint64_t)> fn)
{
_write_fn = fn;
setOption(CURLOPT_WRITEFUNCTION, (void*)&_s_write_callback);
setOption(CURLOPT_WRITEDATA, this);
}
void Curl::setReadFunction(std::function<uint64_t(char*, uint64_t)> fn)
{
_read_fn = fn;
setOption(CURLOPT_READFUNCTION, (void*)&_s_read_callback);
setOption(CURLOPT_READDATA, this);
}
void Curl::setStreamRestartFunction(std::function<bool()> fn)
{
_ioctl_restart_fn = fn;
setOption(CURLOPT_IOCTLFUNCTION, (void*)&_s_ioctl_callback);
setOption(CURLOPT_IOCTLDATA, this);
}
void Curl::setSeekFunction(std::function<bool(uint64_t, int)> fn)
{
_seek_fn = fn;
setOption(CURLOPT_SEEKFUNCTION, (void*)&_s_seek_callback);
setOption(CURLOPT_SEEKDATA, this);
}
void Curl::setXferInfoFunction(std::function<void(uint64_t, uint64_t, uint64_t, uint64_t)> fn)
{
_xferinfo_fn = fn;
setOption(CURLOPT_XFERINFOFUNCTION, (void*)&_s_xferinfo_callback);
setOption(CURLOPT_XFERINFODATA, this);
}
void Curl::setHeaderFunction(std::function<void(std::string)> fn)
{
_header_fn = fn;
setOption(CURLOPT_HEADERFUNCTION, (void*)&_s_header_callback);
setOption(CURLOPT_HEADERDATA, this);
}
void Curl::setDebugFunction(std::function<void(InfoType, char*, size_t)> fn)
{
_debug_fn = fn;
setOption(CURLOPT_DEBUGFUNCTION, (void*)&_s_debug_callback);
setOption(CURLOPT_DEBUGDATA, this);
}
void Curl::setMatchFunction(std::function<bool(const std::string&pattern, const std::string&string)> fn)
{
_match_fn = fn;
setOption(CURLOPT_FNMATCH_FUNCTION, (void*)&_s_fnmatch_callback);
setOption(CURLOPT_FNMATCH_DATA, this);
}
void Curl::setDebugString(std::string & debug)
{
this->setDebugFunction([&debug](auto type, auto data, auto len) {
if (type == InfoType::Text)
debug += data;
});
}
void Curl::setFailOnError(bool v)
{
setOption(CURLOPT_FAILONERROR, v);
}
std::string Curl::getErrorBuffer() const
{
return std::string(_error_buffer);
}
void Curl::setMailFrom(const std::string & from)
{
setOption(CURLOPT_MAIL_FROM, from);
}
void Curl::setMailRecipients(const std::vector<std::string> & rcpt)
{
setOption(CURLOPT_MAIL_RCPT, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_mail_rcpt = toSList(rcpt);
}
setOption(CURLOPT_MAIL_RCPT, _slist_mail_rcpt.get());
}
void Curl::setMailAuth(const std::string & auth)
{
setOption(CURLOPT_MAIL_AUTH, auth);
}
void Curl::setTelnetOptions(const std::vector<std::string> & options)
{
setOption(CURLOPT_TELNETOPTIONS, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_telnet_options = toSList(options);
}
setOption(CURLOPT_TELNETOPTIONS, _slist_telnet_options.get());
}
void Curl::setNewFilePerms(long mode)
{
setOption(CURLOPT_NEW_FILE_PERMS, mode);
}
void Curl::setNewDirectoryPerms(long mode)
{
setOption(CURLOPT_NEW_DIRECTORY_PERMS, mode);
}
void Curl::setTFTPBlockSize(long size)
{
setOption(CURLOPT_TFTP_BLKSIZE, size);
}
void Curl::setTFTPNoOptions(bool v)
{
#if defined(CURLOPT_TFTP_NO_OPTIONS)
setOption(CURLOPT_TFTP_NO_OPTIONS, v);
#else
throw std::runtime_error("Not supported by this CURL version");
#endif
}
void Curl::setRTSPRequest(RTSPRequest req)
{
long request = 0;
switch (req)
{
case RTSPRequest::Announce: request = CURL_RTSPREQ_ANNOUNCE; break;
case RTSPRequest::Describe: request = CURL_RTSPREQ_DESCRIBE; break;
case RTSPRequest::GetParameter: request = CURL_RTSPREQ_GET_PARAMETER; break;
case RTSPRequest::Options: request = CURL_RTSPREQ_OPTIONS; break;
case RTSPRequest::Pause: request = CURL_RTSPREQ_PAUSE; break;
case RTSPRequest::Play: request = CURL_RTSPREQ_PLAY; break;
case RTSPRequest::Receive: request = CURL_RTSPREQ_RECEIVE; break;
case RTSPRequest::Record: request = CURL_RTSPREQ_RECORD; break;
case RTSPRequest::SetParameter: request = CURL_RTSPREQ_SET_PARAMETER; break;
case RTSPRequest::Setup: request = CURL_RTSPREQ_SETUP; break;
case RTSPRequest::Teardown: request = CURL_RTSPREQ_TEARDOWN; break;
}
setOption(CURLOPT_RTSP_REQUEST, request);
}
void Curl::setRTSPSessionID(const std::string & id)
{
setOption(CURLOPT_RTSP_SESSION_ID, id);
}
void Curl::setRTSPStreamURI(const std::string & uri)
{
setOption(CURLOPT_RTSP_STREAM_URI, uri);
}
void Curl::setRTSPTransport(const std::string & str)
{
setOption(CURLOPT_RTSP_TRANSPORT, str);
}
void Curl::setRTSPClientCSEQ(long seq)
{
setOption(CURLOPT_RTSP_CLIENT_CSEQ, seq);
}
void Curl::setRTSPServerCSEQ(long seq)
{
setOption(CURLOPT_RTSP_SERVER_CSEQ, seq);
}
void Curl::setSSHAuthTypes(const std::string & types)
{
long bitmask = 0;
for (const std::string& str : stringSplit(" ", types))
{
if (str == "publickey") bitmask |= CURLSSH_AUTH_PUBLICKEY;
else if (str == "password") bitmask |= CURLSSH_AUTH_PASSWORD;
else if (str == "host") bitmask |= CURLSSH_AUTH_HOST;
else if (str == "keyboard") bitmask |= CURLSSH_AUTH_KEYBOARD;
else if (str == "agent") bitmask |= CURLSSH_AUTH_AGENT;
else if (str == "any") bitmask |= CURLSSH_AUTH_ANY;
}
setOption(CURLOPT_SSH_AUTH_TYPES, bitmask);
}
void Curl::setSSHHostPublicKeyMD5(const std::string & md5)
{
setOption(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, md5);
}
void Curl::setSSHPublicKeyFile(const std::string & path)
{
setOption(CURLOPT_SSH_PUBLIC_KEYFILE, path);
}
void Curl::setSSHPrivateKeyFile(const std::string & path)
{
setOption(CURLOPT_SSH_PRIVATE_KEYFILE, path);
}
void Curl::setSSHKnownHostsFile(const std::string & path)
{
setOption(CURLOPT_SSH_KNOWNHOSTS, path);
}
void Curl::setSSHKeyFunction(std::function<SSHKeyStatus(const SSHKey&, const SSHKey&, SSHKeyMatch)> fn)
{
_ssh_key_match_fn = fn;
setOption(CURLOPT_SSH_KEYFUNCTION, (void*)&_s_ssh_keycallback);
setOption(CURLOPT_SSH_KEYDATA, this);
}
void Curl::setAutoReferer(bool v)
{
setOption(CURLOPT_AUTOREFERER, v);
}
void Curl::setAcceptEncoding(const std::string & str)
{
setOption(CURLOPT_ACCEPT_ENCODING, str);
}
void Curl::setTransferEncoding(const std::string & str)
{
setOption(CURLOPT_TRANSFER_ENCODING, str);
}
void Curl::setFollowLocation(bool v)
{
setOption(CURLOPT_FOLLOWLOCATION, v);
}
void Curl::setUnrestrictedAuth(bool v)
{
setOption(CURLOPT_UNRESTRICTED_AUTH, v);
}
void Curl::setMaxRedirections(long m)
{
setOption(CURLOPT_MAXREDIRS, m);
}
void Curl::setPostRedirection(const std::string & str)
{
long bitmask = 0;
for (const std::string& s : stringSplit(" ", str))
{
if (s == "301") bitmask |= CURL_REDIR_POST_301;
else if (s == "302") bitmask |= CURL_REDIR_POST_302;
else if (s == "303") bitmask |= CURL_REDIR_POST_303;
else if (s == "all") bitmask |= CURL_REDIR_POST_ALL;
}
}
void Curl::setPOST(bool v)
{
setOption(CURLOPT_POST, v);
}
void Curl::setPOSTFields(const std::string & str)
{
setPOSTFieldSize(str.size());
setOption(CURLOPT_COPYPOSTFIELDS, str);
}
void Curl::setPOSTFieldSize(size_t size)
{
curl_off_t csize = size;
setOption(CURLOPT_POSTFIELDSIZE_LARGE, csize);
}
void Curl::setReferer(const std::string & referer)
{
setOption(CURLOPT_REFERER, referer);
}
void Curl::setUserAgent(const std::string & ua)
{
setOption(CURLOPT_USERAGENT, ua);
}
void Curl::setHeaders(const std::multimap<std::string, std::string>& headers)
{
std::vector<std::string> sheaders;
for (auto elem : headers)
{
sheaders.push_back(elem.first + ": " + elem.second);
}
setOption(CURLOPT_HTTPHEADER, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_headers = toSList(sheaders);
}
setOption(CURLOPT_HTTPHEADER, _slist_headers.get());
}
void Curl::setHeaderOpt(bool v)
{
if (v) setOption(CURLOPT_HEADEROPT, (long)CURLHEADER_UNIFIED);
else setOption(CURLOPT_HEADEROPT, (long)CURLHEADER_SEPARATE);
}
void Curl::setProxyHeaders(const std::multimap<std::string, std::string>& headers)
{
std::vector<std::string> sheaders;
for (auto elem : headers)
{
sheaders.push_back(elem.first + ": " + elem.second);
}
setOption(CURLOPT_PROXYHEADER, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_proxyheaders = toSList(sheaders);
}
setOption(CURLOPT_PROXYHEADER, _slist_proxyheaders.get());
}
void Curl::setHTTP200Aliases(const std::vector<std::string>& aliases)
{
setOption(CURLOPT_HTTP200ALIASES, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_200_aliases = toSList(aliases);
}
setOption(CURLOPT_HTTP200ALIASES, _slist_200_aliases.get());
}
void Curl::setCookie(const std::string & cookie)
{
setOption(CURLOPT_COOKIE, cookie);
}
void Curl::setCookieFile(const std::string & cookiefile)
{
setOption(CURLOPT_COOKIEFILE, cookiefile);
}
void Curl::setCookieJar(const std::string & cookiejar)
{
setOption(CURLOPT_COOKIEJAR, cookiejar);
}
void Curl::setCookieSession(bool v)
{
setOption(CURLOPT_COOKIESESSION, v);
}
void Curl::setCookieList(const std::string & cookie)
{
setOption(CURLOPT_COOKIELIST, cookie);
}
void Curl::setHTTPGet(bool v)
{
setOption(CURLOPT_HTTPGET, v);
}
void Curl::setHTTPVersion(HTTPVersion v)
{
long version;
switch (v)
{
case HTTPVersion::V1_0: version = CURL_HTTP_VERSION_1_0; break;
case HTTPVersion::V1_1: version = CURL_HTTP_VERSION_1_1; break;
case HTTPVersion::V2_0: version = CURL_HTTP_VERSION_2_0; break;
#if CURL_AT_LEAST_VERSION(7,47,0)
case HTTPVersion::V2TLS: version = CURL_HTTP_VERSION_2TLS; break;
#else
case HTTPVersion::V2TLS:
throw std::runtime_error("Not supported by compiled curl version");
#endif
default: version = CURL_HTTP_VERSION_NONE; break;
}
setOption(CURLOPT_HTTP_VERSION, version);
}
void Curl::setIgnoreContentLength(bool v)
{
setOption(CURLOPT_IGNORE_CONTENT_LENGTH, v);
}
void Curl::setContentDecoding(bool v)
{
setOption(CURLOPT_HTTP_CONTENT_DECODING, v);
}
void Curl::setTransferDecoding(bool v)
{
setOption(CURLOPT_HTTP_TRANSFER_DECODING, v);
}
void Curl::setExpect100TimeoutMs(long ms)
{
setOption(CURLOPT_EXPECT_100_TIMEOUT_MS, ms);
}
void Curl::setPipeWait(long wait)
{
#if CURL_AT_LEAST_VERSION(7,43,0)
setOption(CURLOPT_PIPEWAIT, wait);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setStreamWeight(long w)
{
#if CURL_AT_LEAST_VERSION(7,46,0)
setOption(CURLOPT_STREAM_WEIGHT, w);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setFTPPort(const std::string & spec)
{
setOption(CURLOPT_FTPPORT, spec);
}
void Curl::setQuote(const std::vector<std::string>& str)
{
setOption(CURLOPT_QUOTE, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_ftp_quote = toSList(str);
}
setOption(CURLOPT_QUOTE, _slist_ftp_quote.get());
}
void Curl::setPOSTQuote(const std::vector<std::string>& str)
{
setOption(CURLOPT_POSTQUOTE, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_ftp_postquote = toSList(str);
}
setOption(CURLOPT_POSTQUOTE, _slist_ftp_postquote.get());
}
void Curl::setPREQuote(const std::vector<std::string>& str)
{
setOption(CURLOPT_PREQUOTE, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_ftp_prequote = toSList(str);
}
setOption(CURLOPT_PREQUOTE, _slist_ftp_prequote.get());
}
void Curl::setFTPAppend(bool v)
{
setOption(CURLOPT_APPEND, v);
}
void Curl::setFTPUseEPRT(bool v)
{
setOption(CURLOPT_FTP_USE_EPRT, v);
}
void Curl::setFTPUseEPSV(bool v)
{
setOption(CURLOPT_FTP_USE_EPSV, v);
}
void Curl::setFTPUsePRET(bool v)
{
setOption(CURLOPT_FTP_USE_PRET, v);
}
void Curl::setFTPCreateDir(FTPCreateDir dir)
{
long option;
switch (dir)
{
case FTPCreateDir::ALL: option = CURLFTP_CREATE_DIR; break;
case FTPCreateDir::RETRY: option = CURLFTP_CREATE_DIR_RETRY; break;
case FTPCreateDir::NONE:
default: option = CURLFTP_CREATE_DIR_NONE; break;
}
setOption(CURLOPT_FTP_CREATE_MISSING_DIRS, option);
}
void Curl::setFTPResponseTimeout(long timeout)
{
setOption(CURLOPT_FTP_RESPONSE_TIMEOUT, timeout);
}
void Curl::setFTPAlternativeToUser(const std::string & alt)
{
setOption(CURLOPT_FTP_ALTERNATIVE_TO_USER, alt);
}
void Curl::setFTPSkipPASVIp(bool v)
{
setOption(CURLOPT_FTP_SKIP_PASV_IP, v);
}
void Curl::setFTPSSLAuth(FTPAuth auth)
{
long option;
switch (auth)
{
case FTPAuth::TLS: option = CURLFTPAUTH_TLS; break;
case FTPAuth::SSL: option = CURLFTPAUTH_SSL; break;
case FTPAuth::DEFAULT:
default: option = CURLFTPAUTH_DEFAULT; break;
}
setOption(CURLOPT_FTPSSLAUTH, option);
}
void Curl::setFTPSSLClearCommandChannel(FTPCCC ccc)
{
long option;
switch (ccc)
{
case FTPCCC::PASSIVE: option = CURLFTPSSL_CCC_PASSIVE; break;
case FTPCCC::ACTIVE: option = CURLFTPSSL_CCC_ACTIVE; break;
case FTPCCC::NONE:
default: option = CURLFTPSSL_CCC_NONE; break;
}
setOption(CURLOPT_FTP_SSL_CCC, option);
}
void Curl::setFTPAccount(const std::string & str)
{
setOption(CURLOPT_FTP_ACCOUNT, str);
}
void Curl::setFTPFileMethod(FTPFileMethod fm)
{
long option;
switch (fm)
{
case FTPFileMethod::MULTICWD: option = CURLFTPMETHOD_MULTICWD; break;
case FTPFileMethod::NOCWD: option = CURLFTPMETHOD_NOCWD; break;
case FTPFileMethod::SINGLECWD: option = CURLFTPMETHOD_SINGLECWD; break;
default: option = CURLFTPMETHOD_DEFAULT; break;
}
setOption(CURLOPT_FTP_FILEMETHOD, option);
}
void Curl::setTransferText(bool v)
{
setOption(CURLOPT_TRANSFERTEXT, v);
}
void Curl::setProxyTransferText(bool v)
{
setOption(CURLOPT_PROXY_TRANSFER_MODE, v);
}
void Curl::setConvertNewLine(bool v)
{
setOption(CURLOPT_CRLF, v);
}
void Curl::setRangeRequest(const std::string & str)
{
setOption(CURLOPT_RANGE, str);
}
void Curl::setResumeFrom(size_t s)
{
setOption(CURLOPT_RESUME_FROM_LARGE, (long)s);
}
void Curl::setCustomRequest(const std::string & req)
{
setOption(CURLOPT_CUSTOMREQUEST, req);
}
void Curl::setFileTime(bool v)
{
setOption(CURLOPT_FILETIME, v);
}
void Curl::setDirListOnly(bool v)
{
setOption(CURLOPT_DIRLISTONLY, v);
}
void Curl::setNoBody(bool v)
{
setOption(CURLOPT_NOBODY, v);
}
void Curl::setInFileSize(size_t s)
{
setOption(CURLOPT_INFILESIZE_LARGE, (long)s);
}
void Curl::setUpload(bool v)
{
setOption(CURLOPT_UPLOAD, v);
}
void Curl::setMaxFileSize(size_t s)
{
setOption(CURLOPT_MAXFILESIZE_LARGE, (long)s);
}
void Curl::setTimeCondition(TimeCondition tc)
{
long option;
switch (tc)
{
case TimeCondition::MODSINCE: option = CURL_TIMECOND_IFMODSINCE; break;
case TimeCondition::UNMODSINCE: option = CURL_TIMECOND_IFUNMODSINCE; break;
case TimeCondition::LASTMOD: option = CURL_TIMECOND_LASTMOD; break;
case TimeCondition::NONE:
default: option = CURL_TIMECOND_NONE; break;
}
setOption(CURLOPT_TIMECONDITION, option);
}
void Curl::setTimeValue(long tv)
{
setOption(CURLOPT_TIMEVALUE, tv);
}
void Curl::setTimeout(long ms)
{
setOption(CURLOPT_TIMEOUT_MS, ms);
}
void Curl::setLowSpeedLimit(long bps)
{
setOption(CURLOPT_LOW_SPEED_LIMIT, bps);
}
void Curl::setLowSpeedTime(long s)
{
setOption(CURLOPT_LOW_SPEED_TIME, s);
}
void Curl::setMaxSendSpeed(long bps)
{
setOption(CURLOPT_MAX_SEND_SPEED_LARGE, bps);
}
void Curl::setMaxRecvSpeed(long bps)
{
setOption(CURLOPT_MAX_RECV_SPEED_LARGE, bps);
}
void Curl::setMaxConnections(long cnt)
{
setOption(CURLOPT_MAXCONNECTS, cnt);
}
void Curl::setFreshConnect(bool fresh)
{
setOption(CURLOPT_FRESH_CONNECT, fresh);
}
void Curl::setForbidReuse(bool close)
{
setOption(CURLOPT_FORBID_REUSE, close);
}
void Curl::setConnectTimeout(long timeoutms)
{
setOption(CURLOPT_CONNECTTIMEOUT_MS, timeoutms);
}
void Curl::setIPResolve(IPResolve res)
{
long option = CURL_IPRESOLVE_WHATEVER;
switch (res)
{
case IPResolve::Whatever: option = CURL_IPRESOLVE_WHATEVER; break;
case IPResolve::IPV4: option = CURL_IPRESOLVE_V4; break;
case IPResolve::IPV6: option = CURL_IPRESOLVE_V6; break;
}
setOption(CURLOPT_IPRESOLVE, option);
}
void Curl::setConnectOnly(bool only)
{
setOption(CURLOPT_CONNECT_ONLY, only);
}
void Curl::setUseSSL(SSLLevel l)
{
long option;
switch (l)
{
default:
case SSLLevel::NONE: option = CURLUSESSL_NONE; break;
case SSLLevel::OPT: option = CURLUSESSL_TRY; break;
case SSLLevel::CONTROL: option = CURLUSESSL_CONTROL; break;
case SSLLevel::ALL: option = CURLUSESSL_ALL; break;
}
setOption(CURLOPT_USE_SSL, option);
}
void Curl::setResolve(const std::vector<std::string>& list)
{
setOption(CURLOPT_RESOLVE, nullptr);
{
std::unique_lock<std::mutex> lck(_handle_lock);
_slist_resolve = toSList(list);
}
setOption(CURLOPT_RESOLVE, _slist_resolve.get());
}
void Curl::setDNSInterface(const std::string& iface)
{
setOption(CURLOPT_DNS_INTERFACE, iface);
}
void Curl::setDNSLocalIPv4(const std::string& address)
{
setOption(CURLOPT_DNS_LOCAL_IP4, address);
}
void Curl::setDNSLocalIPv6(const std::string& address)
{
setOption(CURLOPT_DNS_LOCAL_IP6, address);
}
void Curl::setDNSServers(const std::string& servers)
{
setOption(CURLOPT_DNS_SERVERS, servers);
}
void Curl::setAcceptTimeout(long ms)
{
setOption(CURLOPT_ACCEPTTIMEOUT_MS, ms);
}
void Curl::setSSLCertificate(const std::string& file)
{
setOption(CURLOPT_SSLCERT, file);
}
void Curl::setSSLCertificateType(const std::string& type)
{
setOption(CURLOPT_SSLCERTTYPE, type);
}
void Curl::setSSLKey(const std::string& key)
{
setOption(CURLOPT_SSLKEY, key);
}
void Curl::setSSLKeyType(const std::string& type)
{
setOption(CURLOPT_SSLKEYTYPE, type);
}
void Curl::setSSLKeyPassword(const std::string& pass)
{
setOption(CURLOPT_KEYPASSWD, pass);
}
void Curl::setSSLEnableALPN(bool v)
{
setOption(CURLOPT_SSL_ENABLE_ALPN, v);
}
void Curl::setSSLEnableNPN(bool v)
{
setOption(CURLOPT_SSL_ENABLE_NPN, v);
}
void Curl::setSSLEngine(const std::string& str)
{
setOption(CURLOPT_SSLENGINE, str);
}
void Curl::setSSLEngineDefault(bool v)
{
setOption(CURLOPT_SSLENGINE_DEFAULT, v);
}
void Curl::setSSLFalseStart(bool v)
{
#if CURL_AT_LEAST_VERSION(7,42,0)
setOption(CURLOPT_SSL_FALSESTART, v);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setSSLVersion(SSLVersion v)
{
setOption(CURLOPT_SSLVERSION, (long)v);
}
void Curl::setSSLVerifyHost(bool v)
{
setOption(CURLOPT_SSL_VERIFYHOST, (long)(v ? 2 : 0));
}
void Curl::setSSLVerifyPeer(bool v)
{
setOption(CURLOPT_SSL_VERIFYPEER, v);
}
void Curl::setSSLVerifyStatus(bool v)
{
#if CURL_AT_LEAST_VERSION(7,41,0)
setOption(CURLOPT_SSL_VERIFYSTATUS, v);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setSSLCABundle(const std::string& path)
{
setOption(CURLOPT_CAINFO, path);
}
void Curl::setSSLIssuerCert(const std::string& path)
{
setOption(CURLOPT_ISSUERCERT, path);
}
void Curl::setSSLCAPath(const std::string& path)
{
setOption(CURLOPT_CAPATH, path);
}
void Curl::setSSLCRList(const std::string& file)
{
setOption(CURLOPT_CRLFILE, file);
}
void Curl::setSSLCertInfo(bool v)
{
setOption(CURLOPT_CERTINFO, v);
}
void Curl::setSSLPinnedPublicKey(const std::string& ppk)
{
#if CURL_AT_LEAST_VERSION(7,39,0)
setOption(CURLOPT_PINNEDPUBLICKEY, ppk);
#else
throw std::runtime_error("Not supported by compiled curl version");
#endif
}
void Curl::setSSLRandomFile(const std::string& file)
{
setOption(CURLOPT_RANDOM_FILE, file);
}
void Curl::setSSLEGDSocket(const std::string& socket)
{
setOption(CURLOPT_EGDSOCKET, socket);
}
void Curl::setSSLCipherList(const std::string& list)
{
setOption(CURLOPT_SSL_CIPHER_LIST, list);
}
void Curl::setSSLSessionIDCache(bool enabled)
{
setOption(CURLOPT_SSL_SESSIONID_CACHE, enabled);
}
void Curl::setSSLKRBLevel(const std::string& level)
{
setOption(CURLOPT_KRBLEVEL, level);
}
std::string Curl::getEffectiveURL()
{
std::string res;
getInfo(CURLINFO_EFFECTIVE_URL, res);
return res;
}
int Curl::getResponseCode()
{
long res;
getInfo(CURLINFO_RESPONSE_CODE, res);
return (int)res;
}
int Curl::getHTTPConnectCode()
{
long res;
getInfo(CURLINFO_HTTP_CONNECTCODE, res);
return (int)res;
}
long Curl::getFileTime()
{
long res;
getInfo(CURLINFO_FILETIME, res);
return res;
}
double Curl::getTotalTime()
{
double res;
getInfo(CURLINFO_TOTAL_TIME, res);
return res;
}
double Curl::getNameLookupTime()
{
double res;
getInfo(CURLINFO_NAMELOOKUP_TIME, res);
return res;
}
double Curl::getConnectTime()
{
double res;
getInfo(CURLINFO_CONNECT_TIME, res);
return res;
}
double Curl::getAppConnectTime()
{
double res;
getInfo(CURLINFO_APPCONNECT_TIME, res);
return res;
}
double Curl::getPreTransferTime()
{
double res;
getInfo(CURLINFO_PRETRANSFER_TIME, res);
return res;
}
double Curl::getStartTransferTime()
{
double res;
getInfo(CURLINFO_STARTTRANSFER_TIME, res);
return res;
}
double Curl::getRedirectTime()
{
double res;
getInfo(CURLINFO_REDIRECT_TIME, res);
return res;
}
long Curl::getRedirectCount()
{
long res;
getInfo(CURLINFO_REDIRECT_COUNT, res);
return res;
}
std::string Curl::getRedirectUrl()
{
std::string res;
getInfo(CURLINFO_REDIRECT_URL, res);
return res;
}
double Curl::getSizeUpload()
{
double res;
getInfo(CURLINFO_SIZE_UPLOAD, res);
return res;
}
double Curl::getSizeDownload()
{
double res;
getInfo(CURLINFO_SIZE_DOWNLOAD, res);
return res;
}
double Curl::getSpeedUpload()
{
double res;
getInfo(CURLINFO_SPEED_UPLOAD, res);
return res;
}
double Curl::getSpeedDownload()
{
double res;
getInfo(CURLINFO_SPEED_DOWNLOAD, res);
return res;
}
long Curl::getHeaderSize()
{
long res;
getInfo(CURLINFO_HEADER_SIZE, res);
return res;
}
long Curl::getRequestSize()
{
long res;
getInfo(CURLINFO_REQUEST_SIZE, res);
return res;
}
long Curl::getSSLVerifyResult()
{
long res;
getInfo(CURLINFO_SSL_VERIFYRESULT, res);
return res;
}
std::vector<std::string> Curl::getSSLEngines()
{
std::vector<std::string> res;
getInfo(CURLINFO_SSL_ENGINES, res);
return res;
}
double Curl::getContentLengthDownload()
{
double res;
getInfo(CURLINFO_CONTENT_LENGTH_DOWNLOAD, res);
return res;
}
double Curl::getContentLengthUpload()
{
double res;
getInfo(CURLINFO_CONTENT_LENGTH_UPLOAD, res);
return res;
}
std::string Curl::getContentType()
{
std::string res;
getInfo(CURLINFO_CONTENT_TYPE, res);
return res;
}
std::string Curl::getHTTPAuthAvailable()
{
std::string res;
long info;
getInfo(CURLINFO_HTTPAUTH_AVAIL, info);
if (info & CURLAUTH_BASIC) res += "basic ";
if (info & CURLAUTH_DIGEST) res += "digest ";
if (info & CURLAUTH_DIGEST_IE) res += "digest_ie ";
if (info & CURLAUTH_NEGOTIATE) res += "negotiate ";
if (info & CURLAUTH_GSSNEGOTIATE) res += "gssnegotiate ";
if (info & CURLAUTH_NTLM) res += "ntlm ";
if (info & CURLAUTH_NTLM_WB) res += "ntlm_wb ";
if (res != "" && res[res.size() - 1] == ' ')
res.erase(res.begin() + res.size() - 1);
return res;
}
std::string Curl::getProxyAuthAvailable()
{
std::string res;
long info;
getInfo(CURLINFO_PROXYAUTH_AVAIL, info);
if (info & CURLAUTH_BASIC) res += "basic ";
if (info & CURLAUTH_DIGEST) res += "digest ";
if (info & CURLAUTH_DIGEST_IE) res += "digest_ie ";
if (info & CURLAUTH_NEGOTIATE) res += "negotiate ";
if (info & CURLAUTH_GSSNEGOTIATE) res += "gssnegotiate ";
if (info & CURLAUTH_NTLM) res += "ntlm ";
if (info & CURLAUTH_NTLM_WB) res += "ntlm_wb ";
if (res != "" && res[res.size() - 1] == ' ')
res.erase(res.begin() + res.size() - 1);
return res;
}
long Curl::getOSErrorNumber()
{
long res;
getInfo(CURLINFO_OS_ERRNO, res);
return res;
}
long Curl::getNumConnects()
{
long res;
getInfo(CURLINFO_NUM_CONNECTS, res);
return res;
}
std::string Curl::getPrimaryIP()
{
std::string res;
getInfo(CURLINFO_PRIMARY_IP, res);
return res;
}
uint16_t Curl::getPrimaryPort()
{
long res;
getInfo(CURLINFO_PRIMARY_PORT, res);
return (uint16_t)res;
}
std::string Curl::getLocalIP()
{
std::string res;
getInfo(CURLINFO_LOCAL_IP, res);
return res;
}
uint16_t Curl::getLocalPort()
{
long res;
getInfo(CURLINFO_LOCAL_PORT, res);
return (uint16_t)res;
}
std::vector<std::string> Curl::getCookieList()
{
std::vector<std::string> res;
getInfo(CURLINFO_COOKIELIST, res);
return res;
}
uint64_t Curl::getActiveSocket()
{
#if CURL_AT_LEAST_VERSION(7,45,0)
curl_socket_t t;
getInfo(CURLINFO_ACTIVESOCKET, (void**)&t);
return t;
#else
long t;
getInfo(CURLINFO_LASTSOCKET, t);
return (uint64_t)t;
#endif
}
std::string Curl::getFTPEntryPath()
{
std::string res;
getInfo(CURLINFO_FTP_ENTRY_PATH, res);
return res;
}
std::vector<std::multimap<std::string, std::string>> Curl::getCertInfo()
{
std::vector<std::multimap<std::string, std::string>> res;
struct curl_certinfo* info;
getInfo(CURLINFO_CERTINFO, (void**)&info);
for (int i = 0; i < info->num_of_certs; i++)
{
std::multimap<std::string, std::string> entry;
struct curl_slist* list = info->certinfo[i];
while (list != nullptr)
{
std::string line = list->data;
auto pos = line.find_first_of(':');
entry.insert({ line.substr(0,pos),line.substr(pos + 1) });
list = list->next;
}
res.push_back(entry);
}
return res;
}
void Curl::setOutputString(std::string & str)
{
this->setWriteFunction([&str](auto data, auto len) {
str += std::string(data, data + len);
return len;
});
}
void Curl::setInputString(const std::string & str)
{
this->setReadFunction([&str, pos = 0](auto data, auto len) mutable {
std::string substr = str.substr(pos, (size_t)len);
memcpy(data, substr.data(), substr.size());
pos += substr.size();
return substr.size();
});
this->setPOSTFieldSize(str.size());
}
void Curl::checkCode(int code)
{
if (code != CURLE_OK)
throw std::runtime_error(
"Curl returned error: " +
std::string(curl_easy_strerror((CURLcode)code) +
std::string(" (") +
std::to_string(code) +
std::string(")")));
}
size_t Curl::_s_write_callback(char * ptr, size_t size, size_t nmemb, void * userdata)
{
Curl* instance = (Curl*)userdata;
if (!instance->_write_fn)
return 0;
return (size_t)instance->_write_fn(ptr, size*nmemb);
}
size_t Curl::_s_read_callback(char * ptr, size_t size, size_t nitems, void * userdata)
{
Curl* instance = (Curl*)userdata;
if (!instance->_read_fn)
return 0;
return (size_t)instance->_read_fn(ptr, size*nitems);
}
int Curl::_s_ioctl_callback(void * handle, int cmd, void * userdata)
{
if (cmd != CURLIOCMD_RESTARTREAD)
return CURLIOE_UNKNOWNCMD;
Curl* instance = (Curl*)userdata;
if (!instance->_ioctl_restart_fn)
return CURLIOE_FAILRESTART;
return instance->_ioctl_restart_fn() ? CURLIOE_OK : CURLIOE_FAILRESTART;
}
int Curl::_s_seek_callback(void * userdata, long long offset, int origin)
{
Curl* instance = (Curl*)userdata;
try {
return instance->_seek_fn(offset, origin) ? CURL_SEEKFUNC_OK : CURL_SEEKFUNC_CANTSEEK;
}
catch (std::exception) {
return CURL_SEEKFUNC_FAIL;
}
}
int Curl::_s_xferinfo_callback(void * userdata, long long dltotal, long long dlnow, long long ultotal, long long ulnow)
{
try {
Curl* instance = (Curl*)userdata;
if (instance->_xferinfo_fn) {
instance->_xferinfo_fn(dltotal, dlnow, ultotal, ulnow);
}
return 0;
}
catch (std::exception)
{
return 1;
}
}
size_t Curl::_s_header_callback(char * buffer, size_t size, size_t nitems, void * userdata)
{
try {
Curl* instance = (Curl*)userdata;
if (instance->_header_fn) {
std::string str(buffer, buffer + (size*nitems));
instance->_header_fn(str);
}
return size*nitems;
}
catch (std::exception)
{
return 0;
}
}
int Curl::_s_debug_callback(void* handle, int type, char * data, size_t size, void *userdata)
{
Curl* instance = (Curl*)userdata;
if (instance->_debug_fn)
instance->_debug_fn((InfoType)type, data, size);
return 0;
}
int Curl::_s_fnmatch_callback(void * ptr, const char * pattern, const char * string)
{
Curl* instance = (Curl*)ptr;
try {
return instance->_match_fn(pattern, string) ? CURL_FNMATCHFUNC_MATCH : CURL_FNMATCHFUNC_NOMATCH;
}
catch (std::exception)
{
return CURL_FNMATCHFUNC_FAIL;
}
}
int Curl::_s_ssh_keycallback(void * curl, const void * knownkey, const void * foundkey, int khmatch, void * userdata)
{
Curl* instance = (Curl*)userdata;
const struct curl_khkey* known = (const struct curl_khkey*)knownkey;
const struct curl_khkey* found = (const struct curl_khkey*)foundkey;
SSHKey key_known, key_found;
key_known._data = known->len == 0 ? std::string(known->key) : std::string(known->key, known->key + known->len);
key_found._data = found->len == 0 ? std::string(found->key) : std::string(found->key, found->key + found->len);
key_known._type = (SSHKeyType)known->keytype;
key_found._type = (SSHKeyType)found->keytype;
return (int)(instance->_ssh_key_match_fn(key_known, key_found, (SSHKeyMatch)khmatch));
}
long Curl::getProtocolMask(const std::string & mask)
{
static std::map<std::string, long> names = {
{ "http", CURLPROTO_HTTP },
{ "https", CURLPROTO_HTTPS },
{ "ftp", CURLPROTO_FTP },
{ "ftps", CURLPROTO_FTPS },
{ "scp", CURLPROTO_SCP },
{ "sftp", CURLPROTO_SFTP },
{ "telnet", CURLPROTO_TELNET },
{ "ldap", CURLPROTO_LDAP },
{ "ldaps", CURLPROTO_LDAPS },
{ "dict", CURLPROTO_DICT },
{ "file", CURLPROTO_FILE },
{ "tftp", CURLPROTO_TFTP },
{ "imap", CURLPROTO_IMAP },
{ "imaps", CURLPROTO_IMAPS },
{ "pop3", CURLPROTO_POP3 },
{ "pop3s", CURLPROTO_POP3S },
{ "smtp", CURLPROTO_SMTP },
{ "smtps", CURLPROTO_SMTPS },
{ "rtsp", CURLPROTO_RTSP },
{ "rtmp", CURLPROTO_RTMP },
{ "rtmpt", CURLPROTO_RTMPT },
{ "rtmpe", CURLPROTO_RTMPE },
{ "rtmpte", CURLPROTO_RTMPTE },
{ "rtmps",CURLPROTO_RTMPS },
{ "rtmpts", CURLPROTO_RTMPTS },
{ "gopher", CURLPROTO_GOPHER },
#if CURL_AT_LEAST_VERSION(7,40,0)
{ "smb", CURLPROTO_SMB },
{ "smbs", CURLPROTO_SMBS },
#endif
{ "all", CURLPROTO_ALL }
};
long result = 0;
for (const std::string& name : stringSplit(" ", mask))
result |= names[name];
return result;
}
std::shared_ptr<void> Curl::toSList(const std::vector<std::string>& vector)
{
curl_slist* list = nullptr;
for (const std::string& str : vector)
{
list = curl_slist_append(list, str.c_str());
}
return std::shared_ptr<void>(list, [](void* ptr) { curl_slist_free_all((curl_slist*)ptr); });
}
std::vector<std::string> Curl::fromSList(void * list)
{
struct curl_slist* slist = (struct curl_slist*)list;
std::vector<std::string> res;
while (slist != nullptr)
{
res.push_back(slist->data);
slist = slist->next;
}
return res;
}
Curl::CurlGlobalInit Curl::_auto_init;
Curl::CurlGlobalInit::CurlGlobalInit()
{
curl_global_init(CURL_GLOBAL_ALL);
}
Curl::CurlGlobalInit::~CurlGlobalInit()
{
curl_global_cleanup();
}
}
}
| 23.907077 | 121 | 0.684783 | Thalhammer |
226d4baca5f63f97260efa9e2d9c7ef2d2703612 | 4,404 | cc | C++ | src/thirdparty/acg_localizer/src/solver/solverbase.cc | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | src/thirdparty/acg_localizer/src/solver/solverbase.cc | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | src/thirdparty/acg_localizer/src/solver/solverbase.cc | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | /*===========================================================================*\
* *
* ACG Localizer *
* Copyright (C) 2011 by Computer Graphics Group, RWTH Aachen *
* www.rwth-graphics.de *
* *
*---------------------------------------------------------------------------*
* This file is part of ACG Localizer *
* *
* ACG Localizer 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 *
* (at your option) any later version. *
* *
* ACG Localizer 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 ACG Localizer. If not, see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*
* Definition of Solver base class
*
* Author: Martin Habbecke <M.Habbecke@gmx.de>
* Version: Revision: 1.8
* Date: 2011-10-03 17:30
*/
#include <float.h>
#include <math.h>
#include "solverbase.hh"
using namespace Util::Math;
namespace Util {
namespace CorrSolver {
SolverBase::SolverBase()
{
}
SolverBase::~SolverBase()
{
}
void SolverBase::clear( void )
{
mv_corresp.clear();
mv_correspScaled.clear();
}
void SolverBase::scaleCorrespondences( void )
{
CorrespondenceVec::iterator cIter, cEnd;
cEnd = mv_corresp.end();
Vector2D feat1, feat2;
double n;
m_center1 = Vector2D( 0.0, 0.0 );
m_center2 = Vector2D( 0.0, 0.0 );
//////////////////////////////////////////////
// determine c.o.g. in both images and also x- and y-ranges
n = 1.0;
for( cIter = mv_corresp.begin();
cIter != cEnd;
++cIter )
{
m_center1 = cIter->m_feature1 * (1.0/n) + m_center1 * ((n-1.0) / n);
m_center2 = cIter->m_feature2 * (1.0/n) + m_center2 * ((n-1.0) / n);
n += 1.0f;
}
///////////////////////////////////////////////
// move features to COG and compute scaling factors
mv_correspScaled.clear();
n = 1.0;
m_scale1 = m_scale2 = 0.0;
for( cIter = mv_corresp.begin();
cIter != cEnd;
++cIter )
{
feat1 = cIter->m_feature1 - m_center1;
feat2 = cIter->m_feature2 - m_center2;
m_scale1 = m_scale1 * ((n-1.0) / n) + feat1.norm() * (1.0 / n);
m_scale2 = m_scale2 * ((n-1.0) / n) + feat2.norm() * (1.0 / n);
mv_correspScaled.push_back( Correspondence( feat1, feat2 ) );
n += 1.0f;
}
m_scale1 = 1.41421 / m_scale1;
m_scale2 = 1.41421 / m_scale2;
//////////////////////////////////////////////
// scale coords in both images
cEnd = mv_correspScaled.end();
for( cIter = mv_correspScaled.begin();
cIter != cEnd;
++cIter )
{
cIter->m_feature1 *= m_scale1;
cIter->m_feature2 *= m_scale2;
}
////////////////////////////////////////////
// create scaling matrices that will be multiplied
// to result matrix
m_matScale1.clear();
m_matScale1( 0, 0 ) = m_scale1;
m_matScale1( 1, 1 ) = m_scale1;
m_matScale1( 0, 2 ) = -m_center1[ 0 ] * m_scale1;
m_matScale1( 1, 2 ) = -m_center1[ 1 ] * m_scale1;
m_matScale1( 2, 2 ) = 1.0;
m_matScale2T.clear();
m_matScale2T( 0, 0 ) = m_scale2;
m_matScale2T( 1, 1 ) = m_scale2;
m_matScale2T( 2, 0 ) = -m_center2[ 0 ] * m_scale2;
m_matScale2T( 2, 1 ) = -m_center2[ 1 ] * m_scale2;
m_matScale2T( 2, 2 ) = 1.0;
}
}
}
| 27.873418 | 80 | 0.45663 | rajvishah |
226efccb72784f9e6191e7a3795c1b4c7b162605 | 1,691 | cpp | C++ | Classes/Foundation/NSObject.cpp | duranamu/Foundation | 5569fb52cb93ef11dcf4f779a2d1ea4b8cfeb0df | [
"MIT"
] | 2 | 2015-06-29T06:49:20.000Z | 2016-10-30T04:25:35.000Z | Classes/Foundation/NSObject.cpp | duranamu/Foundation | 5569fb52cb93ef11dcf4f779a2d1ea4b8cfeb0df | [
"MIT"
] | null | null | null | Classes/Foundation/NSObject.cpp | duranamu/Foundation | 5569fb52cb93ef11dcf4f779a2d1ea4b8cfeb0df | [
"MIT"
] | null | null | null | /****************************************************************************
Foundation OpenSource Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <Foundation/NSObject.h>
#include <Foundation/NSCopying.h>
#include <Foundation/NSException.h>
#include <Foundation/NSString.h>
void
NSObject::dealloc()
{
}
vid
NSObject::copy()
{
if(copying)
{
return copying->copyWithZone(self);
}else{
throw NSException::exceptionWithName_reason_userInfo(
NSSTR("Panic"),NSSTR("Not Implementation for copyWithZone"),nil);
}
}
NSString*
NSObject::description()
{
return NSSTR("NSObject");
} | 38.431818 | 77 | 0.698995 | duranamu |
227365972f4cb42f159fc1c6f7cdf04f407e28a0 | 646 | cpp | C++ | poj/3438/main.cpp | nimitz871016/acm | a59aba6333e48473f9ef3c3702965b5ba2c4d741 | [
"MIT"
] | null | null | null | poj/3438/main.cpp | nimitz871016/acm | a59aba6333e48473f9ef3c3702965b5ba2c4d741 | [
"MIT"
] | null | null | null | poj/3438/main.cpp | nimitz871016/acm | a59aba6333e48473f9ef3c3702965b5ba2c4d741 | [
"MIT"
] | null | null | null | //
// main.cpp
// 3438
// 水题
// Created by Nimitz_007 on 16/7/31.
// Copyright © 2016年 Fujian Ruijie Networks Co., Ltd. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
int n, count;
char c,pre;
scanf("%d\n",&n);
while(n--){
count = 1;
scanf("%c",&pre);
while(scanf("%c",&c) && c != '\n'){
if(c != pre){
printf("%d%c",count,pre);
pre = c;
count = 1;
continue;
}else{
count++;
}
}
printf("%d%c\n",count,pre);
}
return 0;
}
| 20.1875 | 75 | 0.417957 | nimitz871016 |
22750dbcc63eb171748ad3043d12a84c0d36e940 | 72,060 | cxx | C++ | dev/ese/src/_esefile/xsum.cxx | ScriptBox99/Extensible-Storage-Engine | 3bcf428c8a041733043e18fd9ae55cffeba307b2 | [
"MIT"
] | 803 | 2021-01-30T02:25:26.000Z | 2022-03-23T15:50:48.000Z | dev/ese/src/_esefile/xsum.cxx | ScriptBox99/Extensible-Storage-Engine | 3bcf428c8a041733043e18fd9ae55cffeba307b2 | [
"MIT"
] | 10 | 2021-01-30T23:45:49.000Z | 2021-07-06T22:03:58.000Z | dev/ese/src/_esefile/xsum.cxx | ScriptBox99/Extensible-Storage-Engine | 3bcf428c8a041733043e18fd9ae55cffeba307b2 | [
"MIT"
] | 49 | 2021-01-30T11:04:35.000Z | 2022-03-24T11:25:10.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/*******************************************************************
Each database page and database header page contains a 8-byte checksum.
The checksum is the first 8 bytes on the page. The checksum incorporates
the page number so that getting back the wrong page will generate a
checksum error.
There are two different formats of page checksums, called (imaginatively
enough) old and new:
- Old: this is the format used by 5.5 through Exchange 2003 SP1, and
Windows 2000 through Longhorn. The first DWORD of the checksum
is an XOR of all DWORDs on the page (except the checksum) along
with the seed value of 0x89abcdef. The second DWORD is the pgno
of the page. XOR is used because it's very easy to optimize on
processors with wide words lengths.
The old checksum format is actually a 4-byte format, we expand
it to 8-bytes for pages by making the pgno check part of checksum
validation. Database and logfile headers don't have a pgno, so
they in fact have a 4-byte checksum.
- New: XOR checksums can only detect problems, not correct them. ECC
checksums can correct single-bit errors in pages, which are actually
a significant percentage of problems we see. Calculating and verifying
ECC checksums is more expensive though.
The new checksum format uses an ECC checksum to allow correction of
single-bit errors in pages.
In an I/O intensive scenario checksum calculation and verification can become
a performance problem. To optimize checksumming as much as possible we take
advantage of different processor features (64-bit words, SSE instructions, SSE2
instructions). This leads to several implementations of the checksum routine,
for different architectures. All checksum calls are indirected through a function
pointer, which is set at runtime, depending on the capabilities of the processor
we are running on.
In order to determine which type of checksum should be used, there is a
bit in the database header/database page which tells us what type of
checksum to use. We always have to consider that a corruption could flip
that bit, so the actual flow of checksumming a page is a little complex to
deal with that.
*******************************************************************/
#include "esefile.hxx"
#include <limits.h>
#include <memory.h>
#include <stddef.h>
#include "xsum.hxx"
#include <intrin.h>
#ifdef _IA64_
extern "C" {
void __lfetch( INT Level,void const *Address );
#pragma intrinsic( __lfetch )
} // extern "C"
#define MD_LFHINT_NONE 0x00
#define MD_LFHINT_NT1 0x01
#define MD_LFHINT_NT2 0x02
#define MD_LFHINT_NTA 0x03
#endif // _IA64_
// ****************************************************************
// page checksum routines
// ****************************************************************
// manipulate bits on the page
inline BOOL FGetBit( const void * const pv, const INT ibitOffset );
// get and set the new checksum format flag
static UINT IbitNewChecksumFormatFlag( const PAGETYPE pagetype );
static BOOL FPageHasNewChecksumFormat( const void * const pv, const PAGETYPE pagetype );
// get and set the checksum
static BOOL FPageHasLongChecksum( const PAGETYPE pagetype );
static ULONG ShortChecksumFromPage( const void * const pv );
static PAGECHECKSUM LongChecksumFromPage( const void * const pv );
static PAGECHECKSUM ChecksumFromPage( const void * const pv, const PAGETYPE pagetype );
static PAGECHECKSUM ComputePageChecksum(
const void* const pv,
const UINT cb,
const PAGETYPE pagetype,
const ULONG pgno,
// set fNew to compute new ECC for a page (R/W wrt the large page!!)
// reset fNew to computer ECC for verification purpose (R/O wrt the page)
const BOOL fNew = fFalse );
//
extern INT g_cbPage;
static BOOL FIsSmallPage( ULONG cbPage ) { return cbPage <= 1024 * 8; }
static BOOL FIsSmallPage( void ) { return FIsSmallPage( g_cbPage ); }
typedef XECHECKSUM (*PFNCHECKSUMNEWFORMAT)( const unsigned char * const, const ULONG, const ULONG, BOOL );
typedef ULONG (*PFNCHECKSUMOLDFORMAT)( const unsigned char * const, const ULONG );
// ****************************************************************
// XOR checksum routines
// ****************************************************************
static XECHECKSUM LongChecksumFromShortChecksum( const ULONG xorChecksum, const ULONG pgno );
static ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb );
static ULONG ChecksumOldFormat( const unsigned char * const pb, const ULONG cb );
static ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb );
static ULONG ChecksumOldFormatSSE( const unsigned char * const pb, const ULONG cb );
static ULONG ChecksumOldFormatSSE2( const unsigned char * const pb, const ULONG cb );
static PFNCHECKSUMOLDFORMAT pfnChecksumOldFormat = ChecksumSelectOldFormat;
// ****************************************************************
// ECC checksum routines
// ****************************************************************
static XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
// see comments in checksum_amd64.cxx to see why these are in a separate file
static XECHECKSUM ChecksumNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
static XECHECKSUM ChecksumNewFormat64Bit( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
static XECHECKSUM ChecksumNewFormatSSE( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
static XECHECKSUM ChecksumNewFormatSSE2( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue);
static PFNCHECKSUMNEWFORMAT pfnChecksumNewFormat = ChecksumSelectNewFormat;
// ================================================================
static XECHECKSUM LongChecksumFromShortChecksum( const ULONG xorChecksum, const ULONG pgno )
// ================================================================
{
Assert( 0 != pgno );
XECHECKSUM checksum = ( ( XECHECKSUM )pgno ) << 32 | xorChecksum;
return checksum;
}
// ================================================================
static ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// Decide which checksum mechanism to use and set the function pointer
// to it. Subsequent calls to the checksum code will call the correct
// function directly
//
// We check for SSE2 instructions before checking to see if this is
// a 64-bit machine, so AMD64 machines will end up using ChecksumOldFormatSSE2.
// That is good as the SSE2 implementation will be faster than the plain
// 64-bit implementation.
//
// Here is a mapping of processor type to function:
//
// P2/P3 : ChecksumOldFormatSSE
// P4 : ChecksumOldFormatSSE2
// AMD64 : ChecksumOldFormatSSE2
// IA64 : ChecksumOldFormat64Bit
// Cyrix etc. : ChecksumOldFormat
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumSelectOldFormat;
if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
pfn = ChecksumOldFormatSSE2;
}
else
{
pfn = ChecksumOldFormatSSE;
}
}
else if( sizeof( void * ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumOldFormat64Bit;
}
else
{
pfn = ChecksumOldFormat;
}
pfnChecksumOldFormat = pfn;
return (*pfn)( pb, cb );
}
// ================================================================
static ULONG ChecksumOldFormat( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// Plain old unrolled-loop checksum that should work on any processor
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat;
Unused( pfn );
const ULONG * pdw = (ULONG *)pb;
INT cbT = cb;
// remove the first unsigned long, as it is the checksum itself
ULONG dwChecksum = 0x89abcdef ^ pdw[0];
do
{
dwChecksum ^= pdw[0]
^ pdw[1]
^ pdw[2]
^ pdw[3]
^ pdw[4]
^ pdw[5]
^ pdw[6]
^ pdw[7];
cbT -= 32;
pdw += 8;
} while ( cbT );
return dwChecksum;
}
// ================================================================
static ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// Do checksumming 64 bits at a time (the native word size)
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat64Bit;
Unused( pfn );
const unsigned __int64* pqw = (unsigned __int64 *)pb;
unsigned __int64 qwChecksum = 0;
ULONG cbT = cb;
// checksum the first four bytes twice to remove the checksum
qwChecksum ^= pqw[0] & 0x00000000FFFFFFFF;
do
{
#ifdef _IA64_
__lfetch( MD_LFHINT_NTA, (unsigned char *)(pqw + 4) );
#endif
qwChecksum ^= pqw[0];
qwChecksum ^= pqw[1];
qwChecksum ^= pqw[2];
qwChecksum ^= pqw[3];
cbT -= ( 4 * sizeof( unsigned __int64 ) );
pqw += 4;
} while ( cbT );
const unsigned __int64 qwUpper = ( qwChecksum >> ( sizeof( ULONG ) * 8 ) );
const unsigned __int64 qwLower = qwChecksum & 0x00000000FFFFFFFF;
qwChecksum = qwUpper ^ qwLower;
const ULONG ulChecksum = static_cast<ULONG>( qwChecksum ) ^ 0x89abcdef;
return ulChecksum;
}
// ================================================================
inline void CachePrefetch( const void * const p )
// ================================================================
{
#ifdef _X86_
_asm
{
mov eax,p
_emit 0x0f // PrefetchNTA
_emit 0x18
_emit 0x00
}
#endif
}
// ================================================================
static ULONG ChecksumOldFormatSSE( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// Use the prefetch instruction to bring memory into the processor
// cache prior to use
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormatSSE;
Unused( pfn );
const ULONG * pdw = (ULONG *)pb;
INT cbT = cb;
// touching this memory puts the page in the processor TLB (needed
// for prefetch) and brings in the first cacheline (cacheline 0)
ULONG dwChecksum = 0x89abcdef ^ pdw[0];
do
{
#if (defined _AMD64_ || defined _X86_ )
#if 1
_mm_prefetch ( (char *)(pdw + 16), _MM_HINT_NTA );
#else
CachePrefetch ( pdw + 16 );
#endif
#endif
dwChecksum ^= pdw[0]
^ pdw[1]
^ pdw[2]
^ pdw[3]
^ pdw[4]
^ pdw[5]
^ pdw[6]
^ pdw[7];
cbT -= 32;
pdw += 8;
} while ( cbT );
return dwChecksum;
}
#if 1
// ================================================================
static ULONG ChecksumOldFormatSSE2( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// SSE2 supports 128-bit XOR operations. XOR the page using the SSE2
// instructions and collapse the checksum at the end.
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormatSSE2;
Unused( pfn );
#if (defined _AMD64_ || defined _X86_ )
__m128i owChecksum = _mm_setzero_si128();
const __m128i * pow = (__m128i *)pb;
const __m128i * const powMax = (__m128i *)(pb + cb);
// checksum the first eight bytes twice to remove the checksum
const ULONG * pdw = (ULONG *)pb;
ULONG ulChecksum = 0x89abcdef ^ pdw[0];
do
{
_mm_prefetch ( (char *)(pow + 16), _MM_HINT_NTA );
__m128i owChecksumT1 = _mm_xor_si128 ( pow[0], pow[1] );
const __m128i owChecksumT2 = _mm_xor_si128 ( pow[2], pow[3] );
__m128i owChecksumT3 = _mm_xor_si128 ( pow[4], pow[5] );
const __m128i owChecksumT4 = _mm_xor_si128 ( pow[6], pow[7] );
owChecksumT1 = _mm_xor_si128 ( owChecksumT1, owChecksumT2 );
owChecksumT3 = _mm_xor_si128 ( owChecksumT3, owChecksumT4 );
owChecksum = _mm_xor_si128 ( owChecksum, owChecksumT1 );
owChecksum = _mm_xor_si128 ( owChecksum, owChecksumT3 );
pow += 8;
} while ( pow < powMax );
ulChecksum ^=
owChecksum.m128i_i32[0]
^ owChecksum.m128i_i32[1]
^ owChecksum.m128i_i32[2]
^ owChecksum.m128i_i32[3];
return ulChecksum;
#else
// we should never get here
return 0x12345678;
#endif
}
#endif // 1
#if 1
#else
//================================================================
static __declspec( naked ) ULONG __stdcall ChecksumOldFormatSSE2_Emitted( const unsigned char * const pb, const ULONG cb )
//================================================================
//
// Exchange's (older) C compiler doesn't support SSE2 intrinsics
//
// The code uses x86 calling convention, it is NOT compatible with AMD64 calling convention
// Under x86, all the xmm regs are caller saved, this is NOT the case for AMD64.
//
// Following is the assembly source, it generates the machine code to be emitted
//
/****************************************************************
.586
.xmm
.model flat
;================================================
; DWORD DwXORChecksumESESSE2( const BYTE * const pb, const DWORD cb )
; pb should be 128-Byte aligned
; cb should be multiple of 128
;================================================
PUBLIC _DwXORChecksumESESSE2@8
_TEXT SEGMENT
_DwXORChecksumESESSE2@8 PROC NEAR
mov eax, [esp+4] ; edx = pb
mov ecx, [esp+8] ; ecx = cb
mov edx, 128 ; edx = stride, cacheline size
movd xmm0, [eax] ; first dword is checksum itself
pxor xmm1, xmm1
pxor xmm2, xmm2
pxor xmm3, xmm3
pxor xmm4, xmm4
pxor xmm5, xmm5
pxor xmm6, xmm6
pxor xmm7, xmm7
;================================
; Use 8 xmm regs, total 128bytes
;================================
align 16
xorloop:
prefetchnta [eax+edx*4] ; prefetch distance can be tuned
pxor xmm0, [eax+16*0]
pxor xmm1, [eax+16*1]
pxor xmm2, [eax+16*2]
pxor xmm3, [eax+16*3]
pxor xmm4, [eax+16*4]
pxor xmm5, [eax+16*5]
pxor xmm6, [eax+16*6]
pxor xmm7, [eax+16*7]
add eax, edx
sub ecx, edx
ja xorloop
;================================
; Consolidate 128 Bytes to 16 Bytes
;================================
pxor xmm0, xmm1
pxor xmm2, xmm3
pxor xmm4, xmm5
pxor xmm6, xmm7
pxor xmm0, xmm2
pxor xmm4, xmm6
pxor xmm0, xmm4
;================================
; Consolidate 16 Bytes to 4 Bytes
;================================
pshufd xmm1, xmm0, 04eh
pxor xmm0, xmm1
pshufd xmm2, xmm0, 0b1h
pxor xmm0, xmm2
movd eax, xmm0
xor eax, 089abcdefh ; 89abcdefH, just our seed
ret 8
_DwXORChecksumSSE2Asm@8 ENDP
_TEXT ENDS
END
****************************************************************/
{
#pragma push_macro( "emit2" )
#pragma push_macro( "emit3" )
#pragma push_macro( "emit4" )
#pragma push_macro( "emit5" )
#define emit2(b1,b2) __asm _emit b1 __asm _emit b2
#define emit3(b1,b2,b3) emit2(b1,b2) __asm _emit b3
#define emit4(b1, b2, b3, b4) emit3(b1,b2,b3) __asm _emit b4
#define emit5(b1, b2, b3, b4, b5) emit4(b1,b2,b3,b4) __asm _emit b5
__asm mov eax, [esp+4]
__asm mov ecx, [esp+8]
__asm mov edx, 0x80
emit4( 0x66, 0x0f, 0x6e, 0x00 ); // movd xmm0,dword ptr [eax]
emit4( 0x66, 0x0f, 0xef, 0xc9 ); // pxor xmm1,xmm1
emit4( 0x66, 0x0f, 0xef, 0xd2 ); // pxor xmm2,xmm2
emit4( 0x66, 0x0f, 0xef, 0xdb ); // pxor xmm3,xmm3
emit4( 0x66, 0x0f, 0xef, 0xe4 ); // pxor xmm4,xmm4
emit4( 0x66, 0x0f, 0xef, 0xed ); // pxor xmm5,xmm5
emit4( 0x66, 0x0f, 0xef, 0xf6 ); // pxor xmm6,xmm6
emit4( 0x66, 0x0f, 0xef, 0xff ); // pxor xmm7,xmm7
__asm align 16
xorloop:
emit4( 0x0f, 0x18, 0x04, 0x90 ); // prefetchtnta byte ptr [eax+edx*4]
emit4( 0x66, 0x0f, 0xef, 0x00 ); // pxor xmm0,oword ptr [eax]
emit5( 0x66, 0x0f, 0xef, 0x48, 0x10 ); // pxor xmm1,oword ptr [eax+0x10]
emit5( 0x66, 0x0f, 0xef, 0x50, 0x20 ); // pxor xmm2,oword ptr [eax+0x20]
emit5( 0x66, 0x0f, 0xef, 0x58, 0x30 ); // pxor xmm3,oword ptr [eax+0x30]
emit5( 0x66, 0x0f, 0xef, 0x60, 0x40 ); // pxor xmm4,oword ptr [eax+0x40]
emit5( 0x66, 0x0f, 0xef, 0x68, 0x50 ); // pxor xmm5,oword ptr [eax+0x50]
emit5( 0x66, 0x0f, 0xef, 0x70, 0x60 ); // pxor xmm6,oword ptr [eax+0x60]
emit5( 0x66, 0x0f, 0xef, 0x78, 0x70 ); // pxor xmm7,oword ptr [eax+0x70]
__asm add eax, edx
__asm sub ecx, edx
__asm ja xorloop
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit4( 0x66, 0x0f, 0xef, 0xd3 ); // pxor xmm2,xmm3
emit4( 0x66, 0x0f, 0xef, 0xe5 ); // pxor xmm4,xmm5
emit4( 0x66, 0x0f, 0xef, 0xf7 ); // pxor xmm6,xmm7
emit4( 0x66, 0x0f, 0xef, 0xc2 ); // pxor xmm0,xmm2
emit4( 0x66, 0x0f, 0xef, 0xe6 ); // pxor xmm4,xmm6
emit4( 0x66, 0x0f, 0xef, 0xc4 ); // pxor xmm0,xmm4
emit5( 0x66, 0x0f, 0x70, 0xc8, 0x4e ); // pshufd xmm1,xmm0,0x4e
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit5( 0x66, 0x0f, 0x70, 0xd0, 0xb1 ); // pshufd xmm2,xmm0,0xb1
emit4( 0x66, 0x0f, 0xef, 0xc2 ); // pxor xmm0,xmm2
emit4( 0x66, 0x0f, 0x7e, 0xc0 ); // movd eax,xmm0
__asm xor eax, 0x89abcdef
__asm ret 0x8
}
// ================================================================
static ULONG ChecksumOldFormatSSE2_Wrapper( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// ChecksumOldFormatSSE2_Emitted is a __stdcall function, but that might not be
// the calling convention we are using. This standard wrapper presents
// a function with the expected signature
//
//-
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormatSSE2_Wrapper;
return ChecksumOldFormatSSE2_Emitted( pb, cb );
}
#endif // 1
// ================================================================
static XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// Decide which checksum mechanism to use and set the function pointer
// to it. Subsequent calls to the checksum code will call the correct
// function directly
//
// We check for SSE2 instructions before checking to see if this is
// a 64-bit machine, so AMD64 machines will end up using ChecksumNewFormatSSE2.
// That is good as the SSE2 implementation will be faster than the plain
// 64-bit implementation.
//
// Here is a mapping of processor type to function:
//
// P2/P3 : ChecksumNewFormatSSE
// P4 : ChecksumNewFormatSSE2
// AMD64 : ChecksumNewFormatSSE2
// IA64 : ChecksumNewFormat64Bit
// Cyrix etc. : ChecksumNewFormat
//
//-
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumSelectNewFormat;
if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
pfn = ChecksumNewFormatSSE2;
}
else
{
pfn = ChecksumNewFormatSSE;
}
}
else if( sizeof( void * ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumNewFormat64Bit;
}
else
{
pfn = ChecksumNewFormat;
}
pfnChecksumNewFormat = pfn;
return (*pfn)( pb, cb, pgno, fHeaderBlock );
}
// ================================================================
inline XECHECKSUM MakeChecksumFromECCXORAndPgno(
const ULONG eccChecksum,
const ULONG xorChecksum,
const ULONG pgno )
// ================================================================
{
const XECHECKSUM low = xorChecksum ^ pgno;
const XECHECKSUM high = ( XECHECKSUM )eccChecksum << 32;
return ( high | low );
}
// ================================================================
__declspec( align( 128 ) ) static const signed char g_bParityLookupTable[ 256 ] =
// ================================================================
{
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0x0x
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0x1x
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0x2x
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0x3x
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0x4x
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0x5x
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0x6x
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0x7x
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0x8x
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0x9x
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0xax
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0xbx
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0xcx
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0xdx
-1, 0, 0, -1, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, 0, -1, // 0xex
0, -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1, -1, 0, // 0xfx
};
// ================================================================
inline LONG lParityMask( const ULONG dw )
// ================================================================
//
// Compute a 32-bit parity mask of a 32-bit integer
//
//-
{
const ULONG dw1 = dw >> 16;
const ULONG dw2 = dw ^ dw1;
const ULONG dw3 = dw2 >> 8;
const ULONG dw4 = dw2 ^ dw3;
return g_bParityLookupTable[ dw4 & 0xff ];
}
// ================================================================
static ULONG DwXORChecksumBasic( const unsigned char * const pb, const ULONG cb )
// ================================================================
//
// Plain old unrolled-loop checksum that should work on any processor
//
//-
{
const ULONG * pdw = (ULONG *)pb;
INT cbT = cb;
// remove the first QWORD, as it is the checksum itself
ULONG dwChecksum = pdw[0] ^ pdw[1];
do
{
dwChecksum ^= pdw[0]
^ pdw[1]
^ pdw[2]
^ pdw[3]
^ pdw[4]
^ pdw[5]
^ pdw[6]
^ pdw[7];
cbT -= 32;
pdw += 8;
} while ( cbT );
return dwChecksum;
}
// ================================================================
static XECHECKSUM ChecksumNewFormatBasic( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// optmized ECC function for 32-bit CPU, 32-byte cache line, no prefetching
// the data is organized into an array of bits that is 32*4=128 bits wide
// each line of CPU cache will hold 2 rows of data
//
//-
{
// ensure correct signature of the function
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormatBasic;
Unused( pfn );
// data size sanity check
//
Assert( 4 == sizeof( ULONG ) );
// cb should be an order of 2 and between 1k and 8k
//
Assert( 0 == ( cb & ( cb -1 ) ) );
Assert( 1024 <= cb && cb <= 8192 );
// pb should align to 32 (2 rows of CPU cache)
//
Assert( 0 == ( ( uintptr_t )pb & ( 32 - 1 ) ) );
//================================================
// long* is easier to use than char*
//
const ULONG* pdw = ( ULONG* )pb;
const ULONG cdw = cb / sizeof( *pdw );
//================================================
// compute ECC bits shown as '1'
// 1111 1111 1000 0000 1111 1111 1000 0000
//
ULONG p = 0;
// p0, p1, p2, p3 hold accumulated column parity bits (32*4=128 bits)
//
unsigned p0 = 0, p1 = 0, p2 = 0, p3 = 0;
{
// combine 16-bit index and ~index together into a 32-bit double index
//
ULONG idxp = 0xff800000;
// loop control variable
//
ULONG i = 0;
// treat the first 64-bit of the data always as 0
//
ULONG pT0 = 0;
ULONG pT1 = 0;
if ( fHeaderBlock )
{
goto Start;
}
// unroll the loop to 32-byte cache line boundary
// one iteration will process 2 rows of data in one cache line.
//
do
{
// read one row (first half of the cache line) from data (32*4=128 bits)
//
pT0 = pdw[ i + 0 ];
pT1 = pdw[ i + 1 ];
Start:
const ULONG pT2 = pdw[ i + 2 ];
const ULONG pT3 = pdw[ i + 3 ];
// update accumulated column parity bits
//
p0 ^= pT0;
p1 ^= pT1;
p2 ^= pT2;
p3 ^= pT3;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT0 ^ pT1 ^ pT2 ^ pT3 );
// update double index
//
idxp += 0xff800080;
// read another row (second half of the cache line) from data (32*4=128 bits)
//
const ULONG pT4 = pdw[ i + 4 ];
const ULONG pT5 = pdw[ i + 5 ];
const ULONG pT6 = pdw[ i + 6 ];
const ULONG pT7 = pdw[ i + 7 ];
// update accumulated column parity bits
//
p0 ^= pT4;
p1 ^= pT5;
p2 ^= pT6;
p3 ^= pT7;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT4 ^ pT5 ^ pT6 ^ pT7 );
// update double index
//
idxp += 0xff800080;
// update loop control variable
//
i += 8;
// inform compiler the loop won't quit in 1st iteration.
//
__assume( 8 < cdw );
}while ( i < cdw );
}
//================================================
// reduce 128 column parity bits (p0, p1, p2, p3) into 32 bits
//
// compute ECC bits shown as '1'
// 0000 0000 0110 0000 0000 0000 0110 0000
//
p |= 0x00400000 & lParityMask( p0 ^ p1 );
p |= 0x00000040 & lParityMask( p2 ^ p3 );
const ULONG r0 = p0 ^ p2;
const ULONG r1 = p1 ^ p3;
p |= 0x00200000 & lParityMask( r0 );
p |= 0x00000020 & lParityMask( r1 );
// r2 holds 32-bit reduced column parity bits
//
const ULONG r2 = r0 ^ r1;
//================================================
// compute ECC bits shown as '1'
// 0000 0000 0001 1111 0000 0000 0001 1111
//
ULONG r = 0;
// double index
//
ULONG idxr = 0xffff0000;
// loop through every column parity bit
//
for ( ULONG i = 1; i; i += i )
{
const LONG mask = -!!( r2 & i );
r ^= mask & idxr;
idxr += 0xffff0001;
}
//================================================
// mask some high bits out according to the data size
//
const ULONG mask = ( cb << 19 ) - 1;
// assemble final ECC
//
const ULONG eccChecksum = p & 0xffe0ffe0 & mask | r & 0x001f001f;
const ULONG xorChecksum = DwXORChecksumBasic( pb, cb );
return MakeChecksumFromECCXORAndPgno( eccChecksum, xorChecksum, pgno );
}
// ================================================================
static XECHECKSUM ChecksumNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// optmized ECC function for 32-bit CPU, 32-byte cache line, no prefetching
// the data is organized into an array of bits that is 32*4=128 bits wide
// each line of CPU cache will hold 2 rows of data
//
//-
{
// ensure correct signature of the function
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormat;
Unused( pfn );
// data size sanity check
//
Assert( 4 == sizeof( ULONG ) );
// cb should be an order of 2 and between 1k and 8k
//
Assert( 0 == ( cb & ( cb -1 ) ) );
Assert( 1024 <= cb && cb <= 8192 );
// pb should align to 32 (2 rows of CPU cache)
//
Assert( 0 == ( ( uintptr_t )pb & ( 32 - 1 ) ) );
//================================================
// long* is easier to use than char*
//
const ULONG* pdw = ( ULONG* )pb;
const ULONG cdw = cb / sizeof( *pdw );
//================================================
// compute ECC bits shown as '1'
// 1111 1111 1000 0000 1111 1111 1000 0000
//
ULONG p = 0;
// p0, p1, p2, p3 hold accumulated column parity bits (32*4=128 bits)
//
ULONG p0 = 0, p1 = 0, p2 = 0, p3 = 0;
{
// combine 16-bit index and ~index together into a 32-bit double index
//
ULONG idxp = 0xff800000;
// loop control variable
//
ULONG i = 0;
// treat first and second 32-bit of the data always as 0
ULONG pT0 = 0;
ULONG pT1 = 0;
// skip first 8 byte when checksum region is at the beginning of a page
if ( fHeaderBlock )
{
goto Start;
}
// unroll the loop to 32-byte cache line boundary
// one iteration will process 2 rows of data in one cache line.
//
do
{
// read one row (first half of the cache line) from data (32*4=128 bits)
//
pT0 = pdw[ i + 0 ];
pT1 = pdw[ i + 1 ];
Start:
const ULONG pT2 = pdw[ i + 2 ];
const ULONG pT3 = pdw[ i + 3 ];
// update accumulated column parity bits
//
p0 ^= pT0;
p1 ^= pT1;
p2 ^= pT2;
p3 ^= pT3;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT0 ^ pT1 ^ pT2 ^ pT3 );
// update double index
//
idxp += 0xff800080;
// read another row (second half of the cache line) from data (32*4=128 bits)
//
const ULONG pT4 = pdw[ i + 4 ];
const ULONG pT5 = pdw[ i + 5 ];
const ULONG pT6 = pdw[ i + 6 ];
const ULONG pT7 = pdw[ i + 7 ];
// update accumulated column parity bits
//
p0 ^= pT4;
p1 ^= pT5;
p2 ^= pT6;
p3 ^= pT7;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT4 ^ pT5 ^ pT6 ^ pT7 );
// update double index
//
idxp += 0xff800080;
// update loop control variable
//
i += 8;
// inform compiler the loop won't quit in 1st iteration.
//
__assume( 8 < cdw );
} while ( i < cdw );
}
//================================================
// reduce 128 column parity bits (p0, p1, p2, p3) into 32 bits
//
// compute ECC bits shown as '1'
// 0000 0000 0110 0000 0000 0000 0110 0000
//
p |= 0x00400000 & lParityMask( p0 ^ p1 );
p |= 0x00000040 & lParityMask( p2 ^ p3 );
const ULONG r0 = p0 ^ p2;
const ULONG r1 = p1 ^ p3;
p |= 0x00200000 & lParityMask( r0 );
p |= 0x00000020 & lParityMask( r1 );
// r2 holds 32-bit reduced column parity bits
//
const ULONG r2 = r0 ^ r1;
//================================================
// compute ECC bits shown as '1'
// 0000 0000 0001 1111 0000 0000 0001 1111
//
ULONG r = 0;
// double index
//
ULONG idxr = 0xffff0000;
// loop through every column parity bit
//
for ( ULONG i = 1; i; i += i )
{
const LONG mask = -!!( r2 & i );
r ^= mask & idxr;
idxr += 0xffff0001;
}
//================================================
// mask some high bits out according to the data size
//
const ULONG mask = ( cb << 19 ) - 1;
// assemble final checksum
//
const ULONG ecc = p & 0xffe0ffe0 & mask | r & 0x001f001f;
const ULONG xor = r2;
return MakeChecksumFromECCXORAndPgno( ecc, xor, pgno );
}
// ================================================================
static XECHECKSUM ChecksumNewFormatSSE( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// optmized ECC function for 32-bit CPU, 32-byte cache line, prefetching
// the data is organized into an array of bits that is 32*4=128 bits wide
// each line of CPU cache will hold 2 rows of data
//
//-
{
// ensure correct signature of the function
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormatSSE;
Unused( pfn );
// data size sanity check
//
Assert( 4 == sizeof( ULONG ) );
// cb should be an order of 2 and between 1k and 8k
//
Assert( 0 == ( cb & ( cb -1 ) ) );
Assert( 1024 <= cb && cb <= 8192 );
// pb should align to 32 (2 rows of CPU cache)
//
Assert( 0 == ( ( uintptr_t )pb & ( 32 - 1 ) ) );
//================================================
// long* is easier to use than char*
//
const ULONG* pdw = ( ULONG* )pb;
const ULONG cdw = cb / sizeof( *pdw );
//================================================
// compute ECC bits shown as '1'
// 1111 1111 1000 0000 1111 1111 1000 0000
//
ULONG p = 0;
// p0, p1, p2, p3 hold accumulated column parity bits (32*4=128 bits)
//
unsigned p0 = 0, p1 = 0, p2 = 0, p3 = 0;
{
// combine 16-bit index and ~index together into a 32-bit double index
//
ULONG idxp = 0xff800000;
// loop control variable
//
ULONG i = 0;
// treat the first and second 32-bit of the data always as 0
//
ULONG pT0 = 0;
ULONG pT1 = 0;
// skip first 8 byte when checksum region is at the beginning of a page
if ( fHeaderBlock )
{
goto Start;
}
// unroll the loop to 32-byte cache line boundary
// one iteration will process 2 rows of data in one cache line.
//
do
{
// read one row (first half of the cache line) from data (32*4=128 bits)
//
pT0 = pdw[ i + 0 ];
pT1 = pdw[ i + 1 ];
Start:
#if (defined _AMD64_ || defined _X86_ )
#if 1
_mm_prefetch( ( char *)&( pdw[ i + 32 ] ), _MM_HINT_NTA );
#else
CachePrefetch( ( char *)&( pdw[ i + 32 ] ) );
#endif
#endif
const ULONG pT2 = pdw[ i + 2 ];
const ULONG pT3 = pdw[ i + 3 ];
// update accumulated column parity bits
//
p0 ^= pT0;
p1 ^= pT1;
p2 ^= pT2;
p3 ^= pT3;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT0 ^ pT1 ^ pT2 ^ pT3 );
// update double index
//
idxp += 0xff800080;
// read another row (second half of the cache line) from data (32*4=128 bits)
//
const ULONG pT4 = pdw[ i + 4 ];
const ULONG pT5 = pdw[ i + 5 ];
const ULONG pT6 = pdw[ i + 6 ];
const ULONG pT7 = pdw[ i + 7 ];
// update accumulated column parity bits
//
p0 ^= pT4;
p1 ^= pT5;
p2 ^= pT6;
p3 ^= pT7;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( pT4 ^ pT5 ^ pT6 ^ pT7 );
// update double index
//
idxp += 0xff800080;
// update loop control variable
//
i += 8;
// inform compiler the loop won't quit in 1st iteration.
//
__assume( 8 < cdw );
}
while ( i < cdw );
}
//================================================
// reduce 128 column parity bits (p0, p1, p2, p3) into 32 bits
//
// compute ECC bits shown as '1'
// 0000 0000 0110 0000 0000 0000 0110 0000
//
p |= 0x00400000 & lParityMask( p0 ^ p1 );
p |= 0x00000040 & lParityMask( p2 ^ p3 );
const ULONG r0 = p0 ^ p2;
const ULONG r1 = p1 ^ p3;
p |= 0x00200000 & lParityMask( r0 );
p |= 0x00000020 & lParityMask( r1 );
// r2 holds 32-bit reduced column parity bits
//
const ULONG r2 = r0 ^ r1;
//================================================
// compute ECC bits shown as '1'
// 0000 0000 0001 1111 0000 0000 0001 1111
//
ULONG r = 0;
// double index
//
ULONG idxr = 0xffff0000;
// loop through every column parity bit
//
for ( ULONG i = 1; i; i += i )
{
const LONG mask = -!!( r2 & i );
r ^= mask & idxr;
idxr += 0xffff0001;
}
//================================================
// mask some high bits out according to the data size
//
const ULONG mask = ( cb << 19 ) - 1;
// assemble final checksum
//
const ULONG ecc = p & 0xffe0ffe0 & mask | r & 0x001f001f;
const ULONG xor = r2;
return MakeChecksumFromECCXORAndPgno( ecc, xor, pgno );
}
#if 1
#if (defined _AMD64_ || defined _X86_ )
// ================================================================
inline __m128i operator^( const __m128i dq0, const __m128i dq1 )
// ================================================================
{
return _mm_xor_si128( dq0, dq1 );
}
// ================================================================
inline __m128i operator^=( __m128i& dq0, const __m128i dq1 )
// ================================================================
{
return dq0 = _mm_xor_si128( dq0, dq1 );
}
// ================================================================
inline LONG lParityMask( const __m128i dq )
// ================================================================
//
// Compute a 32-bit parity mask of a 128-bit integer
//
{
const __m128i dq1 = _mm_shuffle_epi32( dq, 0x4e );
const __m128i dq2 = dq ^ dq1;
const __m128i dq3 = _mm_shuffle_epi32( dq2, 0x1b );
const __m128i dq4 = dq2 ^ dq3;
return lParityMask( _mm_cvtsi128_si32( dq4 ) );
}
// ================================================================
static XECHECKSUM ChecksumNewFormatSSE2( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// optmized ECC function for P4 (SSE2 + 128B L2 + Prefetching)
// the data is organized into an array of bits that is 128*4=512 bits wide
// each line of CPU cache will hold 2 rows of data
//
//-
{
// ensure correct signature of the function
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormatSSE2;
Unused( pfn );
// data size sanity check
//
Assert( 16 == sizeof( __m128i ) );
Assert( 4 == sizeof( ULONG ) );
// cb should be an order of 2 and between 1k and 8k
//
Assert( 0 == ( cb & ( cb -1 ) ) );
Assert( 1024 <= cb && cb <= 8192 );
// pb should align to 128 (2 rows of CPU cache)
//
Assert( 0 == ( ( uintptr_t )pb & ( 128 - 1 ) ) );
// get double quadword count of the data block
//
const ULONG cdq = cb / 16;
//================================================
// compute ECC bits shown as '1'
// 1111 1110 0000 0000 1111 1110 0000 0000
//
ULONG p = 0;
// dq0, dq1, dq2, dq3 hold accumulated column parity bits (128*4=512 bits)
//
__m128i dq0 = _mm_setzero_si128();
__m128i dq1 = _mm_setzero_si128();
__m128i dq2 = _mm_setzero_si128();
__m128i dq3 = _mm_setzero_si128();
{
// combine 16-bit index and ~index together into a 32-bit double index
//
ULONG idxp = 0xfe000000;
// loop control variable
//
ULONG i = 0;
__m128i dqL0;
// treat the first and second 32-bit of the data always as 0
//
const __m128i* pdq = ( const __m128i* )pb;
if ( fHeaderBlock )
{
dqL0 = _mm_unpackhi_epi64( _mm_setzero_si128(), pdq[ 0 ] );
goto Start;
}
// unroll the loop to 128-byte cache line boundary
// one iteration will process 2 rows of data in one cache line.
//
do
{
// read one row (first half of the cache line) from data (128*4=512 bits)
//
dqL0 = pdq[ i + 0 ];
Start:
_mm_prefetch( ( char *)&pdq[ i + 32 ], _MM_HINT_NTA );
const __m128i dqL1 = pdq[ i + 1 ];
const __m128i dqL2 = pdq[ i + 2 ];
const __m128i dqL3 = pdq[ i + 3 ];
// update accumulated column parity bits
//
dq0 ^= dqL0;
dq1 ^= dqL1;
dq2 ^= dqL2;
dq3 ^= dqL3;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( dqL0 ^ dqL1 ^ dqL2 ^dqL3 );
// update double index
//
idxp += 0xfe000200;
// read another row (second half of the cache line) from data (128*4=512 bits)
//
const __m128i dqH0 = pdq[ i + 4 ];
const __m128i dqH1 = pdq[ i + 5 ];
const __m128i dqH2 = pdq[ i + 6 ];
const __m128i dqH3 = pdq[ i + 7 ];
// update accumulated column parity bits
//
dq0 ^= dqH0;
dq1 ^= dqH1;
dq2 ^= dqH2;
dq3 ^= dqH3;
// compute row parity and distribute it according to its index
//
p ^= idxp & lParityMask( dqH0 ^ dqH1 ^ dqH2 ^dqH3 );
// update double index
//
idxp += 0xfe000200;
// update loop control variable
//
i += 8;
// inform compiler the loop won't quit in 1st iteration.
//
__assume( 8 < cdq );
}
while ( i < cdq );
}
//================================================
// reduce 512 column parity bits (dq0, dq1, dq2, dq3) into 32 bits
//
__declspec( align( 128 ) ) __m128i arydq[ 4 ];
ULONG* pdw = ( ULONG* )arydq;
arydq[ 0 ] = dq0;
arydq[ 1 ] = dq1;
arydq[ 2 ] = dq2;
arydq[ 3 ] = dq3;
// compute ECC bits shown as '1'
// 0000 0001 1110 0000 0000 0001 1110 0000
//
ULONG q = 0;
// dw0 holds 32-bit reduced column parity bits
//
ULONG dw0 = 0;
// double index
//
ULONG idxq = 0xffe00000;
for ( ULONG i = 0; i < 16; ++i )
{
ULONG dwT = pdw[ i ];
dw0 ^= dwT;
q ^= idxq & lParityMask( dwT );
idxq += 0xffe00020;
}
//================================================
// compute ECC bits shown as '1'
// 0000 0000 0001 1111 0000 0000 0001 1111
//
ULONG r = 0;
// double index
//
ULONG idxr = 0xffff0000;
// loop through every column parity bit
//
for ( ULONG i = 1; i; i += i )
{
const LONG bit = ( dw0 & i ) ? -1 : 0;
r ^= bit & idxr;
idxr += 0xffff0001;
}
//================================================
// mask some high bits out according to the data size
//
const ULONG mask = ( cb << 19 ) - 1;
// assemble final checksum
//
const ULONG ecc = p & 0xfe00fe00 & mask | q & 0x01e001e0 | r & 0x001f001f;
const ULONG xor = dw0;
return MakeChecksumFromECCXORAndPgno( ecc, xor, pgno );
}
#else
// ================================================================
XECHECKSUM ChecksumNewFormatSSE2( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
//
// stub used for IA64 builds (function ptr never called)
//
//-
{
Assert( fFalse );
return MakeChecksumFromECCXORAndPgno( 0, 0, pgno );
}
#endif
#endif // 1
// ================================================================
static XECHECKSUM ChecksumNewFormat64Bit( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
// ================================================================
{
// ensure correct signature of the function
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormat64Bit;
Unused( pfn );
// the data will be organized into an array of bits that is 32 bits wide
//
const ULONG* rgdwRow = ( ULONG* )pb;
const ULONG cColumn = 32;
const ULONG cRow = cb / ( cColumn / 8 );
// this will hold the column parity bits which we will accumulate while
// computing the row values of the ECC
//
ULONG dwColumnParity = 0;
// the first and second row (8-byte in total) will be the ECC and XOR checksum,
// we cannot include them in the computation, so, we treat them as always 0
//
ULONG p = 0, q = 0;
ULONG iRow = 0;
// compute the remainder of the row values of the ECC from the block
//
for ( iRow = fHeaderBlock ? 2 : 0; iRow < cRow; ++iRow )
{
// read this row from the block
//
const ULONG dwRow = rgdwRow[ iRow ];
// accumulate the column parity for this row
//
dwColumnParity ^= dwRow;
// expand the row parity value into a mask
//
const LONG maskRow = lParityMask( dwRow );
// incorporate this row's parity into the row values of the ECC
//
p ^= maskRow & iRow;
q ^= maskRow & ~iRow;
}
// compute the column values of the ECC from the accumulated column parity bits
//
ULONG r = 0, s = 0;
ULONG iColumn = 0;
for ( iColumn = 0; iColumn < cColumn; ++iColumn )
{
// expand the desired bit from the column parity values into a mask
//
const LONG maskColumn = -( !!( dwColumnParity & ( 1 << iColumn ) ) );
// incorporate this column's parity into the column values of the ECC
//
r ^= maskColumn & iColumn;
s ^= maskColumn & ~iColumn;
}
// the ECC will be encoded as a 32 bit word that will look like this:
//
// 3 22 11 00 0
// 1 10 65 54 0
// qqqqqqqqqqqsssssppppppppppprrrrr
//
// the upper bits of p and q may not be used depending on the size of the
// block. and 8kb block will use all the bits. each block size below
// that will use one fewer bit in both p and q. any unused bits in the
// ECC will always be zero
//
// the ECC is used to detect errors using the XOR of the expected value of
// the ECC and the actual value of the ECC as follows:
//
// all bits are clear: no error
// one bit is set: one bit flip in the ECC was detected
// all used bits are set: one bit flip in the block was detected
// random bits are set: more than one bit flip was detected
//
// if a bit flip in the ECC was detected then the ECC should simply be
// corrected to the expected value of the ECC
//
// if a bit flip in the block was detected then the offset of that bit in
// the block is equal to the least significant 16 bits of the XORed ECC
// values
//
const ULONG ulEcc = ( ( q & ( cRow - 1 ) ) << 21 ) |
( ( s & ( cColumn - 1 ) ) << 16 ) |
( ( p & ( cRow - 1 ) ) << 5 ) |
( ( r & ( cColumn - 1 ) ) << 0 ) |
0;
const ULONG ulXor = dwColumnParity;
return MakeChecksumFromECCXORAndPgno( ulEcc, ulXor, pgno );
}
#if 1
#else
//================================================================
static __declspec( naked ) PAGECHECKSUM __stdcall ChecksumSSE2_Emitted( const unsigned char* pb, const ULONG cb )
//================================================================
//
// we need to be 100% correct about the number of PUSHes inside the assembly routine
// since we access local variable/buffers based on ESP
//
// update STKOFF if local variable/buffers is changed
//
//
//================================================
// latency and throughput for some instructions on P4
//================================================
// movd xmm, r32 6 2 MMX_MISC, MMX_SHFT
// movd r32, xmm 10 1 FP_MOVE, FP_MISC
// movdqa xmm, xmm 6 1 FP_MOVE
// pshufd xmm, xmm, imm8 4 2 MMX_SHFT
// psrldq xmm, imm8 4 2 MMX_SHFT
// pxor 2 2 MMX_ALU
// SAL/SAR/SHL/SHR 4 1
// SETcc 4 1.5 ALU
// CALL 5 1 ALU, MEM_STORE
//
//================================================
//
//-
{
#define STKOFF ( 4 * 6 )
#pragma push_macro( "emit2" )
#pragma push_macro( "emit3" )
#pragma push_macro( "emit4" )
#pragma push_macro( "emit5" )
#define emit2(b1,b2) __asm _emit b1 __asm _emit b2
#define emit3(b1,b2,b3) emit2(b1,b2) __asm _emit b3
#define emit4(b1, b2, b3, b4) emit3(b1,b2,b3) __asm _emit b4
#define emit5(b1, b2, b3, b4, b5) emit4(b1,b2,b3,b4) __asm _emit b5
#define emit6(b1, b2, b3, b4, b5, b6) emit5(b1,b2,b3,b4, b5) __asm _emit b6
#define emit7(b1, b2, b3, b4, b5, b6, b7 ) emit6(b1,b2,b3,b4, b5, b6) __asm _emit b7
__asm mov eax, [ esp + 4 ] // pb
__asm mov ecx, [ esp + 8 ] // cb
__asm mov edx, esp // save esp in edx
__asm and esp, 0xfffffff0 // align esp to 16-byte boundary
__asm sub esp, 16 * 4 // 64-byte local buffer
// treat first 8-Byte always as 0
emit4( 0x66, 0x0f, 0xef, 0xc0 ); // pxor xmm0,xmm0
emit4( 0x66, 0x0f, 0x6d, 0x00 ); // punpckhqdq xmm0,oword ptr [eax]
__asm push edx // edx(esp)
__asm push ebx //
__asm push ebp // save callee saved regs
__asm push esi //
__asm push edi //
//================================================
// cb-byte to 64-byte
//
__asm push ecx
__asm shr ecx, 7 // count
__asm xor ebx, ebx // ecc
__asm mov edx, 0xfe000000 // double index
__asm mov ebp, 0xfe000200 // double index delta
emit4( 0x66, 0x0f, 0xef, 0xe4 ); // pxor xmm4,xmm4
emit4( 0x66, 0x0f, 0xef, 0xed ); // pxor xmm5,xmm5
emit4( 0x66, 0x0f, 0xef, 0xf6 ); // pxor xmm6,xmm6
emit4( 0x66, 0x0f, 0xef, 0xff ); // pxor xmm7,xmm7
__asm jmp loop_page_to_64B_start
loop_page_to_64B:
emit4( 0x66, 0x0f, 0x6f, 0x00 ); // movdqa xmm0,oword ptr [eax]
loop_page_to_64B_start:
emit5( 0x66, 0x0f, 0x6f, 0x48, 0x10 ); // movdqa xmm1,oword ptr [eax+0x10]
emit5( 0x66, 0x0f, 0x6f, 0x50, 0x20 ); // movdqa xmm2,oword ptr [eax+0x20]
emit5( 0x66, 0x0f, 0x6f, 0x58, 0x30 ); // movdqa xmm3,oword ptr [eax+0x30]
emit7( 0x0f, 0x18, 0x80, 0x00, 0x02, 0x00, 0x00 ); // prefetchnta byte ptr [eax+0x200]
emit4( 0x66, 0x0f, 0xef, 0xe0 ); // pxor xmm4,xmm0
emit4( 0x66, 0x0f, 0xef, 0xe9 ); // pxor xmm5,xmm1
emit4( 0x66, 0x0f, 0xef, 0xf2 ); // pxor xmm6,xmm2
emit4( 0x66, 0x0f, 0xef, 0xfb ); // pxor xmm7,xmm3
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit4( 0x66, 0x0f, 0xef, 0xd3 ); // pxor xmm2,xmm3
emit4( 0x66, 0x0f, 0xef, 0xc2 ); // pxor xmm0,xmm2
emit5( 0x66, 0x0f, 0x70, 0xc8, 0x4e ); // pshufd xmm1,xmm0,0x4e
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit5( 0x66, 0x0f, 0x70, 0xc8, 0x1b ); // pshufd xmm1,xmm0,0x1b
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit4( 0x66, 0x0f, 0x7e, 0xc6 ); // movd esi, xmm0
__asm mov edi, esi
__asm shr edi, 16
__asm xor esi, edi
__asm mov edi, esi
__asm shr edi, 8
__asm xor esi, edi
__asm and esi, 0xff
__asm movsx esi, [ g_bParityLookupTable + esi ]
__asm and esi, edx
__asm add edx, ebp
__asm xor ebx, esi
emit5( 0x66, 0x0f, 0x6f, 0x40, 0x40 ); // movdqa xmm0,oword ptr [eax+0x40]
emit5( 0x66, 0x0f, 0x6f, 0x48, 0x50 ); // movdqa xmm1,oword ptr [eax+0x50]
emit5( 0x66, 0x0f, 0x6f, 0x50, 0x60 ); // movdqa xmm2,oword ptr [eax+0x60]
emit5( 0x66, 0x0f, 0x6f, 0x58, 0x70 ); // movdqa xmm3,oword ptr [eax+0x70]
emit4( 0x66, 0x0f, 0xef, 0xe0 ); // pxor xmm4,xmm0
emit4( 0x66, 0x0f, 0xef, 0xe9 ); // pxor xmm5,xmm1
emit4( 0x66, 0x0f, 0xef, 0xf2 ); // pxor xmm6,xmm2
emit4( 0x66, 0x0f, 0xef, 0xfb ); // pxor xmm7,xmm3
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit4( 0x66, 0x0f, 0xef, 0xd3 ); // pxor xmm2,xmm3
emit4( 0x66, 0x0f, 0xef, 0xc2 ); // pxor xmm0,xmm2
emit5( 0x66, 0x0f, 0x70, 0xc8, 0x4e ); // pshufd xmm1,xmm0,0x4e
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit5( 0x66, 0x0f, 0x70, 0xc8, 0x1b ); // pshufd xmm1,xmm0,0x1b
emit4( 0x66, 0x0f, 0xef, 0xc1 ); // pxor xmm0,xmm1
emit4( 0x66, 0x0f, 0x7e, 0xc6 ); // movd esi, xmm0
__asm mov edi, esi
__asm shr edi, 16
__asm xor esi, edi
__asm mov edi, esi
__asm shr edi, 8
__asm xor esi, edi
__asm and esi, 0xff
__asm movsx esi, [ g_bParityLookupTable + esi ]
__asm and esi, edx
__asm add edx, ebp
__asm xor ebx, esi
__asm sub eax, -128
__asm dec ecx
__asm jnz loop_page_to_64B
//================================================
// 64-byte to 4-byte
//
emit6( 0x66, 0x0f, 0x7f, 0x64, 0x24, STKOFF + 0x00 ); // movdqa oword ptr [esp+0x18],xmm4
emit6( 0x66, 0x0f, 0x7f, 0x6c, 0x24, STKOFF + 0x10 ); // movdqa oword ptr [esp+0x28],xmm5
emit6( 0x66, 0x0f, 0x7f, 0x74, 0x24, STKOFF + 0x20 ); // movdqa oword ptr [esp+0x38],xmm6
emit6( 0x66, 0x0f, 0x7f, 0x7c, 0x24, STKOFF + 0x30 ); // movdqa oword ptr [esp+0x48],xmm7
__asm pop ecx
__asm and ebx, 0xfe00fe00
__asm shl ecx, 19
__asm dec ecx
__asm and ebx, ecx
__asm push ebx // save 1st part ECC
__asm lea eax, [ esp + STKOFF ] // address
__asm mov ecx, 16 // count
__asm xor edx, edx // dw
__asm xor ebx, ebx // ecc
__asm mov ebp, 0xffe00000 // double index
loop_64B_to_4B:
__asm mov esi, [ eax ]
__asm xor edx, esi
__asm mov edi, esi
__asm shr edi, 16
__asm xor esi, edi
__asm mov edi, esi
__asm shr edi, 8
__asm xor esi, edi
__asm and esi, 0xff
__asm movsx esi, [ g_bParityLookupTable + esi ]
__asm and esi, ebp
__asm add ebp, 0xffe00020
__asm xor ebx, esi
__asm add eax, 4
__asm dec ecx
__asm jnz loop_64B_to_4B
__asm and ebx, 0x01e001e0
__asm push ebx // save 2nd part ECC
//================================================
// last 32-bit
// edx = xor checksum
//
__asm xor ecx, ecx // ecc
__asm mov ebx, 0xffff0000 // double index
__asm mov eax, 1 // bit mask
loop_4B_to_End:
__asm mov esi, eax
__asm and esi, edx
__asm neg esi
__asm sbb esi, esi
__asm and esi, ebx
__asm add ebx, 0xffff0001
__asm xor ecx, esi
__asm add eax, eax
__asm jnz loop_4B_to_End
//================================================
// Compose final result
// eax = ecc checksum
//
__asm pop eax
__asm pop ebx
__asm and ecx, 0x001f001f
__asm or eax, ecx
__asm or eax, ebx
__asm pop edi //
__asm pop esi //
__asm pop ebp // restore callee saved regs
__asm pop ebx //
__asm pop esp //
__asm ret 8
}
// ================================================================
static PAGECHECKSUM ChecksumNewFormatSSE2_Wrapper( const unsigned char * const pb, const ULONG cb, const ULONG pgno )
// ================================================================
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormatSSE2_Wrapper;
Unused( pfn );
PAGECHECKSUM checksum = ChecksumSSE2_Emitted( pb, cb );
// The emitted code returns a 64-bit number with the ECC as the low DWORD and XOR as the high DWORD
const ULONG checksumXOR = (ULONG)(checksum >> 32);
const ULONG checksumECC = (ULONG)(checksum & 0xffffffff);
return MakeChecksumFromECCXORAndPgno( checksumECC, checksumXOR, pgno );
}
#endif // 1
// ================================================================
inline BOOL FGetBit( const void * const pv, const INT ibitOffset )
// ================================================================
{
const unsigned char * const pb = (unsigned char *)pv;
const INT ibyte = ibitOffset / 8;
const INT ibitInByte = ibitOffset % 8;
const unsigned char bitMask = (unsigned char)( 1 << ibitInByte );
return ( pb[ibyte] & bitMask ) ? fTrue : fFalse;
}
// ================================================================
static UINT IbitNewChecksumFormatFlag( const PAGETYPE pagetype )
// ================================================================
{
if( databasePage == pagetype )
{
// for database pages, the page flags are stored in the 10th
// unsigned long. The format bit is 0x1000, which is the 13th bit.
return ( 9 * 32 ) + 13;
}
return ( UINT )-1;
}
// ================================================================
static BOOL FPageHasNewChecksumFormat( const void * const pv, const PAGETYPE pagetype )
// ================================================================
//
// Returns fTrue if the ECC format bit for the page is set. Database pages
// and header pages have different formats, so we have to store the bit
// in different places
//
//-
{
if( databasePage == pagetype )
{
const INT ibit = IbitNewChecksumFormatFlag( pagetype );
return FGetBit( pv, ibit );
}
return 0;
}
// ================================================================
static BOOL FPageHasLongChecksum( const PAGETYPE pagetype )
// ================================================================
{
return ( databasePage == pagetype );
}
// ================================================================
static ULONG ShortChecksumFromPage( const void * const pv )
// ================================================================
{
return *( const ULONG* )pv;
}
// ================================================================
static PAGECHECKSUM LongChecksumFromPage( const void * const pv )
// ================================================================
{
const PGHDR2* const pPH = ( const PGHDR2* )pv;
if ( FIsSmallPage() )
{
return PAGECHECKSUM( pPH->checksum );
}
else
{
return PAGECHECKSUM( pPH->checksum, pPH->rgChecksum[ 0 ], pPH->rgChecksum[ 1 ], pPH->rgChecksum[ 2 ] );
}
}
// ================================================================
static PAGECHECKSUM ChecksumFromPage( const void * const pv, const PAGETYPE pagetype )
// ================================================================
{
if( FPageHasLongChecksum( pagetype ) )
{
return LongChecksumFromPage( pv );
}
return ShortChecksumFromPage( pv );
}
// ================================================================
static PAGECHECKSUM ComputePageChecksum(
const void* const pv,
const UINT cb,
const PAGETYPE pagetype,
const ULONG pgno,
const BOOL fNew )
// ================================================================
{
if( FPageHasLongChecksum( pagetype ) )
{
if( FPageHasNewChecksumFormat( pv, pagetype ) )
{
// large pages (16/32kiB) always have new checksum format
PAGECHECKSUM pgChecksum;
const unsigned char* const pch = ( unsigned char* )pv;
// divide a large page into 4 blocks, first block is header block which hosts the page header
unsigned cbT = cb;
if ( !FIsSmallPage( cb ) )
{
cbT = cb / cxeChecksumPerPage;
pgChecksum.rgChecksum[ 1 ] = pfnChecksumNewFormat( pch + cbT * 1, cbT, pgno, fFalse );
pgChecksum.rgChecksum[ 2 ] = pfnChecksumNewFormat( pch + cbT * 2, cbT, pgno, fFalse );
pgChecksum.rgChecksum[ 3 ] = pfnChecksumNewFormat( pch + cbT * 3, cbT, pgno, fFalse );
// write checksums into designated location in header block
// so checksum for header block can protect them as well
if ( fNew )
{
// cast RO ( const void* ) to RW ( PGHDR2* )
PGHDR2* const pPgHdr2 = ( PGHDR2* )pv;
pPgHdr2->rgChecksum[ 0 ] = pgChecksum.rgChecksum[ 1 ];
pPgHdr2->rgChecksum[ 1 ] = pgChecksum.rgChecksum[ 2 ];
pPgHdr2->rgChecksum[ 2 ] = pgChecksum.rgChecksum[ 3 ];
}
}
// whole small page or header block for large page
pgChecksum.rgChecksum[ 0 ] = pfnChecksumNewFormat( pch, cbT, pgno, fTrue );
return pgChecksum;
}
else
{
return LongChecksumFromShortChecksum( (*pfnChecksumOldFormat)((unsigned char *)pv, cb), pgno );
}
}
return (*pfnChecksumOldFormat)((unsigned char *)pv, cb);
}
// ================================================================
static ULONG DwECCChecksumFromPagechecksum( const XECHECKSUM checksum )
// ================================================================
{
return (ULONG)( checksum >> 32 );
}
// ================================================================
static ULONG DwXORChecksumFromPagechecksum( const XECHECKSUM checksum )
// ================================================================
{
return (ULONG)( checksum & 0xffffffff );
}
// ================================================================
static INT CbitSet( const ULONG dw )
// ================================================================
{
INT cbit = 0;
for( INT ibit = 0; ibit < 32; ++ibit )
{
if( dw & ( 1 << ibit ) )
{
++cbit;
}
}
return cbit;
}
// ================================================================
static BOOL FECCErrorIsCorrectable( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
// ================================================================
{
const ULONG dwEcc = DwECCChecksumFromPagechecksum( xeChecksumActual ) ^ DwECCChecksumFromPagechecksum( xeChecksumExpected );
const ULONG dwXor = DwXORChecksumFromPagechecksum( xeChecksumActual ) ^ DwXORChecksumFromPagechecksum( xeChecksumExpected );
Assert( xeChecksumActual != xeChecksumExpected ); // nothing to correct?!
const ULONG ulMask = ( ( cb << 3 ) - 1 );
const ULONG ulX = ( ( dwEcc >> 16 ) ^ dwEcc ) & ulMask;
// ulX has all bits set, correctable error
if ( ulMask == ulX )
{
// we can only have a single-bit error if the XOR checksum shows only one bit incorrect
// (of course multiple bits could be corrupted, but this check provides an extra level of
// safety)
if( 1 == CbitSet( dwXor ) )
{
return fTrue;
}
}
return fFalse;
}
// ================================================================
static UINT IbitCorrupted( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
// ================================================================
{
Assert( xeChecksumExpected != xeChecksumActual ); // nothing to correct?!
Assert( FECCErrorIsCorrectable( cb, xeChecksumExpected, xeChecksumActual ) ); // not correctable?!
const ULONG dwEcc = DwECCChecksumFromPagechecksum( xeChecksumActual ) ^ DwECCChecksumFromPagechecksum( xeChecksumExpected );
Assert( 0 != dwEcc );
return ( UINT )( dwEcc & 0xffff );
}
// ================================================================
inline void FlipBit( void * const pv, const INT ibitOffset )
// ================================================================
{
unsigned char * const pb = (unsigned char *)pv;
const INT ibyte = ibitOffset / 8;
const INT ibitInByte = ibitOffset % 8;
const unsigned char bitMask = (unsigned char)( 1 << ibitInByte );
pb[ibyte] ^= bitMask;
}
// ================================================================
enum XECHECKSUMERROR { xeChecksumNoError = 0, xeChecksumCorrectableError = -13, xeChecksumFatalError = -29, };
static XECHECKSUMERROR FTryFixBlock(
const UINT cb,
UINT* const pibitCorrupted, // [in] bit offset of XECHECKSUM flag, [out] bit offset of proposed correction
const XECHECKSUM xeChecksumExpected,
const XECHECKSUM xeChecksumActual )
// ================================================================
{
if ( xeChecksumExpected == xeChecksumActual )
{
return xeChecksumNoError;
}
if ( FECCErrorIsCorrectable( cb, xeChecksumExpected, xeChecksumActual ) )
{
const UINT ibitCorrupted = IbitCorrupted( cb, xeChecksumExpected, xeChecksumActual );
// *pibitCorrupted is the offset of the BIT we can NOT flip
if ( ( *pibitCorrupted != ibitCorrupted ) && ( ibitCorrupted < 8 * cb ) )
{
*pibitCorrupted = ibitCorrupted;
return xeChecksumCorrectableError;
}
}
return xeChecksumFatalError;
}
// ================================================================
static void TryFixPage(
void * const pv,
const UINT cb,
const PAGETYPE pagetype,
const BOOL fCorrectError,
BOOL * const pfCorrectableError,
INT * const pibitCorrupted,
const PAGECHECKSUM checksumExpected,
const PAGECHECKSUM checksumActual )
// ================================================================
{
Assert( checksumActual != checksumExpected );
const BOOL fSmallPage = FIsSmallPage( cb );
const UINT cbT = fSmallPage ? cb : cb / cxeChecksumPerPage;
const UINT cblk = fSmallPage ? 1 : cxeChecksumPerPage;
XECHECKSUMERROR rgErr[ cxeChecksumPerPage ] = { xeChecksumNoError, };
UINT rgibitCorrupted[ cxeChecksumPerPage ] = { IbitNewChecksumFormatFlag( pagetype ), UINT_MAX, UINT_MAX, UINT_MAX, };
UINT ibitCorrupted = UINT_MAX;
// work out correction
for ( UINT iblk = 0; iblk < cblk; ++iblk )
{
rgErr[ iblk ] = FTryFixBlock( cbT, &rgibitCorrupted[ iblk ], checksumExpected.rgChecksum[ iblk ], checksumActual.rgChecksum[ iblk ] );
switch ( rgErr[ iblk ] )
{
case xeChecksumNoError:
break;
case xeChecksumCorrectableError:
// save the location of first correctable error
if ( UINT_MAX == ibitCorrupted )
{
ibitCorrupted = CHAR_BIT * cbT * iblk + rgibitCorrupted[ iblk ];
// does this correctable error actually hit other checksums
UINT ibitStart = CHAR_BIT * offsetof( PGHDR2, rgChecksum );
UINT ibitLength = CHAR_BIT * sizeof( checksumExpected.rgChecksum[ 0 ] );
if ( !fSmallPage && // large page
0 == iblk && // header block
ibitStart <= ibitCorrupted && // hit one of the other checksums
ibitCorrupted < ibitStart + ibitLength * ( cxeChecksumPerPage - 1 ) )
{
// fix the other hit checksum
UINT ibit = ibitLength + ( ibitCorrupted - ibitStart );
FlipBit( ( void* )&checksumExpected, ibit );
}
}
break;
case xeChecksumFatalError:
*pfCorrectableError = fFalse;
return;
}
}
// when multiple correctables, just report first one
*pfCorrectableError = fTrue;
*pibitCorrupted = ibitCorrupted;
Assert( (UINT)*pibitCorrupted < ( 8 * cb ) );
// carry out correction in page
for ( UINT iblk = 0; fCorrectError && iblk < cblk; ++iblk )
{
unsigned char* pch = ( unsigned char* )pv;
if ( xeChecksumCorrectableError == rgErr[ iblk ] )
{
FlipBit( &pch[ cbT * iblk ], rgibitCorrupted[ iblk ]);
}
}
return;
}
// ================================================================
void ChecksumAndPossiblyFixPage(
void * const pv, // pointer to the page
const UINT cb, // size of the page (normally g_cbPage)
const PAGETYPE pagetype, // type of the page
const ULONG pgno,
const BOOL fCorrectError, // fTrue if ECC should be used to correct errors
PAGECHECKSUM * const pchecksumExpected, // set to the checksum the page should have
PAGECHECKSUM * const pchecksumActual, // set the the actual checksum. if actual != expected, JET_errReadVerifyFailure is returned
BOOL * const pfCorrectableError, // set to fTrue if ECC could correct the error (set even if fCorrectError is fFalse)
INT * const pibitCorrupted ) // offset of the corrupted bit (meaningful only if *pfCorrectableError is fTrue)
// ================================================================
{
*pfCorrectableError = fFalse;
*pibitCorrupted = -1;
*pchecksumExpected = ChecksumFromPage( pv, pagetype );
*pchecksumActual = ComputePageChecksum( pv, cb, pagetype, pgno );
const BOOL fNewChecksumFormat = FPageHasNewChecksumFormat( pv, pagetype );
if( *pchecksumActual != *pchecksumExpected && fNewChecksumFormat )
{
TryFixPage( pv, cb, pagetype, fCorrectError, pfCorrectableError, pibitCorrupted, *pchecksumExpected, *pchecksumActual );
Assert( ( *pfCorrectableError && *pibitCorrupted != -1 ) || ( !*pfCorrectableError && *pibitCorrupted == -1 ) );
// no point in re-computing the checksum if we haven't done any changes
if ( fCorrectError && *pfCorrectableError )
{
*pchecksumExpected = ChecksumFromPage( pv, pagetype );
*pchecksumActual = ComputePageChecksum( pv, cb, pagetype, pgno, fTrue );
}
}
}
| 32.591588 | 142 | 0.51242 | ScriptBox99 |
22790e90761843a29aec9854856aa2efcfa93323 | 1,438 | cpp | C++ | 1_Practice_CPP/_CPP_LEARNING__Switch_Operations.cpp | CyberThulhu22/CPP-Projects | d5ed94d45988e5b18ebdff3d19658af87d94a2df | [
"MIT"
] | null | null | null | 1_Practice_CPP/_CPP_LEARNING__Switch_Operations.cpp | CyberThulhu22/CPP-Projects | d5ed94d45988e5b18ebdff3d19658af87d94a2df | [
"MIT"
] | null | null | null | 1_Practice_CPP/_CPP_LEARNING__Switch_Operations.cpp | CyberThulhu22/CPP-Projects | d5ed94d45988e5b18ebdff3d19658af87d94a2df | [
"MIT"
] | 1 | 2022-01-05T04:18:05.000Z | 2022-01-05T04:18:05.000Z | // Switch Operations
//
// NAME: switchoperation.cpp
// VERSION: 0.0.0
// AUTHOR: Jesse Leverett (CyberThulhu)
// STATUS: Work In Progress
// DESCRIPTION: Basic Program That Teaches Switch Operations
// TO-DO: Build Initial Code Framework
// USAGE: switchoperation.exe
// COPYRIGHT © 2021 Jesse Leverett
#include <iostream>
using namespace std;
/*
Learning how to use Switch Operations!
Useful when you have multiple "If Statements" and need to test a variable against multiple conditions
switch (expression) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
case valueN:
statement(s);
break;
}
*/
int main() {
// Example of Case and Switch Statement(s)
int age = 42; // Initial 'age' is set to 42
switch (age) {
case 16: // If 'age' is equal to 16
std::cout << "Too Young" << std::endl;
break;
case 42: // If 'age' is equal to 42
std::cout << "Adult" << std::endl;
break;
case 70: // If 'age' is equal to 70
std::cout << "Senior" << std::endl;
break;
default: // Default case can be used to perform a task when none of the cases are "True"
std::cout << "This is the default case" << std::endl;
break;
}
return 0;
} | 26.145455 | 105 | 0.552156 | CyberThulhu22 |
227a01ac0980fa4de6464601888d40d831ba3220 | 981 | cc | C++ | chrome/browser/extensions/extension_websocket_apitest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/extensions/extension_websocket_apitest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/extension_websocket_apitest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 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 "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
#if defined(OS_MACOSX)
// WebSocket test started timing out - suspect webkit roll from 67965->68051.
// http://crbug.com/56596
#define MAYBE_WebSocket DISABLED_WebSocket
#else
#define MAYBE_WebSocket WebSocket
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) {
FilePath websocket_root_dir;
PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir);
websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests")
.AppendASCII("LayoutTests");
ui_test_utils::TestWebSocketServer server(websocket_root_dir);
ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
| 37.730769 | 77 | 0.793068 | Gitman1989 |
227d267ea08a5f01e7346694f6a213392478c00a | 401 | cpp | C++ | test/src/GTest2FieldsFENonlinearProblem.cpp | andrsd/godzilla | da2dd8918450d7d28e8f1897466eb82f2a65a467 | [
"MIT"
] | null | null | null | test/src/GTest2FieldsFENonlinearProblem.cpp | andrsd/godzilla | da2dd8918450d7d28e8f1897466eb82f2a65a467 | [
"MIT"
] | 24 | 2021-11-13T01:32:41.000Z | 2021-12-11T14:16:24.000Z | test/src/GTest2FieldsFENonlinearProblem.cpp | andrsd/godzilla | da2dd8918450d7d28e8f1897466eb82f2a65a467 | [
"MIT"
] | null | null | null | #include "GTest2FieldsFENonlinearProblem.h"
#include "Godzilla.h"
registerObject(GTest2FieldsFENonlinearProblem);
GTest2FieldsFENonlinearProblem::GTest2FieldsFENonlinearProblem(const InputParameters & params) :
GTestFENonlinearProblem(params),
iv(1)
{
}
void
GTest2FieldsFENonlinearProblem::set_up_fields()
{
GTestFENonlinearProblem::set_up_fields();
add_fe(this->iv, "v", 1, 1);
}
| 22.277778 | 96 | 0.783042 | andrsd |
22839c7c3a288dc0d1ee45357a36dee0ff3a1deb | 706 | hpp | C++ | Code/include/OE/Engine/Transform.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 21 | 2018-06-26T16:37:36.000Z | 2022-01-11T01:19:42.000Z | Code/include/OE/Engine/Transform.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | null | null | null | Code/include/OE/Engine/Transform.hpp | mlomb/OrbitEngine | 41f053626f05782e81c2e48f5c87b04972f9be2c | [
"Apache-2.0"
] | 3 | 2019-10-01T14:10:50.000Z | 2021-11-19T20:30:18.000Z | #ifndef ENGINE_TRANSFORM_HPP
#define ENGINE_TRANSFORM_HPP
#include "OE/Config.hpp"
#include "OE/Engine/Component.hpp"
#include "OE/Math/Vec3.hpp"
#include "OE/Math/Mat4.hpp"
namespace OrbitEngine { namespace Engine {
class Transform : public Component {
NATIVE_REFLECTION
public:
Transform();
~Transform();
Math::Vec3f GetPosition() const;
Math::Vec3f GetRotation() const;
Math::Vec3f GetScale() const;
Math::Mat4 getMatrix();
void SetPosition(const Math::Vec3f& pos);
void SetRotation(const Math::Vec3f& rot);
void SetScale(const Math::Vec3f& scale);
private:
Math::Mat4 m_Matrix;
Math::Vec3f m_Position;
Math::Vec3f m_Rotation;
Math::Vec3f m_Scale;
};
} }
#endif | 19.081081 | 43 | 0.719547 | mlomb |
22841b4dac3d8081a32c55ba564bf19e5a34d857 | 15,614 | cpp | C++ | src/vidhrdw/mermaid.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 8 | 2020-05-01T15:15:16.000Z | 2021-05-30T18:49:15.000Z | src/vidhrdw/mermaid.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | null | null | null | src/vidhrdw/mermaid.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 5 | 2020-05-07T18:38:11.000Z | 2021-08-03T12:57:41.000Z | /***************************************************************************
vidhrdw.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "driver.h"
#include "tilemap.h"
#include "vidhrdw/generic.h"
unsigned char* mermaid_background_videoram;
unsigned char* mermaid_foreground_videoram;
unsigned char* mermaid_foreground_colorram;
unsigned char* mermaid_background_scrollram;
unsigned char* mermaid_foreground_scrollram;
static struct osd_bitmap *helper;
static struct osd_bitmap *helper2;
static struct tilemap *bg_tilemap, *fg_tilemap;
static int coll_bit0,coll_bit1,coll_bit2,coll_bit3,coll_bit6 = 0;
static int mermaid_flipscreen_x, mermaid_flipscreen_y;
static int rougien_gfxbank1, rougien_gfxbank2;
static struct rectangle spritevisiblearea =
{
0*8, 26*8-1,
2*8, 30*8-1
};
WRITE_HANDLER( mermaid_background_videoram_w )
{
mermaid_background_videoram[offset] = data;
tilemap_mark_tile_dirty(bg_tilemap, offset);
}
WRITE_HANDLER( mermaid_foreground_videoram_w )
{
mermaid_foreground_videoram[offset] = data;
tilemap_mark_tile_dirty(fg_tilemap, offset);
}
WRITE_HANDLER( mermaid_foreground_colorram_w )
{
mermaid_foreground_colorram[offset] = data;
tilemap_mark_tile_dirty(fg_tilemap, offset);
}
WRITE_HANDLER( mermaid_flip_screen_x_w )
{
mermaid_flipscreen_x = data & 0x01;
}
WRITE_HANDLER( mermaid_flip_screen_y_w )
{
mermaid_flipscreen_y = data & 0x01;
}
WRITE_HANDLER( mermaid_bg_scroll_w )
{
mermaid_background_scrollram[offset] = data;
tilemap_set_scrolly(bg_tilemap, offset, data);
}
WRITE_HANDLER( mermaid_fg_scroll_w )
{
mermaid_foreground_scrollram[offset] = data;
tilemap_set_scrolly(fg_tilemap, offset, data);
}
WRITE_HANDLER( rougien_gfxbankswitch1_w )
{
rougien_gfxbank1 = data & 0x01;
}
WRITE_HANDLER( rougien_gfxbankswitch2_w )
{
rougien_gfxbank2 = data & 0x01;
}
READ_HANDLER( mermaid_collision_r )
{
/*
collision register active LOW:
with coll = spriteram[offs + 2] & 0xc0
Bit 0 - Sprite (coll = 0x40) - Sprite (coll = 0x00)
Bit 1 - Sprite (coll = 0x40) - Foreground
Bit 2 - Sprite (coll = 0x40) - Background
Bit 3 - Sprite (coll = 0x80) - Sprite (coll = 0x00)
Bit 4
Bit 5
Bit 6 - Sprite (coll = 0x40) - Sprite (coll = 0x80)
Bit 7
*/
int collision = 0xff;
if(coll_bit0) collision &= 0xfe;
if(coll_bit1) collision &= 0xfd;
if(coll_bit2) collision &= 0xfb;
if(coll_bit3) collision &= 0xf7;
if(coll_bit6) collision &= 0xbf;
return collision;
}
/***************************************************************************
Convert the color PROMs into a more useable format.
I'm not sure about the resistor value, I'm using the Galaxian ones.
***************************************************************************/
void mermaid_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom)
{
#define TOTAL_COLORS(gfxn) (Machine->gfx[gfxn]->total_colors * Machine->gfx[gfxn]->color_granularity)
#define COLOR(gfxn,offs) (colortable[Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + offs])
int i;
/* first, the char acter/sprite palette */
for (i = 0;i < TOTAL_COLORS(0); i++)
{
int bit0,bit1,bit2;
/* red component */
bit0 = (*color_prom >> 0) & 0x01;
bit1 = (*color_prom >> 1) & 0x01;
bit2 = (*color_prom >> 2) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* green component */
bit0 = (*color_prom >> 3) & 0x01;
bit1 = (*color_prom >> 4) & 0x01;
bit2 = (*color_prom >> 5) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* blue component */
bit0 = 0;
bit1 = (*color_prom >> 6) & 0x01;
bit2 = (*color_prom >> 7) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
color_prom++;
}
/* blue background */
*(palette++) = 0;
*(palette++) = 0;
*(palette++) = 0xff;
/* set up background palette */
COLOR(2,0) = 32;
COLOR(2,1) = 33;
COLOR(2,2) = 64;
COLOR(2,3) = 33;
}
void rougien_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom)
{
#define TOTAL_COLORS(gfxn) (Machine->gfx[gfxn]->total_colors * Machine->gfx[gfxn]->color_granularity)
#define COLOR(gfxn,offs) (colortable[Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + offs])
int i;
/* first, the char acter/sprite palette */
for (i = 0;i < TOTAL_COLORS(0); i++)
{
int bit0,bit1,bit2;
/* red component */
bit0 = (*color_prom >> 0) & 0x01;
bit1 = (*color_prom >> 1) & 0x01;
bit2 = (*color_prom >> 2) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* green component */
bit0 = (*color_prom >> 3) & 0x01;
bit1 = (*color_prom >> 4) & 0x01;
bit2 = (*color_prom >> 5) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* blue component */
bit0 = 0;
bit1 = (*color_prom >> 6) & 0x01;
bit2 = (*color_prom >> 7) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
color_prom++;
}
/* black background */
*(palette++) = 0;
*(palette++) = 0;
*(palette++) = 0;
/* set up background palette */
COLOR(2,0) = 0x40;
COLOR(2,1) = 0x00;
COLOR(2,2) = 0x00;
COLOR(2,3) = 0x02;
}
static void draw_sprites(struct osd_bitmap *dest_bitmap)
{
int offs;
/* draw the sprites */
for (offs = spriteram_size - 4;offs >= 0;offs -= 4)
{
int flipx,flipy,sx,sy,code,bank,attr,color;
attr = spriteram[offs + 2];
color = attr & 0x0f;
bank = (attr & 0x30) >> 4;
code = (spriteram[offs] & 0x3f) | (bank << 6);
code |= rougien_gfxbank1 * 0x2800;
code |= rougien_gfxbank2 * 0x2400;
sx = spriteram[offs + 3] + 1;
if (sx >= 0xf0) sx -= 256;
sy = 240 - spriteram[offs + 1];
flipx = spriteram[offs + 0] & 0x40;
flipy = spriteram[offs + 0] & 0x80;
drawgfx(dest_bitmap,Machine->gfx[1],
code,
color,
flipx, flipy,
sx, sy,
&spritevisiblearea,TRANSPARENCY_PEN,0);
}
}
static void get_bg_tile_info (int tile_index)
{
int code = mermaid_background_videoram[tile_index];
int sx = tile_index % 32;
int color = (sx >= 26) ? 0 : 1;
SET_TILE_INFO(2, code, color);
}
static void get_fg_tile_info (int tile_index)
{
int attr = mermaid_foreground_colorram[tile_index];
int code = mermaid_foreground_videoram[tile_index] + ((attr & 0x30) << 4);
int color = attr & 0x0f;
code |= rougien_gfxbank1 * 0x2800;
code |= rougien_gfxbank2 * 0x2400;
SET_TILE_INFO(0, code, color);
tile_info.flags = TILE_FLIPYX((attr & 0xc0) >> 6);
}
static unsigned char mermaid_colcheck(int bit, const struct rectangle* rect)
{
unsigned char data = 0;
int x;
int y;
for (y = rect->min_y; y <= rect->max_y; y++)
{
for (x = rect->min_x; x <= rect->max_x; x++)
{
unsigned int pa = read_pixel(helper, x, y);
unsigned int pb = read_pixel(helper2, x, y);
//a[x- rect->min_x] = pa;
//b[x- rect->min_x] = pb;
if (pb != 0)
if ((pa != 0) & (pa != 0x40))
data |= 0x01;
}
}
return data;
}
void mermaid_vh_eof(void)
{
const struct rectangle *visarea = &Machine->visible_area;
int offs,offs2;
coll_bit1 = 0;
coll_bit2 = 0;
coll_bit3 = 0;
coll_bit6 = 0;
coll_bit0 = 0;
// check for bit 0 (sprite-sprite), 1 (sprite-foreground), 2 (sprite-background)
for (offs = spriteram_size - 4; offs >= 0; offs -= 4)
{
int attr = spriteram[offs + 2];
int bank = (attr & 0x30) >> 4;
int coll = (attr & 0xc0) >> 6;
int code = (spriteram[offs] & 0x3f) | (bank << 6);
int flipx = spriteram[offs] & 0x40;
int flipy = spriteram[offs] & 0x80;
int sx = spriteram[offs + 3] + 1;
int sy = 240 - spriteram[offs + 1];
struct rectangle rect;
if (coll != 1) continue;
code |= rougien_gfxbank1 * 0x2800;
code |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flipscreen_x)
{
flipx = !flipx;
sx = 240 - sx;
}
if (mermaid_flipscreen_y)
{
flipy = !flipy;
sy = 240 - sy;
}
#endif
rect.min_x = sx;
rect.min_y = sy;
rect.max_x = sx + Machine->gfx[1]->width - 1;
rect.max_y = sy + Machine->gfx[1]->height - 1;
if (rect.min_x < visarea->min_x)
rect.min_x = visarea->min_x;
if (rect.min_y < visarea->min_y)
rect.min_y = visarea->min_y;
if (rect.max_x > visarea->max_x)
rect.max_x = visarea->max_x;
if (rect.max_y > visarea->max_y)
rect.max_y = visarea->max_y;
tilemap_set_clip(bg_tilemap, &rect);
tilemap_set_clip(fg_tilemap, &rect);
// check collision sprite - background
fillbitmap(helper,0,&rect);
fillbitmap(helper2,0,&rect);
tilemap_draw(helper, bg_tilemap, 0);
drawgfx(helper2, Machine->gfx[1], code, 0, flipx, flipy, sx, sy,
&rect,TRANSPARENCY_PEN, 0);
coll_bit2 |= mermaid_colcheck(2, &rect);
// check collision sprite - foreground
fillbitmap(helper,0,&rect);
fillbitmap(helper2,0,&rect);
tilemap_draw(helper, fg_tilemap, 0);
drawgfx(helper2, Machine->gfx[1], code, 0, flipx, flipy, sx, sy,
&rect,TRANSPARENCY_PEN, 0);
coll_bit1 |= mermaid_colcheck(1, &rect);
// check collision sprite - sprite
fillbitmap(helper,0,&rect);
fillbitmap(helper2,0,&rect);
for (offs2 = spriteram_size - 4; offs2 >= 0; offs2 -= 4)
if (offs != offs2)
{
int attr2 = spriteram[offs2 + 2];
int bank2 = (attr2 & 0x30) >> 4;
int coll2 = (attr2 & 0xc0) >> 6;
int code2 = (spriteram[offs2] & 0x3f) | (bank2 << 6);
int flipx2 = spriteram[offs2] & 0x40;
int flipy2 = spriteram[offs2] & 0x80;
int sx2 = spriteram[offs2 + 3] + 1;
int sy2 = 240 - spriteram[offs2 + 1];
if (coll2 != 0) continue;
code2 |= rougien_gfxbank1 * 0x2800;
code2 |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flip_screen_x)
{
flipx2 = !flipx2;
sx2 = 240 - sx2;
}
if (mermaid_flip_screen_y)
{
flipy2 = !flipy2;
sy2 = 240 - sy2;
}
#endif
drawgfx(helper, Machine->gfx[1], code2, 0, flipx2, flipy2, sx2, sy2,
&rect,TRANSPARENCY_PEN, 0);
}
drawgfx(helper2, Machine->gfx[1], code, 0, flipx, flipy, sx, sy,
&rect,TRANSPARENCY_PEN, 0);
coll_bit0 |= mermaid_colcheck(0, &rect);
}
// check for bit 3 (sprite-sprite)
for (offs = spriteram_size - 4; offs >= 0; offs -= 4)
{
int attr = spriteram[offs + 2];
int bank = (attr & 0x30) >> 4;
int coll = (attr & 0xc0) >> 6;
int code = (spriteram[offs] & 0x3f) | (bank << 6);
int flipx = spriteram[offs] & 0x40;
int flipy = spriteram[offs] & 0x80;
int sx = spriteram[offs + 3] + 1;
int sy = 240 - spriteram[offs + 1];
struct rectangle rect;
if (coll != 2) continue;
code |= rougien_gfxbank1 * 0x2800;
code |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flipscreen_x)
{
flipx = !flipx;
sx = 240 - sx;
}
if (mermaid_flipscreen_y)
{
flipy = !flipy;
sy = 240 - sy;
}
#endif
rect.min_x = sx;
rect.min_y = sy;
rect.max_x = sx + Machine->gfx[1]->width - 1;
rect.max_y = sy + Machine->gfx[1]->height - 1;
if (rect.min_x < visarea->min_x)
rect.min_x = visarea->min_x;
if (rect.min_y < visarea->min_y)
rect.min_y = visarea->min_y;
if (rect.max_x > visarea->max_x)
rect.max_x = visarea->max_x;
if (rect.max_y > visarea->max_y)
rect.max_y = visarea->max_y;
// check collision sprite - sprite
fillbitmap(helper,0,&rect);
fillbitmap(helper2,0,&rect);
for (offs2 = spriteram_size - 4; offs2 >= 0; offs2 -= 4)
if (offs != offs2)
{
int attr2 = spriteram[offs2 + 2];
int bank2 = (attr2 & 0x30) >> 4;
int coll2 = (attr2 & 0xc0) >> 6;
int code2 = (spriteram[offs2] & 0x3f) | (bank2 << 6);
int flipx2 = spriteram[offs2] & 0x40;
int flipy2 = spriteram[offs2] & 0x80;
int sx2 = spriteram[offs2 + 3] + 1;
int sy2 = 240 - spriteram[offs2 + 1];
if (coll2 != 0) continue;
code2 |= rougien_gfxbank1 * 0x2800;
code2 |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flipscreen_x)
{
flipx = !flipx;
sx = 240 - sx;
}
if (mermaid_flipscreen_y)
{
flipy = !flipy;
sy = 240 - sy;
}
#endif
drawgfx(helper, Machine->gfx[1], code2, 0, flipx2, flipy2, sx2, sy2,
&rect,TRANSPARENCY_PEN, 0);
}
drawgfx(helper2, Machine->gfx[1], code, 0, flipx, flipy, sx, sy,
&rect,TRANSPARENCY_PEN, 0);
coll_bit3 |= mermaid_colcheck(3, &rect);
}
// check for bit 6
for (offs = spriteram_size - 4; offs >= 0; offs -= 4)
{
int attr = spriteram[offs + 2];
int bank = (attr & 0x30) >> 4;
int coll = (attr & 0xc0) >> 6;
int code = (spriteram[offs] & 0x3f) | (bank << 6);
int flipx = spriteram[offs] & 0x40;
int flipy = spriteram[offs] & 0x80;
int sx = spriteram[offs + 3] + 1;
int sy = 240 - spriteram[offs + 1];
struct rectangle rect;
if (coll != 1) continue;
code |= rougien_gfxbank1 * 0x2800;
code |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flipscreen_x)
{
flipx = !flipx;
sx = 240 - sx;
}
if (mermaid_flipscreen_y)
{
flipy = !flipy;
sy = 240 - sy;
}
#endif
rect.min_x = sx;
rect.min_y = sy;
rect.max_x = sx + Machine->gfx[1]->width - 1;
rect.max_y = sy + Machine->gfx[1]->height - 1;
if (rect.min_x < visarea->min_x)
rect.min_x = visarea->min_x;
if (rect.min_y < visarea->min_y)
rect.min_y = visarea->min_y;
if (rect.max_x > visarea->max_x)
rect.max_x = visarea->max_x;
if (rect.max_y > visarea->max_y)
rect.max_y = visarea->max_y;
// check collision sprite - sprite
fillbitmap(helper,0,&rect);
fillbitmap(helper2,0,&rect);
for (offs2 = spriteram_size - 4; offs2 >= 0; offs2 -= 4)
if (offs != offs2)
{
int attr2 = spriteram[offs2 + 2];
int bank2 = (attr2 & 0x30) >> 4;
int coll2 = (attr2 & 0xc0) >> 6;
int code2 = (spriteram[offs2] & 0x3f) | (bank2 << 6);
int flipx2 = spriteram[offs2] & 0x40;
int flipy2 = spriteram[offs2] & 0x80;
int sx2 = spriteram[offs2 + 3] + 1;
int sy2 = 240 - spriteram[offs2 + 1];
if (coll2 != 2) continue;
code2 |= rougien_gfxbank1 * 0x2800;
code2 |= rougien_gfxbank2 * 0x2400;
#if 0
if (mermaid_flipscreen_x)
{
flipx = !flipx;
sx = 240 - sx;
}
if (mermaid_flipscreen_y)
{
flipy = !flipy;
sy = 240 - sy;
}
#endif
drawgfx(helper, Machine->gfx[1], code2, 0, flipx2, flipy2, sx2, sy2,
&rect,TRANSPARENCY_PEN, 0);
}
drawgfx(helper2, Machine->gfx[1], code, 0, flipx, flipy, sx, sy,
&rect,TRANSPARENCY_PEN, 0);
coll_bit6 |= mermaid_colcheck(6, &rect);
}
}
int mermaid_vh_start(void)
{
helper = bitmap_alloc(Machine->drv->screen_width, Machine->drv->screen_height);
if (!helper)
return 1;
helper2 = bitmap_alloc(Machine->drv->screen_width, Machine->drv->screen_height);
if (!helper2)
{
free (helper);
helper = 0;
return 1;
}
bg_tilemap = tilemap_create(get_bg_tile_info, tilemap_scan_rows, TILEMAP_OPAQUE, 8, 8, 32, 32);
tilemap_set_scroll_cols(bg_tilemap, 32);
fg_tilemap = tilemap_create(get_fg_tile_info, tilemap_scan_rows, TILEMAP_TRANSPARENT, 8, 8, 32, 32);
tilemap_set_scroll_cols(fg_tilemap, 32);
tilemap_set_transparent_pen(fg_tilemap, 0);
if (bg_tilemap && fg_tilemap)
return 0;
else
return 1;
}
void mermaid_vh_stop(void)
{
if (helper)
{
free (helper);
helper = 0;
}
if (helper2)
{
free (helper2);
helper2 = 0;
}
}
void mermaid_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh)
{
tilemap_set_clip(bg_tilemap, &Machine->visible_area);
tilemap_set_clip(fg_tilemap, &Machine->visible_area);
tilemap_update(ALL_TILEMAPS);
tilemap_render(ALL_TILEMAPS);
tilemap_draw(bitmap, bg_tilemap, 0);
tilemap_draw(bitmap, fg_tilemap, 0);
draw_sprites(bitmap);
}
| 23.444444 | 118 | 0.626937 | gameblabla |
22866855db221634cabad0169bdeab827220463b | 128 | cpp | C++ | engine/Source.cpp | LHolmberg/L3D | 6020222700f3ee70cfbf02601bd93bfd59a8fb34 | [
"MIT"
] | null | null | null | engine/Source.cpp | LHolmberg/L3D | 6020222700f3ee70cfbf02601bd93bfd59a8fb34 | [
"MIT"
] | null | null | null | engine/Source.cpp | LHolmberg/L3D | 6020222700f3ee70cfbf02601bd93bfd59a8fb34 | [
"MIT"
] | null | null | null | #include "TESTSAMPLEFILE.h"
int main() {
Game::Startup();
while (running)
Game::Update();
Game::Shutdown();
return 0;
} | 11.636364 | 27 | 0.632813 | LHolmberg |
2288a9f0d5ffd36fe1a4e2e1cc2289293258d161 | 662 | cpp | C++ | SourceCode/Chapter 12/Pr12-4.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | 1 | 2019-04-09T18:29:38.000Z | 2019-04-09T18:29:38.000Z | SourceCode/Chapter 12/Pr12-4.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | SourceCode/Chapter 12/Pr12-4.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | // This program writes three rows of numbers to a file.
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
const int ROWS = 3; // Rows to write
const int COLS = 3; // Columns to write
int nums[ROWS][COLS] = { 2897, 5, 837,
34, 7, 1623,
390, 3456, 12 };
fstream outFile("table.txt", ios::out);
// Write the three rows of numbers with each
// number in a field of 8 character spaces.
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
outFile << setw(8) << nums[row][col];
}
outFile << endl;
}
outFile.close();
cout << "Done.\n";
return 0;
} | 22.827586 | 55 | 0.595166 | aceiro |
228afc782532f44f85c8c75a02be5accb5e677c2 | 2,329 | cpp | C++ | admin/activec/designer/vb98ctls/mssnapr/mssnapr/dataobjs.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/activec/designer/vb98ctls/mssnapr/mssnapr/dataobjs.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/activec/designer/vb98ctls/mssnapr/mssnapr/dataobjs.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=--------------------------------------------------------------------------=
// dataobjs.cpp
//=--------------------------------------------------------------------------=
// Copyright (c) 1999, Microsoft Corp.
// All Rights Reserved
// Information Contained Herein Is Proprietary and Confidential.
//=--------------------------------------------------------------------------=
//
// CMMCDataObjects class implementation
//
//=--------------------------------------------------------------------------=
#include "pch.h"
#include "common.h"
#include "dataobjs.h"
// for ASSERT and FAIL
//
SZTHISFILE
#pragma warning(disable:4355) // using 'this' in constructor
CMMCDataObjects::CMMCDataObjects(IUnknown *punkOuter) :
CSnapInCollection<IMMCDataObject, MMCDataObject, IMMCDataObjects>(punkOuter,
OBJECT_TYPE_MMCDATAOBJECTS,
static_cast<IMMCDataObjects *>(this),
static_cast<CMMCDataObjects *>(this),
CLSID_MMCDataObject,
OBJECT_TYPE_MMCDATAOBJECT,
IID_IMMCDataObject,
NULL)
{
}
#pragma warning(default:4355) // using 'this' in constructor
CMMCDataObjects::~CMMCDataObjects()
{
}
IUnknown *CMMCDataObjects::Create(IUnknown * punkOuter)
{
CMMCDataObjects *pMMCDataObjects = New CMMCDataObjects(punkOuter);
if (NULL == pMMCDataObjects)
{
return NULL;
}
else
{
return pMMCDataObjects->PrivateUnknown();
}
}
//=--------------------------------------------------------------------------=
// CUnknownObject Methods
//=--------------------------------------------------------------------------=
HRESULT CMMCDataObjects::InternalQueryInterface(REFIID riid, void **ppvObjOut)
{
if(IID_IMMCDataObjects == riid)
{
*ppvObjOut = static_cast<IMMCDataObjects *>(this);
ExternalAddRef();
return S_OK;
}
else
return CSnapInCollection<IMMCDataObject, MMCDataObject, IMMCDataObjects>::InternalQueryInterface(riid, ppvObjOut);
}
| 31.90411 | 123 | 0.451696 | npocmaka |
228e98e9c38d2139893a515586219984c9e0031b | 113 | hpp | C++ | redvoid/src/DLL.hpp | fictionalist/RED-VOID | 01bacd893f095748d784e494c80a6a9c96481acc | [
"MIT"
] | 1 | 2021-01-04T01:31:34.000Z | 2021-01-04T01:31:34.000Z | redvoid/src/DLL.hpp | fictionalist/RED-VOID | 01bacd893f095748d784e494c80a6a9c96481acc | [
"MIT"
] | null | null | null | redvoid/src/DLL.hpp | fictionalist/RED-VOID | 01bacd893f095748d784e494c80a6a9c96481acc | [
"MIT"
] | 1 | 2021-01-05T00:55:47.000Z | 2021-01-05T00:55:47.000Z | #pragma once
#include <Windows.h>
namespace DLL {
void init();
void quit();
DWORD WINAPI main(LPVOID lp);
}
| 11.3 | 30 | 0.672566 | fictionalist |
228f97ad7c8a18ceeaf766bfe8470114312b1d06 | 12,309 | cpp | C++ | SDL2/SDL2Engine/SDL2Engine/Player.cpp | functard/INK.-A-SDL-2-GAME | 2b65706c65ba38fa909c8b7726863f3c4e835748 | [
"MIT"
] | 1 | 2022-02-22T13:42:44.000Z | 2022-02-22T13:42:44.000Z | SDL2/SDL2Engine/SDL2Engine/Player.cpp | functard/INK.-A-SDL-2-GAME | 2b65706c65ba38fa909c8b7726863f3c4e835748 | [
"MIT"
] | null | null | null | SDL2/SDL2Engine/SDL2Engine/Player.cpp | functard/INK.-A-SDL-2-GAME | 2b65706c65ba38fa909c8b7726863f3c4e835748 | [
"MIT"
] | null | null | null | #pragma region project include
#include "Player.h"
#include "Input.h"
#include "Engine.h"
#include "Renderer.h"
#include "ContentManagement.h"
#include "Config.h"
#include "Bullet.h"
#include "MenuScene.h"
#include "MainScene.h"
#include "Animation.h"
#include "Sound.h"
#include "Texture.h"
#include "Config.h"
#include "Time.h"
#include "MoveEnemy.h"
#include "Text.h"
#include "Game.h"
#pragma endregion
//Made by Ege, Iman
GPlayer* GPlayer::pPlayer = nullptr;
#pragma region public function
// initialize player
void GPlayer::Init()
{
pPlayer = this;
#pragma region Ege, Iman
//create take damage animation
m_pTakaDamageAnim = new CAnimation(SVector2(GConfig::s_PlayerSrcRectWidth * 8, 0),
SVector2(GConfig::s_PlayerSrcRectWidth, 165), 2);
//set take damage animation time
m_pTakaDamageAnim->SetAnimationTime(0.5f);
// create idle animation
m_pIdleAnim = new CAnimation(SVector2(0.0f, 0.0f),
SVector2(GConfig::s_PlayerSrcRectWidth , 165), 1);
//create shoot animation
m_pShootAnim = new CAnimation(SVector2(0, 219),
SVector2(GConfig::s_PlayerSrcRectWidth, 155), 5);
//set shoot animation time
m_pShootAnim->SetAnimationTime(0.5f);
// create run animation
m_pRunAnim = new CAnimation(SVector2(0,0),
SVector2(GConfig::s_PlayerSrcRectWidth, GConfig::s_PlayerSrcRectHeight), 8);
//set run animation time
m_pRunAnim->SetAnimationTime(0.5f);
// set idle to current animation
m_pCurrentAnim = m_pIdleAnim;
// create shot sound
m_pShot = new CSound("Audio/S_Shot.wav");
//create fox attack sound
m_pFoxAttack = new CSound("Audio/S_WolfAttack.wav");
//create form changing sound
m_Fox = new CSound("Audio/M_Fox.wav");
#pragma endregion
}
#pragma endregion
#pragma region public override function
// update every frame
void GPlayer::Update(float _deltaSeconds)
{
#pragma region Ege
// if cooldown start
if (m_startCooldown)
{
// set invulnerability to true;
m_invulnerability = true;
// decrease invulnerability timer
m_invulnerabilityTimer -= _deltaSeconds;
//set current animation to take damage
m_pCurrentAnim = m_pTakaDamageAnim;
}
// when timer hits zero
if (m_invulnerabilityTimer <= 0)
{
//reset timer
m_invulnerabilityTimer = 2.0f;
//stop cooldown
m_startCooldown = false;
//set invulnerability to false
m_invulnerability = false;
}
//when shoot animation finishes
if (m_pShootAnim->GetAnimationPercentage() == 100)
{
//can idle
m_canIdle = true;
//can run
m_canRun = true;
//reset animation percantage
m_pShootAnim->ResetAnimationPercentage();
}
//when shoot animation finishes
if (m_pTakaDamageAnim->GetAnimationPercentage() == 100)
{
//reset animation percantage
m_pTakaDamageAnim->ResetAnimationPercentage();
//can idle
m_canIdle = true;
//can run
m_canRun = true;
}
//if hit by boss bullet and not invulnerable
if (m_pColTarget && m_pColTarget->GetTag() == "BossBullet" && !m_invulnerability)
{
//remove bullet
CTM->RemoveObject(m_pColTarget);
//player take damage
m_playerHealth -= 50;
//start invulnerability timer
m_startCooldown = true;
//player invulnerable
m_invulnerability = true;
//set animation to take damage animation
m_pCurrentAnim = m_pTakaDamageAnim;
}
// if collides when falling
if (m_pColFallTarget)
{
// if collides with fire and not invulnerable
if (m_pColFallTarget->GetTag() == "Fire" && !m_invulnerability)
{
//delays for 2 sec
SDL_Delay(2000);
//change scene
ENGINE->ChangeScene(new GMenuScene());
}
}
// if key space is pressed down and is human form jump
if (CInput::GetKeyDown(SDL_SCANCODE_SPACE) && m_grounded && m_isHumanForm)
{
//player jump
SetFallTime(-GConfig::s_PlayerJump);
canJump = false;
}
// if key space is pressed down and is fox form jump
if (CInput::GetKeyDown(SDL_SCANCODE_SPACE) && m_grounded && !m_isHumanForm)
{
//fox currently jumping
isJumping = true;
//set current animation to jump animation
m_pCurrentAnim = m_pJumpAnim;
//fox jump
SetFallTime(-GConfig::s_PlayerJump);
//set can jump to false
canJump = false;
}
// fox form double jump
else if (CInput::GetKeyDown(SDL_SCANCODE_SPACE) && !m_grounded && !canJump && !m_isHumanForm)
{
//fox currently jumping
isJumping = true;
//set current animation to jump animation
m_pCurrentAnim = m_pJumpAnim;
//fox double jump
SetFallTime(-GConfig::s_PlayerJump);
//set can jump to true
canJump = true;
}
// if key r pressed spawn ice bullet
if (CInput::GetKeyDown(SDL_SCANCODE_R) && m_isHumanForm)
{
//can idle
m_canIdle = false;
//can run
m_canRun = false;
//sets current animation to shoot animation
m_pCurrentAnim = m_pShootAnim;
// create ice bullet
GBullet* pBullet = new GBullet(SVector2(), SVector2(8, 8), "Texture/Bullet/T_IceBullet.png");
// spawn left (-1) or right (1) from player
int spawnSide = 1;
// if mirror set spawn side left
if (m_mirror.X)
spawnSide = -1;
// set values
pBullet->SetPosition(SVector2(m_position.X + 20 + spawnSide * m_rect.w, m_position.Y + m_rect.h * 0.25f));
pBullet->SetColType(ECollisionType::WALL);
pBullet->SetSpeed(GConfig::s_BulletSpeed);
pBullet->SetMovement(SVector2(spawnSide, 0.0f));
pBullet->SetTag("Bullet");
// add bullet to content management
CTM->AddPersistantObject(pBullet);
// play shot sound
m_pShot->Play();
}
// if key space spawn ice bullet
if (CInput::GetKeyDown(SDL_SCANCODE_RETURN) && m_isHumanForm)
{
//can idle
m_canIdle = false;
//can run
m_canRun = false;
//set current animation to run
m_pCurrentAnim = m_pShootAnim;
// create bullet
GBullet* pBullet = new GBullet(SVector2(), SVector2(8, 8), "Texture/Bullet/T_Bullet.png");
// spawn left (-1) or right (1) from player
int spawnSide = 1;
// if mirror set spawn side left
if (m_mirror.X)
spawnSide = -1;
// set values
pBullet->SetPosition(SVector2(m_position.X + 20 + spawnSide * m_rect.w, m_position.Y + m_rect.h * 0.25f));
pBullet->SetColType(ECollisionType::WALL);
pBullet->SetSpeed(GConfig::s_BulletSpeed);
pBullet->SetMovement(SVector2(spawnSide, 0.0f));
pBullet->SetTag("Bullet");
// add bullet to content management
CTM->AddPersistantObject(pBullet);
// play shot sound
m_pShot->Play();
// if current animation finishes
if (m_pCurrentAnim->GetAnimationPercentage() == 100)
m_canIdle = true; // can idle
}
#pragma endregion
#pragma region Iman, Ege
//if f pressed and is human
if ((CInput::GetKeyUp(SDL_SCANCODE_F) && m_isHumanForm))
{
//fox texture
m_pTexture = new CTexture("Texture/Player/T_Fox.png");
//not human
m_isHumanForm = false;
//play form change sound
m_Fox->Play();
// create idle animation
m_pIdleAnim = new CAnimation(SVector2(0, 0),
SVector2(210, GConfig::s_FoxSrcRectHeight), 1);
// set idle animation time
m_pIdleAnim->SetAnimationTime(2.0f);
// create walk animation
m_pRunAnim = new CAnimation(SVector2(0,145),
SVector2(GConfig::s_FoxSrcRectWidth, GConfig::s_FoxSrcRectHeight), 6);
// set walk animation time
m_pRunAnim->SetAnimationTime(0.5f);
// create wolf attack animation
m_pAttackAnim = new CAnimation(SVector2(0, 451),
SVector2(230,170), 5);
// set attack animation time
m_pAttackAnim->SetAnimationTime(1.0f);
// create wolf jump animation
m_pJumpAnim = new CAnimation(SVector2(0, 310),
SVector2(230, 137),10);
// set jump animation time
m_pJumpAnim->SetAnimationTime(0.5f);
}
#pragma endregion
#pragma region Iman
//if f pressed and is fox
else if ((CInput::GetKeyUp(SDL_SCANCODE_F) && !m_isHumanForm))
{
//can run
m_canRun = true;
//set player texture
m_pTexture = new CTexture("Texture/Player/T_Player.png");
//is human
m_isHumanForm = true;
// create idle animation
m_pIdleAnim = new CAnimation(SVector2(0.0f, 0),
SVector2(GConfig::s_PlayerSrcRectWidth, GConfig::s_PlayerSrcRectHeight), 1);
// create walk animation
m_pRunAnim = new CAnimation(SVector2(0.0f, 0.0f),
SVector2(GConfig::s_PlayerSrcRectWidth, GConfig::s_PlayerSrcRectHeight), 8);
// set walk animation time
m_pRunAnim->SetAnimationTime(0.5f);
// create shoot animation
m_pShootAnim = new CAnimation(SVector2(0,219),
SVector2(GConfig::s_PlayerSrcRectWidth, 155), 5);
//set shoot animation time
m_pShootAnim->SetAnimationTime(0.5f);
// create jump animation
m_pJumpAnim = new CAnimation(SVector2(0.0f, GConfig::s_PlayerSrcRectHeight * 2),
SVector2(GConfig::s_PlayerSrcRectWidth, GConfig::s_PlayerSrcRectHeight), 8);
}
#pragma endregion
#pragma region Ege
//if fox form and enter pressed
if (CInput::GetKeyDown(SDL_SCANCODE_RETURN) && !m_isHumanForm)
{
//can run
m_canRun = false;
//starts attack
m_isAttacking = true;
//if facing right
if(m_mirror.X == 0)
m_movement = 3.0f; // move right
else
m_movement = -3.0f; // move left
//play fox attack sound
m_pFoxAttack->Play();
}
// if jump animation finishes
if (m_pJumpAnim && m_pJumpAnim->GetAnimationPercentage() == 100)
{
//is jumping
isJumping = false;
//reset animation percentage
m_pJumpAnim->ResetAnimationPercentage();
}
// if key a is pressed and not attacking
if (CInput::GetKey(SDL_SCANCODE_A) && m_isAttacking == false && m_canRun)
{
// set negative x movement and mirror horizontal
m_movement.X = -10.0f;
m_mirror.X = 1.0f;
// set current animation to run
if(!isJumping )//c)
m_pCurrentAnim = m_pRunAnim;
//can idle
m_canIdle = true;
}
// if key d is pressed and not attacking
else if (CInput::GetKey(SDL_SCANCODE_D) && m_isAttacking == false && m_canRun)
{
// set positive x movement and mirror none
//set movement
m_movement.X = 10.0f;
//set direction
m_mirror.X = 0.0f;
//if is jumping
if (!isJumping)
m_pCurrentAnim = m_pRunAnim; // set current animation to run
//can idle
m_canIdle = true;
}
// if fox attack
else if (m_isAttacking)
{
// set attack animation
m_pCurrentAnim = m_pAttackAnim;
//if animation finishes
if (m_pCurrentAnim->GetAnimationPercentage() == 100)
{
//reset animation percentage
m_pCurrentAnim->ResetAnimationPercentage();
//is attacking
m_isAttacking = false;
//can run
m_canRun = true;
}
}
// else no x movement
else
{
m_movement.X = 0.0f;
if (!isJumping && m_canIdle)
{
//reset shoot animation
m_pShootAnim->ResetAnimationPercentage();
// set current animation to idle
m_pCurrentAnim = m_pIdleAnim;
}
}
// update animation
m_pCurrentAnim->Update(_deltaSeconds);
// set source from animation
m_srcRect = SRect(
m_pCurrentAnim->GetSize().X,
m_pCurrentAnim->GetSize().Y,
m_pCurrentAnim->GetCurrentTexturePosition().X,
m_pCurrentAnim->GetCurrentTexturePosition().Y
);
// if collision target valid and is enemy and not attacking destroy all and back to menu
if (m_pColTarget && m_pColTarget->GetTag() == "Enemy" && !m_isAttacking)
{
if (!m_invulnerability)
m_playerHealth -= 50;
//can idle
m_canIdle = false;
//can run
m_canRun = false;
//invulnerable
m_invulnerability = true;
//start invulnerability timer
m_startCooldown = true;
}
// if collision target valid and is enemy and not attacking destroy all and back to menu
if (m_pColTarget && m_pColTarget->GetTag() == "Boss" && !m_isAttacking)
{
// if not invulnerable
if (!m_invulnerability)
m_playerHealth -= 50; // player get damage
//can idle
m_canIdle = false;
//can run
m_canRun = false;
//is invulnerable
m_invulnerability = true;
//start invulnerability timer
m_startCooldown = true;
}
//if player dies
if (m_playerHealth <= 0)
{
//delays for 2 sec
SDL_Delay(2000);
//change scene
ENGINE->ChangeScene(new GMenuScene());
}
// if collision target valid and is enemy and is attacking
else if (m_pColTarget && (m_pColTarget->GetTag() == "Enemy" || m_pColTarget->GetTag() == "Boss") && m_isAttacking)
{
//damage enemy
GMoveEnemy::Get()->m_health -= 20;
}
// update parent
CMoveEntity::Update(_deltaSeconds);
// parent camera to player
RENDERER->SetCamera(m_position);
}
#pragma endregion
// render every frame
void GPlayer::Render()
{
CMoveEntity::Render();
}
#pragma endregion
| 20.79223 | 115 | 0.699488 | functard |
22941298dfcca580c5dc668974c30d6ed6b491c1 | 397 | hpp | C++ | Parser/includes/RapidJsonErrorHandler.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | 2 | 2020-02-12T12:02:00.000Z | 2020-12-23T15:31:59.000Z | Parser/includes/RapidJsonErrorHandler.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | null | null | null | Parser/includes/RapidJsonErrorHandler.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | 2 | 2020-02-12T12:02:03.000Z | 2020-12-23T15:32:55.000Z | //
// Created by Quentin Liardeaux on 11/18/19.
//
#ifndef R_TYPE_RAPIDJSONERRORHANDLER_HPP
#define R_TYPE_RAPIDJSONERRORHANDLER_HPP
#include <string>
#include "ParseError.hpp"
#include "rapidjson/document.h"
class RapidJsonErrorHandler {
public:
static const rapidjson::Value &getValidValue(rapidjson::Value const &value, const string &id);
};
#endif //R_TYPE_RAPIDJSONERRORHANDLER_HPP
| 19.85 | 98 | 0.783375 | LiardeauxQ |
2294966034f0c3b8f277cccd7cae798cfcec69a5 | 14,328 | cpp | C++ | CT/CT_PhysX.cpp | ca1773130n/CubeTop | 15059ad1c82723738d6c2bfb529663eb0796ff50 | [
"MIT"
] | null | null | null | CT/CT_PhysX.cpp | ca1773130n/CubeTop | 15059ad1c82723738d6c2bfb529663eb0796ff50 | [
"MIT"
] | null | null | null | CT/CT_PhysX.cpp | ca1773130n/CubeTop | 15059ad1c82723738d6c2bfb529663eb0796ff50 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CT_PhysX.h"
#include "CT_Object.h"
#include "NxCooking.h"
#include "Stream.h"
#include <vector>
/*************************************************************************************************************************************************************/
/* 피직스 클래스 */
/*************************************************************************************************************************************************************/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 메인 초기화 함수
PhysX 환경을 초기화 하는 함수이다. SDK를 초기화 하고 기본 파라미터를 설정한다.
* \param VOID 없음
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL
CtPhysX::Init( VOID )
{
NxPhysicsSDKDesc desc;
NxSDKCreateError errorCode = NXCE_NO_ERROR;
m_pPhysXSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode );
if( !m_pPhysXSDK )
{
MessageBox( 0, L"PhysX SDK를 초기화하지 못했습니다.", 0, 0 );
return false;
}
NxHWVersion hwCheck = m_pPhysXSDK->getHWVersion();
m_bHasHW = (hwCheck != NX_HW_VERSION_NONE);
// PhysX 파라미터 설정
m_pPhysXSDK->setParameter( NX_SKIN_WIDTH, 0.005f );
m_pPhysXSDK->setParameter( NX_ASYNCHRONOUS_MESH_CREATION, 1.0f );
m_bSimulation = TRUE;
// 쿠킹 초기화
if( !NxInitCooking() )
{
MessageBox(0,L"NxInitCooking 실패!",0,0);
exit(0);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief PhysX 씬 생성 함수
큐브 마다 할당되는 기본 씬 객체를 생성하는 함수이다. 이 함수는 한개의 ground plane static actor를 갖는 기본 씬을 생성한다.
또 이 기본 씬은 기본 및 고마찰력 피직스 재질 및 기본 collision group들을 갖는다.
* \note
씬을 생성할 때 NxSceneDesc 작성시 flags 값에 유의할 것. 멀티쓰레딩 시 원하지 않는 결과를 얻을 수 있다.
* \param VOID 없음
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NxScene*
CtPhysX::CreateScene( VOID )
{
NxBounds3 bounds;
bounds.max = NxVec3( -32, -32, -32 );
bounds.min = NxVec3( 32, 32, 32 );
NxSceneDesc sceneDesc;
sceneDesc.simType = ( m_bHasHW ? NX_SIMULATION_HW : NX_SIMULATION_SW );
sceneDesc.gravity = NxVec3( 0.0f, -20.0f, 0.f );
sceneDesc.maxBounds = &bounds;
sceneDesc.flags |= NX_SF_RESTRICTED_SCENE;
sceneDesc.flags |= NX_SF_ENABLE_MULTITHREAD;
//sceneDesc.flags &= ~NX_SF_SIMULATE_SEPARATE_THREAD;
NxScene *scene = m_pPhysXSDK->createScene( sceneDesc );
if( !scene )
{
MessageBox( 0, L"PhysX Scene 생성 에러", 0, 0 );
return NULL;
}
// 기본 재질 설정
NxMaterial* defaultMaterial = scene->getMaterialFromIndex( 0 );
defaultMaterial->setRestitution( 0.0f );
defaultMaterial->setStaticFriction( 0.4f );
defaultMaterial->setDynamicFriction( 0.2f );
NxMaterialDesc mDesc;
mDesc.staticFriction = 1000.0f;
mDesc.dynamicFriction = 1000.0f;
mDesc.restitution = 0.f;
scene->createMaterial( mDesc );
scene->setGroupCollisionFlag( ACTOR_GROUP_DEFAULT, ACTOR_GROUP_TEMPPLANE, FALSE );
scene->setGroupCollisionFlag( ACTOR_GROUP_DEFAULT, ACTOR_GROUP_BREAKINGCHIP, FALSE );
scene->setGroupCollisionFlag( ACTOR_GROUP_BREAKINGCHIP, ACTOR_GROUP_BREAKINGCHIP, FALSE );
// 이벤트 처리를 위한 user notify, contact report 등록
scene->setUserNotify( &m_PhysXUserNotify );
scene->setUserContactReport( &m_PhysXContactReport );
// 큐브 내부 6면 액터 생성
NxPlaneShapeDesc planeDesc;
NxActorDesc actorDesc;
planeDesc.normal = NxVec3( 0, 1, 0 );
planeDesc.d = 0;
actorDesc.shapes.pushBack( &planeDesc );
scene->createActor( actorDesc );
return scene;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 객체 정리 함수
* \param VOID 없음
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID
CtPhysX::Exit( VOID )
{
if(m_pPhysXSDK != NULL)
{
NxReleasePhysicsSDK(m_pPhysXSDK);
m_pPhysXSDK = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 지정한 씬의 두 액터 사이에 고정 조인트를 생성하는 함수
* \param pScene 씬 포인터
* \param a0 액터1 포인터
* \param a1 액터2 포인터
* \return 생성한 조인트 포인터
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NxFixedJoint*
CtPhysX::CreateFixedJoint( NxScene* pScene, NxActor* a0, NxActor* a1 )
{
NxFixedJointDesc jointDesc;
jointDesc.jointFlags |= NX_JPM_LINEAR_MINDIST;
jointDesc.actor[0] = a0;
jointDesc.actor[1] = a1;
NxFixedJoint *joint = (NxFixedJoint*)pScene->createJoint(jointDesc);
return joint;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 박스 등 기본도형이 아닌 실제 메시의 액터를 생성하는 함수이다.
* @param bScaling 액터를 생성할때 객체의 스케일 정보를 사용할 것인지 여부
* @warning
PhysX 기본 도형 간 및 기본 도형과 TriangleMesh 액터 간의 충돌처리는 제대로 되나
TriangleMesh 간의 충돌처리는 완전하지 않다. 이것을 위해서는 Pmap을 사용하여야 한다.
Pmap를 사용하려면 최초 1번은 메시 파일에 대한 Pmap 파일을 작성하여야 하며, 비용이 크다.
한번 Pmap 파일을 작성하였으면 다음부터는 그것을 불러들여 사용하면 되고 비용은 거의 들지 않는다.
Pmap을 사용하더라도 TriangleMesh간의 충돌처리는 완전하지 않다. TriangleMesh가 실제 메시를
많이 단순화시키기 때문이다. Pmap의 하드웨어 지원은 아직 되지 않고 있다.
* \param pObject CT객체 포인터
* \param bScaling TRUE이면 객체의 스케일 벡터에 따라 스케일링된 피직스 메시 생성, FALSE면 그대로 생성
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID
CtPhysX::GenerateTriangleMesh( VOID* pObject, bool bScaling )
{
CtObjectBase* pObj = (CtObjectBase*)pObject;
LPD3DXMESH pMesh = pObj->GetDXUTMesh()->m_pMesh;
DWORD NumVerticies = pMesh->GetNumVertices();
DWORD NumTriangles = pMesh->GetNumFaces();
NxVec3* verts = new NxVec3[NumVerticies];
WORD*pIndices = new WORD[NumTriangles*3];
FLOAT maxX = 0, maxY = 0, maxZ = 0; // 부피 추정을 위한 값들
BYTE* DXMeshPtr;
pMesh->LockVertexBuffer(D3DLOCK_READONLY, (VOID**)&DXMeshPtr);
//////////////////////////////////////////////////////////////////////////
// 버텍스 버퍼 채움
//////////////////////////////////////////////////////////////////////////
NxVec3 vScale = pObj->GetScale();
DWORD perByte = pMesh->GetNumBytesPerVertex();
for(DWORD i = 0; i < NumVerticies; i++)
{
MESHVERTEX *DXMeshFVF = (MESHVERTEX*)DXMeshPtr;
verts[i] = NxVec3(DXMeshFVF->pos.x * vScale.x, DXMeshFVF->pos.y * vScale.y, DXMeshFVF->pos.z * vScale.z);
if( maxX < verts[i].x ) maxX = verts[i].x;
if( maxY < verts[i].y ) maxY = verts[i].y;
if( maxZ < verts[i].z ) maxZ = verts[i].z;
DXMeshPtr += perByte;
}
pMesh->UnlockVertexBuffer();
//////////////////////////////////////////////////////////////////////////
// 인덱스 버퍼 채움
//////////////////////////////////////////////////////////////////////////
WORD *pIB = 0;
pMesh->LockIndexBuffer(D3DLOCK_READONLY, (VOID**)&pIB);
memcpy( pIndices, pIB, sizeof(WORD)*NumTriangles*3 );
pMesh->UnlockIndexBuffer();
NxTriangleMeshDesc TriMeshDesc;
TriMeshDesc.numVertices = NumVerticies;
TriMeshDesc.numTriangles = NumTriangles;
TriMeshDesc.pointStrideBytes = 3 * sizeof(float);
TriMeshDesc.triangleStrideBytes = 3 * sizeof(WORD);
TriMeshDesc.points = verts;
TriMeshDesc.triangles = pIndices;
TriMeshDesc.flags = NX_MF_16_BIT_INDICES;
// 메모리 버퍼에 메시를 쿠킹
MemoryWriteBuffer buf;
bool status = NxCookTriangleMesh(TriMeshDesc, buf);
if( !status )
{
MessageBox( 0, L"PhysX cooking failed!", 0, 0 );
if( verts )
delete[] verts;
if( pIndices )
delete[] pIndices;
return;
}
// 기존 메쉬와 액터를 삭제한다
NxActor* pActor = pObj->GetActor();
NxTriangleMesh* pActorMesh = pObj->GetActorMesh();
if( pActor ) pObj->GetParentCube()->GetScene()->releaseActor( *pActor );
if( pActorMesh ) m_pPhysXSDK->releaseTriangleMesh( *pActorMesh );
pActorMesh = m_pPhysXSDK->createTriangleMesh(MemoryReadBuffer(buf.data));
NxTriangleMeshShapeDesc ShapeDesc;
// 바디 설정
NxBodyDesc bodyDesc;
bodyDesc.angularDamping = 0.5f;
bodyDesc.maxAngularVelocity = 1.f;
bodyDesc.linearVelocity = NxVec3(0,0,0);
// 액터 설정
NxActorDesc actorDesc;
ShapeDesc.meshData = pActorMesh;
actorDesc.shapes.pushBack(&ShapeDesc);
actorDesc.body = &bodyDesc;
actorDesc.density = 50.0f;
if( bScaling )
actorDesc.globalPose = pObj->GetPose();
else
actorDesc.globalPose.t = NxVec3( pObj->GetPose().t.x, pObj->GetPose().t.y, 0 );
// TriangleMesh 액터 생성
pObj->SetActor( pActor = pObj->GetParentCube()->GetScene()->createActor(actorDesc) );
pActor->userData = (VOID*)this;
pActor->setMass( maxX * maxY * maxZ );
if( verts ) delete[] verts;
if( pIndices ) delete[] pIndices;
buf.clear();
}
/*************************************************************************************************************************************************************/
/* 피직스 UserNotify를 위한 클래스 */
/*************************************************************************************************************************************************************/
CtPhysXUserNotify::CtPhysXUserNotify( void )
{
}
CtPhysXUserNotify::~CtPhysXUserNotify( void )
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief PhysX 객체 sleep 이벤트 핸들러
sleep 모드로 진입하는 객체가 있을 경우 발생하는 이벤트 핸들러 함수이다. CtObjectBase::OnSleep 함수로 연결시킨다
* \param **actors sleep 되는 액터들의 배열
* \param count 액터들의 수(배열 크기)
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID
CtPhysXUserNotify::onSleep( NxActor **actors, NxU32 count )
{
CtObjectBase* pObj;
for( int i=0; i < count; i++ )
((CtObjectBase*)actors[i]->userData)->OnSleep();
}
/*************************************************************************************************************************************************************/
/* 피직스 UserContactReport를 위한 클래스 */
/*************************************************************************************************************************************************************/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 객체 간 충돌 이벤트 발생시 호출되는 함수이다.
이 함수를 사용하여 다양한 충돌 이벤트 발생시에 UI의 기능으로 활용할 수 있다.(ex: 클립보드에 충돌->클립보드 추가, Pile에 충돌->Pile에 추가 등)
* \param pair contact pair 객체. 충돌한 액터 및 기타 정보를 가진다
* \param events 발생 이벤트 정보. 터치 시작인지 중인지 끝인지 여부와 threshold 값등을 알려줌. SDK참고.
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID
CtPhysXContactReport::onContactNotify( NxContactPair& pair, NxU32 events )
{
CtObjectBase* pObj1 = (CtObjectBase*)pair.actors[0]->userData;
CtObjectBase* pObj2 = (CtObjectBase*)pair.actors[1]->userData;
//////////////////////////////////////////////////////////////////////////
// Pile과 칩 객체의 충돌시
//////////////////////////////////////////////////////////////////////////
if( !pObj1 || !pObj2 ) return;//|| pair.sumNormalForce.magnitude() < CONTACT_FORCE_THRESHOLD_ADDCHIP_TO_PILE ) return;
bool bPile1, bPile2;
bPile1 = pObj1->IsPiled();
bPile2 = pObj2->IsPiled();
// 둘중 하나만 piled인 경우만 해당
if( pObj1->IsChip() && pObj2->IsChip() && (bPile1 ^ bPile2) )
{
CtObjectChip* pPile = bPile1 ? (CtObjectChip*)pObj1 : (CtObjectChip*)pObj2;
CtObjectChip* pChip = bPile1 ? (CtObjectChip*)pObj2 : (CtObjectChip*)pObj1;
if( !pChip->IsForced() ) return;
NxMat34 matPose;
NxActor* pActor1;
NxActor* pActor2 = pChip->GetActor();
while( pPile->GetNext() )
pPile = pPile->GetNext();
pActor1 = pPile->GetActor();
// 포인터 연결 및 기타 설정
pChip->SetPileJointNext( NULL );
pPile->SetBoundaryOfPile( FALSE );
pChip->SetBoundaryOfPile( TRUE );
pChip->SetPileOrder( pPile->GetPileOrder() + 1 );
//////////////////////////////////////////////////////////////////////////
// 타겟 포즈를 구한다
//////////////////////////////////////////////////////////////////////////
matPose = pActor1->getGlobalPose();
NxVec3 vUp = matPose.M.getColumn( 1 );
vUp.normalize();
D3DXVECTOR3 vScale1 = pPile->GetScale();
D3DXVECTOR3 vScale2 = pChip->GetScale();
vUp *= ( (CHIP_THICKNESS * vScale1.z) / 2.f ) + ( (CHIP_THICKNESS * vScale2.z) / 2.f);
matPose.t += vUp;
pChip->SetCollisionGroup( ACTOR_GROUP_BREAKINGCHIP );
pActor2->raiseActorFlag( NX_AF_DISABLE_COLLISION );
pChip->RaiseStateFlag( OBJECT_STATE_PILED );
pChip->SetPoseTransition( matPose, pChip->GetScale(), 0.6f, 0.8f );
pChip->SetPrev( pPile );
pChip->SetNext( NULL );
pPile->SetNext( pChip );
pPile->GetActor()->setLinearVelocity( NxVec3(0,0,0) );
GetCTmain()->m_stStateFlags.bPilingAddModeDone = TRUE;
}
// 큐브에 충돌시
bool bCube1 = pObj1->IsCube();
bool bCube2 = pObj2->IsCube();
if( bCube1 || bCube2 )
{
CtObjectCube* pCube = bCube1 ? (CtObjectCube*)pObj1 : (CtObjectCube*)pObj2;
CtObjectChip* pChip = bCube1 ? (CtObjectChip*)pObj2 : (CtObjectChip*)pObj1;
if( !pChip->IsForced() ) return;
// 파일을 이동
CString newPath = pCube->GetFilePath();
newPath += L"\\" + pChip->GetFileInfo()->lpszFileName;
MoveFile( pChip->GetFilePath(), newPath );
// 현재 큐브에서 해당 큐브로 객체 이동
GetCTmain()->MoveObject( pChip, GetCTmain()->m_pCurrentCube, pCube );
pCube->GetActor()->setLinearVelocity( NxVec3(0,0,0) );
}
} | 34.277512 | 159 | 0.490717 | ca1773130n |
22956c2e81ae51d0c6242c8b621d1af1d84506f4 | 3,022 | cpp | C++ | Source/ThirdParty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp | vinhig/rbfx | 884de45c623d591f346a2abd5e52edaa84bcc137 | [
"MIT"
] | 441 | 2018-12-26T14:50:23.000Z | 2021-11-05T03:13:27.000Z | Source/ThirdParty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp | vinhig/rbfx | 884de45c623d591f346a2abd5e52edaa84bcc137 | [
"MIT"
] | 221 | 2018-12-29T17:40:23.000Z | 2021-11-06T21:41:55.000Z | Source/ThirdParty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp | vinhig/rbfx | 884de45c623d591f346a2abd5e52edaa84bcc137 | [
"MIT"
] | 101 | 2018-12-29T13:08:10.000Z | 2021-11-02T09:58:37.000Z | // Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "bvh_intersector_stream.cpp"
namespace embree
{
namespace isa
{
////////////////////////////////////////////////////////////////////////////////
/// General BVHIntersectorStreamPacketFallback Intersector
////////////////////////////////////////////////////////////////////////////////
DEFINE_INTERSECTORN(BVH4IntersectorStreamPacketFallback,BVHNIntersectorStreamPacketFallback<SIMD_MODE(4)>);
////////////////////////////////////////////////////////////////////////////////
/// BVH4IntersectorStream Definitions
////////////////////////////////////////////////////////////////////////////////
IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4iIntersectorStreamMoeller, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Triangle4iIntersectorStreamMoeller<true>>));
IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4vIntersectorStreamPluecker, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA true COMMA Triangle4vIntersectorStreamPluecker<true>>));
IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4iIntersectorStreamPluecker, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA true COMMA Triangle4iIntersectorStreamPluecker<true>>));
IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4IntersectorStreamMoeller, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Triangle4IntersectorStreamMoeller<true>>));
IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4IntersectorStreamMoellerNoFilter, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Triangle4IntersectorStreamMoeller<false>>));
IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamMoeller, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Quad4vIntersectorStreamMoeller<true>>));
IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamMoellerNoFilter,BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Quad4vIntersectorStreamMoeller<false>>));
IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4iIntersectorStreamMoeller, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA Quad4iIntersectorStreamMoeller<true>>));
IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamPluecker, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA true COMMA Quad4vIntersectorStreamPluecker<true>>));
IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4iIntersectorStreamPluecker, BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA true COMMA Quad4iIntersectorStreamPluecker<true>>));
IF_ENABLED_USER(DEFINE_INTERSECTORN(BVH4VirtualIntersectorStream,BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA ObjectIntersectorStream>));
IF_ENABLED_INSTANCE(DEFINE_INTERSECTORN(BVH4InstanceIntersectorStream,BVHNIntersectorStream<SIMD_MODE(4) COMMA BVH_AN1 COMMA false COMMA InstanceIntersectorStream>));
}
}
| 81.675676 | 199 | 0.747849 | vinhig |
2296489d805f3296218ed09ab0eef7438d470912 | 1,181 | hpp | C++ | include/NGGMergeOperator.hpp | NikolasGialitsis/NGramGraphParallel | 26427e7ff39ba591a8c7eedd0ace458f1821a876 | [
"Apache-2.0"
] | 1 | 2021-09-17T08:51:55.000Z | 2021-09-17T08:51:55.000Z | include/NGGMergeOperator.hpp | NikolasGialitsis/NGramGraphParallel | 26427e7ff39ba591a8c7eedd0ace458f1821a876 | [
"Apache-2.0"
] | 1 | 2021-05-24T10:36:50.000Z | 2021-05-24T10:36:50.000Z | include/NGGMergeOperator.hpp | NikolasGialitsis/NGramGraphParallel | 26427e7ff39ba591a8c7eedd0ace458f1821a876 | [
"Apache-2.0"
] | 1 | 2021-05-09T16:00:52.000Z | 2021-05-09T16:00:52.000Z | #ifndef NGGMERGEOPERATOR_H
#define NGGMERGEOPERATOR_H
#include "BinaryOperator.hpp"
#include "NGGUpdateOperator.hpp"
#include "NGramGraph.hpp"
//TODO Add an NGGUpdateOperator object as a member field, and set it's operands in the apply().
/*
* \class Implements the merge operator for NGramGraph objects.
* The operator doesn't alter it's operands, but creates a new NGramGraph object to hold the result.
*/
class NGGMergeOperator : public BinaryOperator<NGramGraph, NGramGraph> {
public:
/*
* Constructor
* \param operand1 Pointer to the first NGramGraph operand.
* \param operand2 Pointer to the second NGramGraph operand.
*/
NGGMergeOperator(NGramGraph *operand1, NGramGraph *operand2) : BinaryOperator(operand1, operand2) {}
/*
* Implementation of the merge operator.
* \return The new merged NGramGraph object.
*/
NGramGraph apply() override;
private:
/*
* Utility function to find the small and the big graph among the operands w.r.t. the number of edges.
* \return A pair of NGramGraph pointers, in ascending order w.r.t. number of edges.
*/
std::pair<NGramGraph *, NGramGraph *> findSmallAndBigGraphs();
};
#endif // NGGMERGEOPERATOR_H
| 29.525 | 103 | 0.748518 | NikolasGialitsis |
229a78f7772aecb1f99d4f1a67c4c40bba56a308 | 2,610 | cpp | C++ | src/InputFileParser/AuxDataParser.cpp | dgoldri25/WaterPaths | 08f098e5f8baf93bc25098aa450650a4632c7eb6 | [
"Apache-2.0"
] | 11 | 2018-07-30T01:47:55.000Z | 2021-07-28T22:17:07.000Z | src/InputFileParser/AuxDataParser.cpp | bernardoct/RevampedTriangleModel | 122116eb5b32efd35f4212f09511cd68528462be | [
"Apache-2.0"
] | 26 | 2018-06-26T15:48:20.000Z | 2021-01-12T15:48:59.000Z | src/InputFileParser/AuxDataParser.cpp | bernardoct/RevampedTriangleModel | 122116eb5b32efd35f4212f09511cd68528462be | [
"Apache-2.0"
] | 9 | 2018-12-08T02:47:39.000Z | 2021-07-26T15:34:22.000Z | //
// Created by bernardo on 11/27/19.
//
#include <algorithm>
#include "AuxDataParser.h"
#include "../Utils/Utils.h"
#include "AuxParserFunctions.h"
vector<vector<int>> AuxDataParser::parseReservoirUtilityConnectivityMatrix(
vector<vector<string>> &block, const map<string, int> &ws_name_to_id,
const map<string, int> &utility_name_to_id, const string &tag, int l) {
for (auto line : block) {
AuxParserFunctions::replaceNameById(block, tag, l, line[0], 1,
ws_name_to_id);
AuxParserFunctions::replaceNameById(block, tag, l, line[0], 0,
utility_name_to_id);
}
vector<vector<int>> reservoir_utility_connectivity_matrix(block.size());
for (auto &line : block) {
vector<int> utilitys_sources;
Utils::tokenizeString(line[1], utilitys_sources, ',');
reservoir_utility_connectivity_matrix[stoi(line[0])] = utilitys_sources;
}
return reservoir_utility_connectivity_matrix;
}
vector<vector<double>>
AuxDataParser::tableStorageShiftParser(vector<vector<string>> &block,
const map<string, int> &ws_name_to_id,
const map<string, int> &utility_name_to_id,
const string &tag, int l) {
for (vector<string> &line : block) {
try {
line[0] = to_string(utility_name_to_id.at(line[0]));
line[1] = to_string(ws_name_to_id.at(line[1]));
} catch (const std::out_of_range &e) {
char error[500];
sprintf(error,
"Wrong name in %s in line %d. Are either %s or %s mispelled "
"in either in storage shift table or in utility/water "
"source?", tag.c_str(), l, line[0].c_str(), line[1].c_str()
);
throw invalid_argument(error);
}
}
try {
vector<vector<double>> table_storage_shift(
AuxParserFunctions::getMax(utility_name_to_id).second + 1,
vector<double>(
AuxParserFunctions::getMax(ws_name_to_id).second + 1,
0));
for (auto line : block) {
vector<int> v = {stoi(line[0]), stoi(line[1])};
table_storage_shift[v[0]][v[1]] = stod(line[2]);
}
return table_storage_shift;
} catch (...) {
char error[128];
sprintf(error, "Something is wrong with %s in line %d", tag.c_str(), l);
throw invalid_argument(error);
}
} | 37.285714 | 82 | 0.560536 | dgoldri25 |
229ac60f794443c7a788c4501ceb9f18de1e7ff9 | 8,201 | cc | C++ | gen_secondary_antiproton_source.cc | bjbuckman/galprop_bb_ | 076b168f7475b3ba9fb198b6ec2df7be66b1763c | [
"MIT"
] | null | null | null | gen_secondary_antiproton_source.cc | bjbuckman/galprop_bb_ | 076b168f7475b3ba9fb198b6ec2df7be66b1763c | [
"MIT"
] | null | null | null | gen_secondary_antiproton_source.cc | bjbuckman/galprop_bb_ | 076b168f7475b3ba9fb198b6ec2df7be66b1763c | [
"MIT"
] | null | null | null |
//**.****|****.****|****.****|****.****|****.****|****.****|****.****|****.****|
// * gen_secondary_antiproton_source.cc * galprop package * 2001/05/11
//**"****!****"****!****"****!****"****!****"****!****"****!****"****!****"****|
//**"****!****"****!****"****!****"****!****"****!****"****!****"****!****"****|
// The routine to calculate the antiproton source function.
//
// CR density gcr.cr_density is in c/4pi * n(E) [cm s^-1 sr^-1 cm^-3 MeV^-1]
//
// The routine ANTIPROTON written in FORTRAN-77 is designed to calculate
// the antiproton (+antineutron) production spectrum vs. momentum (barn/GeV).
// Antiproton momentum and nucleus momentum (GeV) per nucleon are used as input
// parameters as well as beam and target nuclei atomic numbers.
//
// The antiproton source function [cm^-2 s^-2 sr^-1 MeV^-1] as used in galprop is
// defined as following (c/4pi * q) [q = cm^-3 s^-1 MeV^-1]:
// ___ ___
// c \ \ / c d sigma_ij(p,p')
// q(p) * --- = c /__ n_i /__ \ dp' beta n_j(p') --- --------------- ,
// 4pi i=H,He j / 4pi dp
//
// where n_i is the gas density, d sigma_ij(p,p')/dp is
// the production cross section, n_j(p') is the CR species density,
// and p' is the total momentum of a nucleus.
// Substitution of dp' with d(log Ekin) gives:
// ___ ___
// c \ / \ c d sigma_ij(p,Ekin)
// q(p)*--- = c A /__ n_i \ d(log Ekin) Ekin /__ n_j(Ekin) --- -----------------
// 4pi i=H,He / j 4pi dp
// ___ ___ ___
// \ \ \ c d sigma_ij(p,Ekin)
// = c A /\(log Ekin) /__ n_i /__ Ekin /__ n_j(Ekin) --- -----------------,
// i=H,He Ekin j 4pi dp
//
// where /\=Delta, and we used dp'=1/beta A Ekin d(log Ekin).
//
// To transfer to units cm^2/MeV we need a factor= 1.0e-24 *1.0e-3.
// Ref.: Moskalenko I.V. et al. 2002, ApJ 565, 280
//=="====!===="====!===="====!===="====!===="====!===="====!===="====!===="====!
using namespace std;//AWS20050624
#include"galprop_classes.h"
#include"galprop_internal.h"
#include <fort_interface.h>
#include <cstring>
//**.****|****.****|****.****|****.****|****.****|****.****|****.****|****.****|
int Galprop::gen_secondary_antiproton_source(Particle &particle)
{
if(galdef.verbose>=1) cout<<"gen_secondary_antiproton_source"<<endl;
if(galdef.verbose>=1) cout<<"generating "<<particle.name<<" source function for n_spatial_dimensions="
<<gcr[0].n_spatial_dimensions<<endl;
if(strcmp(particle.name,"secondary_antiprotons")!=0) {
cout<<"invalid particle "<<particle.name<<endl;
return 2;
}
int stat=0, iprotons=-1, iHelium =-1, Z1, A1, Z2, A2;
float cs_p_HI, cs_p_He, cs_He_HI, cs_He_He;
Distribution protons; // IMOS20000606.6
// identify CR protons // IMOS20000606.7
if(galdef.n_spatial_dimensions==2) protons.init(gcr[0].n_rgrid, gcr[0].n_zgrid, gcr[0].n_pgrid);
if(galdef.n_spatial_dimensions==3) protons.init(gcr[0].n_xgrid, gcr[0].n_ygrid, gcr[0].n_zgrid, gcr[0].n_pgrid);
protons=0.;
for(int i=0; i<n_species; i++)
if(101==100*gcr[i].Z+gcr[i].A) {
iprotons=i;
protons+=gcr[iprotons].cr_density;
if(galdef.verbose>=1) cout<<" CR protons found as species #"<<iprotons<<endl;
}
if(iprotons==-1) {
cout<<"CR protons not found!"<<endl;
return 1;
}
// identify CR Helium
for(int i=0; i<n_species; i++) if(204 == 100*gcr[i].Z+gcr[i].A) iHelium =i;
if(iHelium ==-1) {
cout<<"CR Helium not found!"<<endl;
return 1;
} else if(galdef.verbose>=1) cout<<" CR Helium found as species #"<<iHelium <<endl;
//Gulli20070821
#pragma omp parallel for schedule(dynamic) default(shared) private(Z1,Z2,A1,A2,cs_p_HI,cs_He_HI,cs_p_He,cs_He_He)
for(int ip_sec=0; ip_sec<particle.n_pgrid; ip_sec++) {
for(int ip=0; ip<gcr[iprotons].n_pgrid; ip++) {
Z1=gcr[iprotons].Z;
A1=gcr[iprotons].A;
Z2=1;
A2=1; // beam+target: p+HI
cs_p_HI =antiproton_cc(galdef.total_cross_section,particle.p[ip_sec]*1.e-3, gcr[iprotons].p[ip]*1.e-3, Z1,A1,Z2,A2); // IMOS20010511 IMOS20000601
// secondary_antiprotons =1 uses scaling to calc.; =2 uses factors by Simon et al. 1998
if(galdef.secondary_antiprotons == 2) { // IMOS20000802.2
cs_p_HI*=0.12/pow(particle.Ekin[ip_sec]/1000,1.67)+1.78;
cs_He_HI = cs_p_He = cs_He_He = 0.;
} else {
Z1=gcr[iprotons].Z;
A1=gcr[iprotons].A;
Z2=2;
A2=4; // beam+target: p+He
cs_p_He =antiproton_cc(galdef.total_cross_section,particle.p[ip_sec]*1.e-3, gcr[iprotons].p[ip]*1.e-3, Z1,A1,Z2,A2); // IMOS20010511 IMOS20000601
Z1=gcr[iHelium ].Z;
A1=gcr[iHelium ].A;
Z2=1;
A2=1; // beam+target: He+HI
cs_He_HI=antiproton_cc(galdef.total_cross_section,particle.p[ip_sec]*1.e-3, gcr[iHelium ].p[ip]*1.e-3, Z1,A1,Z2,A2); // IMOS20010511 IMOS20000601
Z1=gcr[iHelium ].Z;
A1=gcr[iHelium ].A;
Z2=2;
A2=4; // beam+target: He+He
cs_He_He=antiproton_cc(galdef.total_cross_section,particle.p[ip_sec]*1.e-3, gcr[iHelium ].p[ip]*1.e-3, Z1,A1,Z2,A2); // IMOS20010511 IMOS20000601
}
if(galaxy.n_spatial_dimensions==2) {
for(int ir=0; ir<gcr[iprotons].n_rgrid; ir++) {
for(int iz=0; iz<gcr[iprotons].n_zgrid; iz++) {
particle.secondary_source_function.d2[ir][iz].s[ip_sec ]+=
(galaxy.n_HI.d2[ir][iz].s[0]+2.0*galaxy.n_H2.d2[ir][iz].s[0]+galaxy.n_HII.d2[ir][iz].s[0])
*( (cs_p_HI +cs_p_He *galdef.He_H_ratio)
*protons.d2[ir][iz].s[ip] *gcr[iprotons].Ekin[ip] // IMOS20000606.8
+(cs_He_HI +cs_He_He*galdef.He_H_ratio)
*gcr[iHelium ].cr_density.d2[ir][iz].s[ip] *gcr[iHelium ].Ekin[ip] *gcr[iHelium].A );
} // iz
} // ir
} // particle.n_spatial_dimensions==2
if(galaxy.n_spatial_dimensions==3) {
for(int ix=0; ix<gcr[iprotons].n_xgrid; ix++) {
for(int iy=0; iy<gcr[iprotons].n_ygrid; iy++) {
for(int iz=0; iz<gcr[iprotons].n_zgrid; iz++) {
particle.secondary_source_function.d3[ix][iy][iz].s[ip_sec ]+=
(galaxy.n_HI.d3[ix][iy][iz].s[0]+2.0*galaxy.n_H2.d3[ix][iy][iz].s[0]+galaxy.n_HII.d3[ix][iy][iz].s[0])
*( (cs_p_HI +cs_p_He *galdef.He_H_ratio)
*protons.d3[ix][iy][iz].s[ip] *gcr[iprotons].Ekin[ip] // IMOS20000606.9
+(cs_He_HI +cs_He_He*galdef.He_H_ratio)
*gcr[iHelium ].cr_density.d3[ix][iy][iz].s[ip] *gcr[iHelium ].Ekin[ip] *gcr[iHelium].A );
} // iz
} // iy
} // ix
} // particle.n_spatial_dimensions==3
} // ip
} // ip_sec
double factor=1.e-24 *1.e-3 *C *log(galdef.Ekin_factor); // transformation to cm2/MeV and constant factors
particle.secondary_source_function *= factor;
protons.delete_array(); // IMOS20000606.10
if(galdef.verbose>=2) {
cout<<" particle.secondary_source_function for "<<particle.name<<endl;
particle.secondary_source_function.print();
}
if(galdef.verbose>=1) cout<<" <<<< gen_secondary_antiproton_source"<<endl;
return stat;
}
| 50.006098 | 161 | 0.501524 | bjbuckman |
229bd1555a21376df233101267fa45a6458335b0 | 742 | hpp | C++ | boost/sequence/traits/size_type.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 11 | 2015-02-21T11:23:44.000Z | 2021-08-15T03:39:29.000Z | boost/sequence/traits/size_type.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | null | null | null | boost/sequence/traits/size_type.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 3 | 2015-05-09T02:25:42.000Z | 2019-11-02T13:39:29.000Z | // Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_SEQUENCE_TRAITS_SIZE_TYPE_DWA200658_HPP
# define BOOST_SEQUENCE_TRAITS_SIZE_TYPE_DWA200658_HPP
# include <boost/utility/result_of.hpp>
# include <boost/sequence/size.hpp>
# include <boost/type_traits/add_reference.hpp>
namespace boost { namespace sequence { namespace traits {
// Don't specialize this.
template<typename S>
struct size_type
: result_of<
op::size(typename add_reference<S>::type)
>
{};
}}} // namespace boost::sequence::traits
#endif // BOOST_SEQUENCE_TRAITS_SIZE_TYPE_DWA200658_HPP
| 30.916667 | 73 | 0.752022 | ericniebler |
229e2ab063f6b8b391d4ea89f759e538bc49d474 | 2,823 | hpp | C++ | src/libs/io/binary_output_stream.hpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/libs/io/binary_output_stream.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/libs/io/binary_output_stream.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #pragma once
#include <type_traits>
#include <string>
#include "output_stream.hpp"
#include "utility/service_registry.hpp"
#include "utility/time.hpp"
#include "utility/flag_set.hpp"
namespace gorc {
class binary_output_stream : public output_stream {
private:
output_stream &stream;
public:
service_registry const &services;
explicit binary_output_stream(output_stream &stream);
binary_output_stream(output_stream &stream, service_registry const &services);
template <typename T>
typename std::enable_if<std::is_fundamental<T>::value, void>::type write_value(T &out)
{
stream.write(&out, sizeof(T));
}
void write_string(std::string const &str);
virtual size_t write_some(void const *src, size_t size) override;
};
template <typename T>
typename std::enable_if<std::is_fundamental<T>::value, void>::type
binary_serialize(binary_output_stream &os, T const &value)
{
os.write_value(value);
}
template <typename T>
typename std::enable_if<std::is_same<std::string, T>::value, void>::type
binary_serialize(binary_output_stream &os, T const &value)
{
os.write_string(value);
}
template <typename T>
auto binary_serialize(binary_output_stream &os, T const &value)
-> typename std::conditional<true, void, decltype(value.binary_serialize_object(os))>::type
{
value.binary_serialize_object(os);
}
template <typename T>
typename std::enable_if<std::is_enum<T>::value, void>::type
binary_serialize(binary_output_stream &os, T const &value)
{
binary_serialize(os, static_cast<typename std::underlying_type<T>::type>(value));
}
template <typename T>
typename std::enable_if<std::is_same<time_delta, T>::value, void>::type
binary_serialize(binary_output_stream &os, T const &value)
{
binary_serialize<double>(os, value.count());
}
template <typename U>
typename std::enable_if<std::is_enum<U>::value, void>::type
binary_serialize(binary_output_stream &os, flag_set<U> const &value)
{
binary_serialize(os, static_cast<U>(value));
}
template <typename RangeT, typename FmtFnT>
void binary_serialize_range(binary_output_stream &os,
RangeT const &rng,
FmtFnT fn)
{
binary_serialize<size_t>(os, rng.size());
for(auto const &em : rng) {
fn(os, em);
}
}
template <typename RangeT>
void binary_serialize_range(binary_output_stream &os, RangeT const &rng)
{
binary_serialize<size_t>(os, rng.size());
for(auto const &em : rng) {
binary_serialize(os, em);
}
}
}
| 29.40625 | 99 | 0.639391 | jdmclark |
22a1e69931c23ffe346ef76c330301268dc9137c | 669 | hpp | C++ | asyncnet.hpp | Chingyat/asyncnet | e012b64fcf38c9fba15dee52e467d98772926b81 | [
"MIT"
] | null | null | null | asyncnet.hpp | Chingyat/asyncnet | e012b64fcf38c9fba15dee52e467d98772926b81 | [
"MIT"
] | null | null | null | asyncnet.hpp | Chingyat/asyncnet | e012b64fcf38c9fba15dee52e467d98772926b81 | [
"MIT"
] | 1 | 2020-11-10T05:33:25.000Z | 2020-11-10T05:33:25.000Z | //
// Created by lince on 11/6/20.
//
#ifndef ASYNCNET_HPP
#define ASYNCNET_HPP
#include <asyncnet/associated_allocator.hpp>
#include <asyncnet/associated_executor.hpp>
#include <asyncnet/async_completion.hpp>
#include <asyncnet/async_result.hpp>
#include <asyncnet/defer.hpp>
#include <asyncnet/dispatch.hpp>
#include <asyncnet/execution_context.hpp>
#include <asyncnet/executor.hpp>
#include <asyncnet/executor_binder.hpp>
#include <asyncnet/executor_work_guard.hpp>
#include <asyncnet/io_context.hpp>
#include <asyncnet/post.hpp>
#include <asyncnet/service.hpp>
#include <asyncnet/system_context.hpp>
#include <asyncnet/system_executor.hpp>
#endif// ASYNCNET_HPP
| 26.76 | 44 | 0.796712 | Chingyat |
22a2e0e92f47a335804837d759948e065ca53ce0 | 3,707 | cpp | C++ | blast/src/objtools/readers/message_listener.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/readers/message_listener.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/readers/message_listener.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /*
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Michael Kornbluh
*
* File Description:
* Classes for listening to errors, progress, etc.
*
*/
#include <ncbi_pch.hpp>
#include <objtools/readers/message_listener.hpp>
#include <objtools/readers/reader_error_codes.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects) // namespace ncbi::objects::
void
CMessageListenerBase::PutProgress(
const string & sMessage,
const Uint8 iNumDone,
const Uint8 iNumTotal)
{
// NB: Some other classes rely on the message fitting in one line.
// NB: New attributes or inner elements could be added to the resulting
// message at any time, so make no assumptions.
if( ! m_pProgressOstrm ) {
// no stream to write to
return;
}
*m_pProgressOstrm << "<message severity=\"INFO\" ";
if( iNumDone > 0 ) {
*m_pProgressOstrm << "num_done=\"" << iNumDone << "\" ";
}
if( iNumTotal > 0 ) {
*m_pProgressOstrm << "num_total=\"" << iNumTotal << "\" ";
}
if( sMessage.empty() ) {
*m_pProgressOstrm << " />";
} else {
*m_pProgressOstrm << " >";
string sXMLEncodedMessage = NStr::XmlEncode(sMessage);
// some functionality relies on progress messages fitting into
// one line, so we escape newlines (just in case) while
// we write it.
ITERATE( string, msg_it, sXMLEncodedMessage ) {
const char ch = *msg_it;
switch(ch) {
case '\r':
*m_pProgressOstrm << "
";
break;
case '\n':
*m_pProgressOstrm << "
";
break;
default:
*m_pProgressOstrm << ch;
break;
}
}
*m_pProgressOstrm << "</message>" << NcbiEndl;
}
m_pProgressOstrm->flush();
}
CGPipeMessageListener::CGPipeMessageListener(bool ignoreBadModValue)
: m_IgnoreBadModValue(ignoreBadModValue) {}
bool CGPipeMessageListener::PutError(const ILineError& error) {
const auto severity = error.GetSeverity();
if (severity == eDiag_Info) {
return true;
}
if (severity == eDiag_Warning) {
ERR_POST(Warning << error.Message());
return true;
}
return ((error.GetCode() == EReaderCode::eReader_Mods) &&
(error.GetSubCode() != EModSubcode::eModSubcode_InvalidValue ||
m_IgnoreBadModValue));
}
END_SCOPE(objects)
END_NCBI_SCOPE
| 29.420635 | 78 | 0.604532 | mycolab |
22a3a012de375dda73818b93c8777d79f20248d9 | 10,125 | cpp | C++ | CrystalCavern/Plugins/VRM4U/Source/VRM4U/Private/VrmUtil.cpp | NikkoBertoa/test | 6e27eb89ae8fddb41535a73617704cb1c8f6e125 | [
"Apache-2.0"
] | null | null | null | CrystalCavern/Plugins/VRM4U/Source/VRM4U/Private/VrmUtil.cpp | NikkoBertoa/test | 6e27eb89ae8fddb41535a73617704cb1c8f6e125 | [
"Apache-2.0"
] | null | null | null | CrystalCavern/Plugins/VRM4U/Source/VRM4U/Private/VrmUtil.cpp | NikkoBertoa/test | 6e27eb89ae8fddb41535a73617704cb1c8f6e125 | [
"Apache-2.0"
] | null | null | null | // VRM4U Copyright (c) 2019 Haruyoshi Yamamoto. This software is released under the MIT License.
#pragma once
#include "VrmUtil.h"
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
void FImportOptionData::init() {
}
const TArray<VRMUtil::VRMBoneTable> VRMUtil::table_ue4_vrm = {
{"Root",""},
{"Pelvis","hips"},
{"spine_01","spine"},
{"spine_02","chest"},
{"spine_03","upperChest"},
{"clavicle_l","leftShoulder"},
{"UpperArm_L","leftUpperArm"},
{"lowerarm_l","leftLowerArm"},
{"Hand_L","leftHand"},
{"index_01_l","leftIndexProximal"},
{"index_02_l","leftIndexIntermediate"},
{"index_03_l","leftIndexDistal"},
{"middle_01_l","leftMiddleProximal"},
{"middle_02_l","leftMiddleIntermediate"},
{"middle_03_l","leftMiddleDistal"},
{"pinky_01_l","leftLittleProximal"},
{"pinky_02_l","leftLittleIntermediate"},
{"pinky_03_l","leftLittleDistal"},
{"ring_01_l","leftRingProximal"},
{"ring_02_l","leftRingIntermediate"},
{"ring_03_l","leftRingDistal"},
{"thumb_01_l","leftThumbProximal"},
{"thumb_02_l","leftThumbIntermediate"},
{"thumb_03_l","leftThumbDistal"},
{"lowerarm_twist_01_l",""},
{"upperarm_twist_01_l",""},
{"clavicle_r","rightShoulder"},
{"UpperArm_R","rightUpperArm"},
{"lowerarm_r","rightLowerArm"},
{"Hand_R","rightHand"},
{"index_01_r","rightIndexProximal"},
{"index_02_r","rightIndexIntermediate"},
{"index_03_r","rightIndexDistal"},
{"middle_01_r","rightMiddleProximal"},
{"middle_02_r","rightMiddleIntermediate"},
{"middle_03_r","rightMiddleDistal"},
{"pinky_01_r","rightLittleProximal"},
{"pinky_02_r","rightLittleIntermediate"},
{"pinky_03_r","rightLittleDistal"},
{"ring_01_r","rightRingProximal"},
{"ring_02_r","rightRingIntermediate"},
{"ring_03_r","rightRingDistal"},
{"thumb_01_r","rightThumbProximal"},
{"thumb_02_r","rightThumbIntermediate"},
{"thumb_03_r","rightThumbDistal"},
{"lowerarm_twist_01_r",""},
{"upperarm_twist_01_r",""},
{"neck_01","neck"},
{"head","head"},
{"Thigh_L","leftUpperLeg"},
{"calf_l","leftLowerLeg"},
{"calf_twist_01_l",""},
{"Foot_L","leftFoot"},
{"ball_l","leftToes"},
{"thigh_twist_01_l",""},
{"Thigh_R","rightUpperLeg"},
{"calf_r","rightLowerLeg"},
{"calf_twist_01_r",""},
{"Foot_R","rightFoot"},
{"ball_r","rightToes"},
{"thigh_twist_01_r",""},
{"ik_foot_root",""},
{"ik_foot_l",""},
{"ik_foot_r",""},
{"ik_hand_root",""},
{"ik_hand_gun",""},
{"ik_hand_l",""},
{"ik_hand_r",""},
{"Custom_1",""},
{"Custom_2",""},
{"Custom_3",""},
{"Custom_4",""},
{"Custom_5",""},
};
const TArray<VRMUtil::VRMBoneTable> VRMUtil::table_ue4_pmx = {
{"Root",TEXT("全ての親")},
{"Pelvis",TEXT("センター")},
{"spine_01",TEXT("上半身")},
{"spine_02",TEXT("上半身")},
{"spine_03",TEXT("上半身2")},
{"clavicle_l",TEXT("左肩")},
{"UpperArm_L",TEXT("左腕")},
{"lowerarm_l",TEXT("左ひじ")},
{"Hand_L",TEXT("左手首")},
{"index_01_l",TEXT("左人指1")},
{"index_02_l",TEXT("左人指2")},
{"index_03_l",TEXT("左人指3")},
{"middle_01_l",TEXT("左中指1")},
{"middle_02_l",TEXT("左中指2")},
{"middle_03_l",TEXT("左中指3")},
{"pinky_01_l",TEXT("左小指1")},
{"pinky_02_l",TEXT("左小指2")},
{"pinky_03_l",TEXT("左小指3")},
{"ring_01_l",TEXT("左薬指1")},
{"ring_02_l",TEXT("左薬指2")},
{"ring_03_l",TEXT("左薬指3")},
{"thumb_01_l",TEXT("左親指1")},
{"thumb_02_l",TEXT("左親指1")},
{"thumb_03_l",TEXT("左親指2")},
{"lowerarm_twist_01_l",TEXT("")},
{"upperarm_twist_01_l",TEXT("")},
{"clavicle_r",TEXT("右肩")},
{"UpperArm_R",TEXT("右腕")},
{"lowerarm_r",TEXT("右ひじ")},
{"Hand_R",TEXT("右手首")},
{"index_01_r",TEXT("右人指1")},
{"index_02_r",TEXT("右人指2")},
{"index_03_r",TEXT("右人指3")},
{"middle_01_r",TEXT("右中指1")},
{"middle_02_r",TEXT("右中指2")},
{"middle_03_r",TEXT("右中指3")},
{"pinky_01_r",TEXT("右小指1")},
{"pinky_02_r",TEXT("右小指2")},
{"pinky_03_r",TEXT("右小指3")},
{"ring_01_r",TEXT("右薬指1")},
{"ring_02_r",TEXT("右薬指2")},
{"ring_03_r",TEXT("右薬指3")},
{"thumb_01_r",TEXT("右親指1")},
{"thumb_02_r",TEXT("右親指1")},
{"thumb_03_r",TEXT("右親指2")},
{"lowerarm_twist_01_r",TEXT("")},
{"upperarm_twist_01_r",TEXT("")},
{"neck_01",TEXT("首")},
{"head",TEXT("頭")},
{"Thigh_L",TEXT("左足")},
{"calf_l",TEXT("左ひざ")},
{"calf_twist_01_l",TEXT("")},
{"Foot_L",TEXT("左足首")},
{"ball_l",TEXT("左つま先")},
{"thigh_twist_01_l",TEXT("")},
{"Thigh_R",TEXT("右足")},
{"calf_r",TEXT("右ひざ")},
{"calf_twist_01_r",TEXT("")},
{"Foot_R",TEXT("右足首")},
{"ball_r",TEXT("右つま先")},
{"thigh_twist_01_r",TEXT("")},
{"ik_foot_root",TEXT("")},
{"ik_foot_l",TEXT("")},
{"ik_foot_r",TEXT("")},
{"ik_hand_root",TEXT("")},
{"ik_hand_gun",TEXT("")},
{"ik_hand_l",TEXT("")},
{"ik_hand_r",TEXT("")},
{"Custom_1",TEXT("")},
{"Custom_2",TEXT("")},
{"Custom_3",TEXT("")},
{"Custom_4",TEXT("")},
{"Custom_5",TEXT("")},
};
const TArray<FString> VRMUtil::vrm_humanoid_bone_list = {
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal",
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal",
"upperChest"
};
const TArray<FName> VRMUtil::vrm_humanoid_bone_list_name = {
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", // 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal",
"upperChest"
};
const TArray<FString> VRMUtil::vrm_humanoid_parent_list = {
"", //"hips",
"hips",//"leftUpperLeg",
"hips",//"rightUpperLeg",
"leftUpperLeg",//"leftLowerLeg",
"rightUpperLeg",//"rightLowerLeg",
"leftLowerLeg",//"leftFoot",
"rightLowerLeg",//"rightFoot",
"hips",//"spine",
"spine",//"chest",
"chest",//"neck",
"neck",//"head",
"chest",//"leftShoulder", // <-- upper..
"chest",//"rightShoulder",
"leftShoulder",//"leftUpperArm",
"rightShoulder",//"rightUpperArm",
"leftUpperArm",//"leftLowerArm",
"rightUpperArm",//"rightLowerArm",
"leftLowerArm",//"leftHand",
"rightLowerArm",//"rightHand",
"leftLowerLeg",//"leftToes",
"rightLowerLeg",//"rightToes",
"head",//"leftEye",
"head",//"rightEye",
"head",//"jaw",
"leftHand",//"leftThumbProximal",
"leftThumbProximal",//"leftThumbIntermediate",
"leftThumbIntermediate",//"leftThumbDistal",
"leftHand",//"leftIndexProximal",
"leftIndexProximal",//"leftIndexIntermediate",
"leftIndexIntermediate",//"leftIndexDistal",
"leftHand",//"leftMiddleProximal",
"leftMiddleProximal",//"leftMiddleIntermediate",
"leftMiddleIntermediate",//"leftMiddleDistal",
"leftHand",//"leftRingProximal",
"leftRingProximal",//"leftRingIntermediate",
"leftRingIntermediate",//"leftRingDistal",
"leftHand",//"leftLittleProximal",
"leftLittleProximal",//"leftLittleIntermediate",
"leftLittleIntermediate",//"leftLittleDistal",
"rightHand",//"rightThumbProximal",
"rightThumbProximal",//"rightThumbIntermediate",
"rightThumbIntermediate",//"rightThumbDistal",
"rightHand",//"rightIndexProximal",
"rightIndexProximal",//"rightIndexIntermediate",
"rightIndexIntermediate",//"rightIndexDistal",
"rightHand",//"rightMiddleProximal",
"rightMiddleProximal",//"rightMiddleIntermediate",
"rightMiddleIntermediate",//"rightMiddleDistal",
"rightHand",//"rightRingProximal",
"rightRingProximal",//"rightRingIntermediate",
"rightRingIntermediate",//"rightRingDistal",
"rightHand",//"rightLittleProximal",
"rightLittleProximal",//"rightLittleIntermediate",
"rightLittleIntermediate",//"rightLittleDistal",
"chest",//"upperChest"
};
//
const TArray<FString> VRMUtil::ue4_humanoid_bone_list = {
"Root",
"Pelvis",
"spine_01",
"spine_02",
"spine_03",
"clavicle_l",
"UpperArm_L",
"lowerarm_l",
"Hand_L","leftHand",
"index_01_l",
"index_02_l",
"index_03_l",
"middle_01_l",
"middle_02_l",
"middle_03_l",
"pinky_01_l",
"pinky_02_l",
"pinky_03_l",
"ring_01_l",
"ring_02_l",
"ring_03_l",
"thumb_01_l",
"thumb_02_l",
"thumb_03_l",
"lowerarm_twist_01_l",
"upperarm_twist_01_l",
"clavicle_r",
"UpperArm_R",
"lowerarm_r",
"Hand_R",
"index_01_r",
"index_02_r",
"index_03_r",
"middle_01_r",
"middle_02_r",
"middle_03_r",
"pinky_01_r",
"pinky_02_r",
"pinky_03_r",
"ring_01_r",
"ring_02_r",
"ring_03_r",
"thumb_01_r",
"thumb_02_r",
"thumb_03_r",
"lowerarm_twist_01_r",
"upperarm_twist_01_r",
"neck_01",
"head",
"Thigh_L",
"calf_l",
"calf_twist_01_l",
"Foot_L",
"ball_l",
"thigh_twist_01_l",
"Thigh_R",
"calf_r",
"calf_twist_01_r",
"Foot_R",
"ball_r",
"thigh_twist_01_r",
"ik_foot_root",
"ik_foot_l",
"ik_foot_r",
"ik_hand_root",
"ik_hand_gun",
"ik_hand_l",
"ik_hand_r",
"Custom_1",
"Custom_2",
"Custom_3",
"Custom_4",
"Custom_5",
};
| 24.049881 | 97 | 0.679111 | NikkoBertoa |
22a7bd433656a096e6e21118b963d5287106c662 | 433 | cpp | C++ | src/atta/uiSystem/layers/editor/windows/logWindow.cpp | brenocq/atta | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 5 | 2021-11-18T02:44:45.000Z | 2021-12-21T17:46:10.000Z | src/atta/uiSystem/layers/editor/windows/logWindow.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 1 | 2021-11-18T02:56:14.000Z | 2021-12-04T15:09:16.000Z | src/atta/uiSystem/layers/editor/windows/logWindow.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 3 | 2020-09-10T07:17:00.000Z | 2020-11-05T10:24:41.000Z | //--------------------------------------------------
// Atta UI System
// logWindow.cpp
// Date: 2021-12-28
// By Breno Cunha Queiroz
//--------------------------------------------------
#include <atta/uiSystem/layers/editor/windows/logWindow.h>
#include <imgui.h>
namespace atta::ui
{
void LogWindow::render()
{
ImGui::Begin("Log");
ImGui::Text("Logging not implemented yet");
ImGui::End();
}
}
| 22.789474 | 58 | 0.471132 | brenocq |
22a81895bc47a1df94e35679c5d89285e4847a96 | 1,332 | cpp | C++ | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 14 ( Recursion)/main(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 14 ( Recursion)/main(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 14 ( Recursion)/main(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
}
}
int factorial(int n)
{
if(n==1)
return 1;
else
return n*factorial (n-1);
}
int add(int n)
{
if(n != 0)
return n + add(n - 1);
return 0;
}
int findmin(const int a[], int n)
{
if(n == 0)
return a[0];
else
{
if(a[n-1] < findmin(a,(n-1)))
return a[n-1];
else
return findmin(a,(n-1));
}
}
int find(int decimal_number)
{
if (decimal_number == 0)
return 0;
else
return (decimal_number % 2 + 10 *find(decimal_number / 2));
}
float sumSeries(int n)
if(n==0)
return 1;
else
return( sumSeries(1/pow(2,n)))+sumSeris(1/pow(2/(n-1)))))
int main()
{
int n,i=0;
int A[5]={2,3,1,6,9};
int decimal_number = 10;
cout<<"Input the number of terms for Fibonacci Series:";
cin>>n;
cout<<"\nFibonacci Series is as follows\n";
while(i<n)
{
cout<<" "<<fibonacci(i);
i++;
}
cout<<"factorial of"<<n<<factorial(n);
cout<<"Sum of"<<n <<" is" <<add(n);
cout<<"Minimum number is A is "<<findmin(A,5);
cout<<find(decimal_number);
cout<<(Sumofseries);
return 0;
}
| 14.021053 | 67 | 0.511261 | diptu |
22a892bf8494cb0101a3d4e48295ffaa2af74f6e | 1,424 | cpp | C++ | Competitive Programming/RotaUFMG/Roteiro 3 (DC, Backtracking, Brute Force)/DontGetRooked.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Competitive Programming/RotaUFMG/Roteiro 3 (DC, Backtracking, Brute Force)/DontGetRooked.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Competitive Programming/RotaUFMG/Roteiro 3 (DC, Backtracking, Brute Force)/DontGetRooked.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
using namespace std;
int size;
char board[4][4 + 1];
int canPut(int i, int j)
{
int left, right, up, down; left = right = up = down = 1;
for (int k = 0; k < size; k ++)
{
if (j + k < size && board[i][j + k] == 'X') right = 0;
if (j - k >= 0 && board[i][j - k] == 'X') left = 0;
if (i + k < size && board[i + k][j] == 'X') down = 0;
if (i - k >= 0 && board[i - k][j] == 'X') up = 0;
if (j + k < size && right && board[i][j + k] == 'R') return(0);
if (j - k >= 0 && left && board[i][j - k] == 'R') return(0);
if (i + k < size && down && board[i + k][j] == 'R') return(0);
if (i - k >= 0 && up && board[i - k][j] == 'R') return(0);
}
return(1);
}
int bruteForce(int i, int j)
{
int put = 0, notPut = 0;
if (i == size)
return(0);
else if (board[i][j] != '.')
{
if (j == size - 1) return(bruteForce(i + 1, 0));
else return(bruteForce(i, j + 1));
}
if (canPut(i, j))
{
board[i][j] = 'R';
if (j == size - 1) put = 1 + bruteForce(i + 1, 0);
else put = 1 + bruteForce(i, j + 1);
board[i][j] = '.';
}
if (j == size - 1) notPut = bruteForce(i + 1, 0);
else notPut = bruteForce(i, j + 1);
return(max(put, notPut));
}
int main()
{
while (scanf("%d", &size) && size)
{
for (int i = 0; i < size; i ++)
scanf("\n%s", board[i]);
int ans = bruteForce(0, 0);
printf("%d\n", ans);
}
return(0);
} | 24.551724 | 67 | 0.456461 | NelsonGomesNeto |
22ac6edc23e3ee23a1513a485413b9f292131d90 | 27,483 | cc | C++ | src/messages.cc | qian-long/TileDB-multinode | ba2a38b2cc6169935c73b76af8c53e8544c11300 | [
"MIT"
] | null | null | null | src/messages.cc | qian-long/TileDB-multinode | ba2a38b2cc6169935c73b76af8c53e8544c11300 | [
"MIT"
] | null | null | null | src/messages.cc | qian-long/TileDB-multinode | ba2a38b2cc6169935c73b76af8c53e8544c11300 | [
"MIT"
] | null | null | null | #include "messages.h"
#include <assert.h>
#include <cstring>
#include <functional>
#include "debug.h"
/******************************************************
*********************** MESSAGE **********************
******************************************************/
std::pair<char*, uint64_t> Msg::serialize() {
throw MessageException("Bad function call");
}
Msg* deserialize_msg(int type, char* buf, uint64_t length){
switch(type){
case GET_TAG:
return GetMsg::deserialize(buf, length);
case DEFINE_ARRAY_TAG:
return DefineArrayMsg::deserialize(buf, length);
case LOAD_TAG:
return LoadMsg::deserialize(buf, length);
case SUBARRAY_TAG:
return SubarrayMsg::deserialize(buf, length);
case FILTER_TAG:
return FilterMsg::deserialize(buf, length);
case AGGREGATE_TAG:
return AggregateMsg::deserialize(buf, length);
case PARALLEL_LOAD_TAG:
return ParallelLoadMsg::deserialize(buf, length);
case JOIN_TAG:
return JoinMsg::deserialize(buf, length);
case ACK_TAG:
return AckMsg::deserialize(buf, length);
}
throw MessageException("trying to deserailze msg of unknown type");
}
/******************************************************
******************* SubArray MESSAGE *****************
******************************************************/
SubarrayMsg::SubarrayMsg(std::string result_name, ArraySchema schema, std::vector<double> ranges) : Msg(SUBARRAY_TAG) {
result_array_name_ = result_name;
ranges_ = ranges;
array_schema_ = schema;
}
std::pair<char*, uint64_t> SubarrayMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
uint64_t length;
// serialize relevant sub components
std::pair<char*, uint64_t> as_pair = array_schema_.serialize();
// calculating buffer_size
buffer_size += sizeof(size_t); // result arrayname length
buffer_size += result_array_name_.size(); // result_arrayname
buffer_size += sizeof(uint64_t); // array schema length
buffer_size += as_pair.second; // array schema
buffer_size += ranges_.size(); // ranges length
for (int i = 0; i < ranges_.size(); ++i) {
buffer_size += sizeof(double); // add each range part
}
// creating buffer
buffer = new char[buffer_size];
// serialize filename
length = result_array_name_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], result_array_name_.c_str(), length);
pos += length;
// serialize array schema
length = as_pair.second;
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], as_pair.first, length);
pos += length;
// serialize ranges
length = ranges_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
std::vector<double>::iterator it = ranges_.begin();
for (; it != ranges_.end(); it++, pos += sizeof(double)) {
double extent = *it;
memcpy(&buffer[pos], &extent, sizeof(double));
}
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
SubarrayMsg* SubarrayMsg::deserialize(char* buffer, uint64_t buffer_length){
uint64_t counter = 0;
std::stringstream ss;
std::vector<double> ranges;
// deserialize array name
size_t filename_length;
memcpy(&filename_length, &buffer[counter], sizeof(size_t));
counter += sizeof(size_t);
ss.write(&buffer[counter], filename_length);
std::string array_name = ss.str(); // first arg
counter += filename_length;
//deserailize schema
uint64_t arrayschema_length;
memcpy(&arrayschema_length, &buffer[counter], sizeof(uint64_t));
counter += sizeof(uint64_t);
ArraySchema* schema = new ArraySchema();
schema->deserialize(&buffer[counter], arrayschema_length);
counter += arrayschema_length;
//deserialize vector
size_t num_doubles;
memcpy(&num_doubles, &buffer[counter], sizeof(size_t));
counter += sizeof(size_t);
for (size_t i = 0; i < num_doubles; i++) {
double extent;
memcpy(&extent, &buffer[counter], sizeof(double));
ranges.push_back(extent);
counter += sizeof(double);
}
return new SubarrayMsg(array_name, *schema, ranges);
}
/******************************************************
********************* LOAD MESSAGE *******************
******************************************************/
LoadMsg::LoadMsg() : Msg(LOAD_TAG) { }
LoadMsg::LoadMsg(const std::string filename,
ArraySchema& array_schema,
PartitionType type,
LoadMethod method,
uint64_t num_samples) :Msg(LOAD_TAG) {
filename_ = filename;
array_schema_ = array_schema;
type_ = type;
method_ = method;
num_samples_ = num_samples;
}
std::pair<char*, uint64_t> LoadMsg::serialize() {
uint64_t buffer_size = 0;
uint64_t pos = 0;
char* buffer;
uint64_t length;
// serialize relevant components
std::pair<char*, uint64_t> as_pair = array_schema_.serialize();
// calculate buffer size
buffer_size += sizeof(size_t); // filename length
buffer_size += filename_.size(); // filename
buffer_size += sizeof(uint64_t); // array schema length
buffer_size += as_pair.second; // array schema
buffer_size += sizeof(PartitionType); // partition type
buffer_size += sizeof(LoadMethod); // load method (sort or sample)
buffer_size += sizeof(uint64_t); // num_samples
buffer = new char[buffer_size];
// serialize filename
length = filename_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], filename_.c_str(), length);
pos += length;
// serialize array schema
length = as_pair.second;
memcpy(&buffer[pos], &length, sizeof(uint64_t));
pos += sizeof(uint64_t);
memcpy(&buffer[pos], as_pair.first, length);
pos += length;
// serialize partition type
memcpy(&buffer[pos], (char *) &type_, sizeof(PartitionType));
pos += sizeof(PartitionType);
// serialize load method
memcpy(&buffer[pos], (char *) &method_, sizeof(LoadMethod));
pos += sizeof(LoadMethod);
// serialize num_samples
memcpy(&buffer[pos], (char *) &num_samples_, sizeof(uint64_t));
assert(pos + sizeof(uint64_t) == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
LoadMsg* LoadMsg::deserialize(char* buffer, uint64_t buffer_length) {
std::string filename;
std::stringstream ss;
uint64_t counter = 0;
size_t filename_length;
memcpy(&filename_length, &buffer[counter], sizeof(size_t));
counter += sizeof(size_t);
ss.write(&buffer[counter], filename_length);
filename = ss.str(); // first arg
counter += filename_length;
uint64_t arrayschema_length;
memcpy(&arrayschema_length, &buffer[counter], sizeof(uint64_t));
counter += sizeof(uint64_t);
// this is creating space for it on the heap.
ArraySchema* schema = new ArraySchema();
schema->deserialize(&buffer[counter], arrayschema_length); // second arg
counter += arrayschema_length;
// partition type
PartitionType type;
memcpy(&type, &buffer[counter], sizeof(PartitionType));
counter += sizeof(PartitionType);
// load method
LoadMethod method;
memcpy(&method, &buffer[counter], sizeof(LoadMethod));
counter += sizeof(LoadMethod);
// num samples
uint64_t num_samples;
memcpy(&num_samples, &buffer[counter], sizeof(uint64_t));
counter += sizeof(uint64_t);
// sanity check
assert(counter == buffer_length);
return new LoadMsg(filename, *schema, type, method, num_samples);
}
/******************************************************
********************* GET MESSAGE ********************
******************************************************/
GetMsg::GetMsg() : Msg(GET_TAG) {};
GetMsg::GetMsg(std::string array_name) : Msg(GET_TAG) {
array_name_ = array_name;
}
std::pair<char*, uint64_t> GetMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
size_t length = array_name_.size();
buffer_size += sizeof(size_t);
buffer_size += length;
buffer = new char[buffer_size];
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], array_name_.c_str(), length);
assert(pos + length == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
GetMsg* GetMsg::deserialize(char* buffer, uint64_t buffer_length) {
//getmsg args
std::string arrayname;
std::stringstream ss;
uint64_t counter = 0;
size_t array_name_length;
memcpy(&array_name_length, &buffer[counter], sizeof(size_t));
counter += sizeof(size_t);
ss.write(&buffer[counter], array_name_length);
arrayname = ss.str(); // first arg
return new GetMsg(arrayname);
}
/******************************************************
*************** ARRAYSCHEMA MESSAGE ******************
******************************************************/
DefineArrayMsg::DefineArrayMsg() : Msg(DEFINE_ARRAY_TAG) {};
DefineArrayMsg::DefineArrayMsg(ArraySchema& schema) : Msg(DEFINE_ARRAY_TAG) {
array_schema_ = schema;
}
std::pair<char*, uint64_t> DefineArrayMsg::serialize() {
return array_schema_.serialize();
}
DefineArrayMsg* DefineArrayMsg::deserialize(char* buffer, uint64_t buffer_length) {
ArraySchema* schema = new ArraySchema();
schema->deserialize(buffer, buffer_length);
return new DefineArrayMsg(*schema);
}
/******************************************************
****************** FILTER MESSAGE ********************
******************************************************/
FilterMsg::FilterMsg() : Msg(FILTER_TAG) {}
FilterMsg::FilterMsg(
std::string& array_name,
std::string& expression,
std::string& result_array_name) : Msg(FILTER_TAG) {
array_name_ = array_name;
expr_ = expression;
result_array_name_ = result_array_name;
}
std::pair<char*, uint64_t> FilterMsg::serialize() {
uint64_t buffer_size = 0;
uint64_t pos = 0;
char* buffer;
uint64_t length;
// calculate buffer size
buffer_size += sizeof(size_t); // result array name length
buffer_size += result_array_name_.size(); // result array name
buffer_size += sizeof(size_t); // expr str length
buffer_size += expr_.size(); // expr str
buffer_size += sizeof(size_t); // array name length
buffer_size += array_name_.size(); // array name
// creating buffer
buffer = new char[buffer_size];
// serialize resulting array name
length = result_array_name_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], result_array_name_.c_str(), length);
pos += length;
// serialize expr str
length = expr_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], expr_.c_str(), length);
pos += length;
// serialize array name
length = array_name_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], array_name_.c_str(), length);
assert(pos + length == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
FilterMsg* FilterMsg::deserialize(char* buffer, uint64_t buf_length) {
std::stringstream ss;
uint64_t pos = 0;
// parse result array name
size_t length;
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
std::string result_array_name = ss.str(); // first arg
pos += length;
ss.str(std::string());
// parse expr str
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
std::string expr = ss.str();
pos += length;
ss.str(std::string());
// parse array name
length = (size_t) buffer[pos];
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
std::string array_name = ss.str();
// finished parsing
assert(length + pos == buf_length);
return new FilterMsg(array_name, expr, result_array_name);
}
/*********************************************************
***************** PARALLEL LOAD MESSAGE *****************
*********************************************************/
ParallelLoadMsg::ParallelLoadMsg() : Msg(PARALLEL_LOAD_TAG) {}
ParallelLoadMsg::ParallelLoadMsg(
std::string filename,
PartitionType type,
ArraySchema& array_schema,
uint64_t num_samples) : Msg(PARALLEL_LOAD_TAG) {
filename_ = filename;
type_ = type;
array_schema_ = array_schema;
num_samples_ = num_samples;
}
std::pair<char*, uint64_t> ParallelLoadMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
// serialize relevant components
std::pair<char*, uint64_t> as_pair = array_schema_.serialize();
// calculate buffer size
buffer_size += sizeof(size_t); // filename length
buffer_size += filename_.size(); // filename
buffer_size += sizeof(PartitionType); // load type
buffer_size += sizeof(uint64_t); // array schema length
buffer_size += as_pair.second; // array schema
buffer_size += sizeof(uint64_t); // num samples
// creating buffer
buffer = new char[buffer_size];
// serialize filename
size_t length = filename_.size();
memcpy(&buffer[pos], &length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], filename_.c_str(), length);
pos += length;
// serialize load type
memcpy(&buffer[pos], (char *) &type_, sizeof(PartitionType));
pos += sizeof(PartitionType);
// serialize array schema
uint64_t schema_length = as_pair.second;
memcpy(&buffer[pos], &schema_length, sizeof(uint64_t));
pos += sizeof(uint64_t);
memcpy(&buffer[pos], as_pair.first, schema_length);
pos += schema_length;
// serialize num samples
memcpy(&buffer[pos], &num_samples_, sizeof(uint64_t));
assert(pos + sizeof(uint64_t) == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
ParallelLoadMsg* ParallelLoadMsg::deserialize(char* buffer, uint64_t buffer_size) {
std::string filename;
uint64_t pos = 0;
// filename
size_t length;
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
filename = std::string(&buffer[pos], length);
pos += length;
// load type
PartitionType type = static_cast<PartitionType>(buffer[pos]);
pos += sizeof(PartitionType);
// array schema
memcpy(&length, &buffer[pos], sizeof(uint64_t));
pos += sizeof(uint64_t);
ArraySchema* schema = new ArraySchema();
schema->deserialize(&buffer[pos], length);
pos += length;
// num samples
uint64_t num_samples;
memcpy(&num_samples, &buffer[pos], sizeof(uint64_t));
assert(pos + sizeof(uint64_t) == buffer_size);
return new ParallelLoadMsg(filename, type, *schema, num_samples);
}
/******************************************************
******************* AGGREGATE MESSAGE ****************
******************************************************/
AggregateMsg::AggregateMsg() : Msg(AGGREGATE_TAG) {};
AggregateMsg::AggregateMsg(std::string array_name, int attr_index): Msg(AGGREGATE_TAG) {
attr_index_ = attr_index;
array_name_ = array_name;
}
std::pair<char*, uint64_t> AggregateMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
// calculate buffer size
buffer_size += sizeof(uint64_t); // array name size
buffer_size += array_name_.size(); // array name
buffer_size += sizeof(int); // attr index
buffer = new char[buffer_size];
// serialize array name
uint64_t length = array_name_.size();
memcpy(&buffer[pos], &length, sizeof(uint64_t));
pos += sizeof(uint64_t);
memcpy(&buffer[pos], array_name_.c_str(), length);
pos += length;
// serialize attr int
memcpy(&buffer[pos], &attr_index_, sizeof(int));
assert(pos += sizeof(int) == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
AggregateMsg* AggregateMsg::deserialize(char* buf, uint64_t len) {
uint64_t pos = 0;
// deserialize array name
uint64_t length = (uint64_t) buf[pos];
pos += sizeof(uint64_t);
std::string array_name = std::string(&buf[pos], length);
pos += length;
// deserialize attribute index
int attr_index = (int) buf[pos];
assert(pos + sizeof(int) == len);
return new AggregateMsg(array_name, attr_index);
}
/******************************************************
********************* JOIN MESSAGE *******************
******************************************************/
JoinMsg::JoinMsg() : Msg(JOIN_TAG) {};
JoinMsg::JoinMsg(std::string array_name_A,
std::string array_name_B,
std::string result_array_name) : Msg(JOIN_TAG) {
array_name_A_ = array_name_A;
array_name_B_ = array_name_B;
result_array_name_ = result_array_name;
}
std::pair<char*, uint64_t> JoinMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
// Compute lengths
size_t A_length = array_name_A_.size();
size_t B_length = array_name_B_.size();
size_t result_length = result_array_name_.size();
buffer_size += sizeof(size_t);
buffer_size += A_length;
buffer_size += sizeof(size_t);
buffer_size += B_length;
buffer_size += sizeof(size_t);
buffer_size += result_length;
// creating buffer
buffer = new char[buffer_size];
// Serializing array_name_A_
memcpy(&buffer[pos], &A_length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], array_name_A_.c_str(), A_length);
pos += A_length;
// Serializing array_name_B_
memcpy(&buffer[pos], &B_length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], array_name_B_.c_str(), B_length);
pos += B_length;
// Serializing result_array_name_
memcpy(&buffer[pos], &result_length, sizeof(size_t));
pos += sizeof(size_t);
memcpy(&buffer[pos], result_array_name_.c_str(), result_length);
assert(pos + result_length == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
JoinMsg* JoinMsg::deserialize(char* buffer, uint64_t buffer_length) {
std::string array_name_A;
std::string array_name_B;
std::string result_array_name;
uint64_t pos = 0;
std::stringstream ss;
// deserializing array_name_A_
size_t length;
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
pos += length;
array_name_A = ss.str();
ss.str(std::string());
// deserializing array_name_B_
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
pos += length;
array_name_B = ss.str();
ss.str(std::string());
// deserializing result_array_name_
memcpy(&length, &buffer[pos], sizeof(size_t));
pos += sizeof(size_t);
ss.write(&buffer[pos], length);
result_array_name = ss.str();
assert(pos + length == buffer_length);
return new JoinMsg(array_name_A, array_name_B, result_array_name);
}
/******************************************************
******************** ACK MESSAGE *********************
******************************************************/
AckMsg::AckMsg() : Msg(ACK_TAG) {};
AckMsg::AckMsg(Result r, int tag, double time) : Msg(ACK_TAG) {
result_ = r;
tag_ = tag;
time_ = time;
}
std::pair<char*, uint64_t> AckMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
buffer_size = sizeof(Result); // result
buffer_size += sizeof(int); // tag
buffer_size += sizeof(double); // time
buffer = new char[buffer_size];
// serialize result
memcpy(&buffer[pos], &result_, sizeof(Result));
pos += sizeof(Result);
// serialize tag
memcpy(&buffer[pos], &tag_, sizeof(int));
pos += sizeof(int);
// serialize time
memcpy(&buffer[pos], &time_, sizeof(double));
pos += sizeof(double);
assert(pos == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
AckMsg* AckMsg::deserialize(char* buffer, uint64_t buffer_length) {
// getmsg args
int pos = 0;
// deserialize result
Result result;
memcpy(&result, &buffer[pos], sizeof(Result));
pos += sizeof(Result);
// deserialize tag
int tag;
memcpy(&tag, &buffer[pos], sizeof(int));
pos += sizeof(int);
// deserialize time
double time;
memcpy(&time, &buffer[pos], sizeof(double));
pos += sizeof(double);
// sanity check
assert(pos == buffer_length);
return new AckMsg(result, tag, time);
}
std::string AckMsg::to_string() {
std::stringstream ss;
switch (tag_) {
case GET_TAG:
ss << "GET";
break;
case DEFINE_ARRAY_TAG:
ss << "DEFINE_ARRAY_TAG";
break;
case LOAD_TAG:
ss << "LOAD";
break;
case SUBARRAY_TAG:
ss << "SUBARRAY";
break;
case FILTER_TAG:
ss << "FILTER";
break;
case AGGREGATE_TAG:
ss << "AGGREGATE";
break;
case PARALLEL_LOAD_TAG:
ss << "PARALLEL_LOAD";
break;
case JOIN_TAG:
ss << "JOIN_TAG";
break;
default:
break;
}
if (result_ == DONE) {
ss << "[DONE]";
} else {
assert(result_ == ERROR);
ss << "[ERROR]";
}
ss << " Time[" << time_ << " secs]";
return ss.str();
}
/******************************************************
******************* Samples MESSAGE ******************
******************************************************/
SamplesMsg::SamplesMsg() : Msg(SAMPLES_TAG) {};
SamplesMsg::SamplesMsg(std::vector<uint64_t> samples) : Msg(SAMPLES_TAG) {
samples_ = samples;
}
std::pair<char*, uint64_t> SamplesMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
buffer_size = sizeof(uint64_t) * samples_.size();
buffer = new char[buffer_size];
for (std::vector<uint64_t>::iterator it = samples_.begin();
it != samples_.end(); ++it, pos += sizeof(uint64_t)) {
uint64_t sample = *it;
memcpy(&buffer[pos], &sample, sizeof(uint64_t));
}
assert(pos == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
SamplesMsg* SamplesMsg::deserialize(char* buffer, uint64_t buffer_length) {
std::vector<uint64_t> samples;
uint64_t pos;
assert(buffer_length % 8 == 0);
for (pos = 0; pos < buffer_length; pos += sizeof(uint64_t)) {
uint64_t sample;
memcpy(&sample, &buffer[pos], sizeof(uint64_t));
samples.push_back(sample);
}
assert(samples.size() * 8 == buffer_length);
return new SamplesMsg(samples);
}
/******************************************************
*************** Bounding Coords MESSAGE **************
******************************************************/
BoundingCoordsMsg::BoundingCoordsMsg() : Msg(BOUNDING_COORDS_TAG) {};
BoundingCoordsMsg::BoundingCoordsMsg(
StorageManager::BoundingCoordinates bounding_coords) :
Msg(BOUNDING_COORDS_TAG) {
bounding_coords_ = bounding_coords;
}
std::pair<char*, uint64_t> BoundingCoordsMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
int num_dim = 0;
if (bounding_coords_.size() > 0) {
num_dim = bounding_coords_[0].first.size();
}
buffer_size = sizeof(int); // number of dimensions
buffer_size += 2 * num_dim * bounding_coords_.size() * sizeof(double); // size of bounding coordinates
buffer = new char[buffer_size];
// serialize num dim
memcpy(&buffer[pos], &num_dim, sizeof(int));
pos += sizeof(int);
// serialize bounding coordinates
for (int i = 0; i < bounding_coords_.size(); ++i) {
// serialize first coords in pair
for (std::vector<double>::iterator it = bounding_coords_[i].first.begin();
it != bounding_coords_[i].first.end(); ++it) {
double coord = *it;
memcpy(&buffer[pos], &coord, sizeof(double));
pos += sizeof(double);
}
// serialize second coords in pair
for (std::vector<double>::iterator it = bounding_coords_[i].second.begin();
it != bounding_coords_[i].second.end(); ++it) {
double coord = *it;
memcpy(&buffer[pos], &coord, sizeof(double));
pos += sizeof(double);
}
}
assert(pos == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
BoundingCoordsMsg* BoundingCoordsMsg::deserialize(char* buffer, uint64_t buffer_length) {
StorageManager::BoundingCoordinates bounding_coords;
uint64_t pos = 0;
// deserialize num_dim
int num_dim;
memcpy(&num_dim, &buffer[pos], sizeof(int));
pos += sizeof(int);
// deserialize all bounding coords
for (; pos < buffer_length; pos += 2 * num_dim * sizeof(double)) {
std::vector<double> coords1;
std::vector<double> coords2;
for (int i = 0; i < num_dim; ++i) {
double coord;
memcpy(&coord, &buffer[pos + i*sizeof(double)], sizeof(double));
coords1.push_back(coord);
}
int offset = num_dim * sizeof(double);
for (int i = 0; i < num_dim; ++i) {
double coord;
memcpy(&coord, &buffer[pos + i*sizeof(double) + offset], sizeof(double));
coords2.push_back(coord);
}
bounding_coords.push_back(
StorageManager::BoundingCoordinatesPair(coords1, coords2));
}
// TODO fix when buffer is empty...
if (buffer_length > 0) {
assert(pos == buffer_length);
}
return new BoundingCoordsMsg(bounding_coords);
}
/******************************************************
******************** TILE MESSAGE ********************
******************************************************/
TileMsg::TileMsg() : Msg(BOUNDING_COORDS_TAG) {};
TileMsg::TileMsg(std::string array_name,
int attr_id,
const char* payload,
uint64_t num_cells,
uint64_t cell_size) : Msg(TILE_TAG) {
array_name_ = array_name;
attr_id_ = attr_id;
payload_ = payload;
num_cells_ = num_cells;
cell_size_ = cell_size;
}
std::pair<char*, uint64_t> TileMsg::serialize() {
uint64_t buffer_size = 0, pos = 0;
char* buffer;
buffer_size = sizeof(int); // array_name length
buffer_size += array_name_.size(); // array_name
buffer_size += sizeof(int); // attr_id
buffer_size += sizeof(uint64_t); // num_cells
buffer_size += sizeof(uint64_t); // cell_size
buffer_size += payload_size(); // payload size
buffer = new char[buffer_size];
// serialize array name
int length = array_name_.size();
memcpy(&buffer[pos], &length, sizeof(int));
pos += sizeof(int);
memcpy(&buffer[pos], array_name_.c_str(), length);
pos += length;
// serialize attr id
memcpy(&buffer[pos], &attr_id_, sizeof(int));
pos += sizeof(int);
// serialize num cells
memcpy(&buffer[pos], &num_cells_, sizeof(uint64_t));
pos += sizeof(uint64_t);
// serialize cell size
memcpy(&buffer[pos], &cell_size_, sizeof(uint64_t));
pos += sizeof(uint64_t);
// serialize payload
memcpy(&buffer[pos], payload_, payload_size());
pos += payload_size();
assert(pos == buffer_size);
return std::pair<char*, uint64_t>(buffer, buffer_size);
}
TileMsg* TileMsg::deserialize(char* buffer, uint64_t buffer_length) {
std::stringstream ss;
uint64_t pos = 0;
// deserialize array name
int length;
memcpy(&length, &buffer[pos], sizeof(int));
pos += sizeof(int);
ss.write(&buffer[pos], length);
std::string array_name = ss.str();
pos += length;
ss.str(std::string());
// deserialize attr id
int attr_id;
memcpy(&attr_id, &buffer[pos], sizeof(int));
pos += sizeof(int);
// deserialize num cells
uint64_t num_cells;
memcpy(&num_cells, &buffer[pos], sizeof(uint64_t));
pos += sizeof(uint64_t);
// deserialize cell size
uint64_t cell_size;
memcpy(&cell_size, &buffer[pos], sizeof(uint64_t));
pos += sizeof(uint64_t);
// deserialize payload
uint64_t payload_size = cell_size * num_cells;
assert(payload_size < buffer_length);
const char *payload = new char[payload_size];
memcpy((char *)payload, &buffer[pos], payload_size);
pos += payload_size;
assert(pos == buffer_length);
return new TileMsg(array_name, attr_id, payload, num_cells, cell_size);
}
| 28.12999 | 119 | 0.632573 | qian-long |
22b1285a0e087bd9dd15fa751123b318b5bc40c5 | 2,316 | cc | C++ | SimCalorimetry/EcalSimAlgos/src/EcalSimParameterMap.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | SimCalorimetry/EcalSimAlgos/src/EcalSimParameterMap.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimCalorimetry/EcalSimAlgos/src/EcalSimParameterMap.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2020-01-10T13:36:46.000Z | 2020-01-10T13:36:46.000Z | #include "SimCalorimetry/EcalSimAlgos/interface/EcalSimParameterMap.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
#include <iostream>
/** Relevant constants are:
4.5 photoelectrons per MeV (J. Nash's slides)
APD gain 50, but analog signal stays in GeV
Account for excess noise factor
*/
EcalSimParameterMap::EcalSimParameterMap() :
theBarrelParameters(2250., 1./2250.,
1., 0,
10, 6, true, true),
theEndcapParameters( 1800., 1./1800.,
1., 0,
10, 6, true, true),
theESParameters(1., 1., 1., 20., 3, 2, false, true)
{}
EcalSimParameterMap::EcalSimParameterMap(double simHitToPhotoelectronsBarrel,
double simHitToPhotoelectronsEndcap,
double photoelectronsToAnalogBarrel,
double photoelectronsToAnalogEndcap,
double samplingFactor, double timePhase,
int readoutFrameSize, int binOfMaximum,
bool doPhotostatistics, bool syncPhase) :
theBarrelParameters(simHitToPhotoelectronsBarrel, photoelectronsToAnalogBarrel,
samplingFactor, timePhase,
readoutFrameSize, binOfMaximum, doPhotostatistics, syncPhase),
theEndcapParameters(simHitToPhotoelectronsEndcap, photoelectronsToAnalogEndcap,
samplingFactor, timePhase,
readoutFrameSize, binOfMaximum, doPhotostatistics, syncPhase),
theESParameters(1., 1., 1., 20., 3, 2, false, syncPhase)
{}
/*
CaloSimParameters(double simHitToPhotoelectrons, double photoelectronsToAnalog,
double samplingFactor, double timePhase,
int readoutFrameSize, int binOfMaximum,
bool doPhotostatistics, bool syncPhase)
*/
const CaloSimParameters & EcalSimParameterMap::simParameters(const DetId & detId) const
{
if (EcalSubdetector(detId.subdetId()) == EcalBarrel)
return theBarrelParameters;
else if (EcalSubdetector(detId.subdetId()) == EcalEndcap)
return theEndcapParameters;
else
return theESParameters;
}
| 42.109091 | 88 | 0.629965 | nistefan |
22b2b4b3c01f94a387aa9b5836834c4e2d2f1e88 | 59,332 | cpp | C++ | src/fw/asdxApp.cpp | ProjectAsura/asdx12 | 359f7288557ea3e83775864f69a85b6ad11f7f62 | [
"MIT"
] | 2 | 2021-06-17T02:27:43.000Z | 2022-01-30T09:06:05.000Z | src/fw/asdxApp.cpp | ProjectAsura/asdx12 | 359f7288557ea3e83775864f69a85b6ad11f7f62 | [
"MIT"
] | null | null | null | src/fw/asdxApp.cpp | ProjectAsura/asdx12 | 359f7288557ea3e83775864f69a85b6ad11f7f62 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// File : asdxApp.cpp
// Desc : Application Module.
// Copyright(c) Project Asura. All right reserved.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <list>
#include <cassert>
#include <fnd/asdxMacro.h>
#include <fnd/asdxMath.h>
#include <fnd/asdxLogger.h>
#include <fw/asdxApp.h>
#include <gfx/asdxCommandQueue.h>
namespace /* anonymous */ {
///////////////////////////////////////////////////////////////////////////////
// ApplicationList class
///////////////////////////////////////////////////////////////////////////////
class ApplicationList
{
//=========================================================================
// list of friend classes and methods.
//=========================================================================
/* NOTHING */
public:
//=========================================================================
// public variables.
//=========================================================================
typedef std::list< asdx::Application* > List;
typedef std::list< asdx::Application* >::iterator ListItr;
typedef std::list< asdx::Application* >::const_iterator ListCItr;
//=========================================================================
// public methods.
//=========================================================================
//-------------------------------------------------------------------------
//! @brief コンストラクタです.
//-------------------------------------------------------------------------
ApplicationList()
{ m_List.clear(); }
//-------------------------------------------------------------------------
//! @brief デストラクタです.
//-------------------------------------------------------------------------
~ApplicationList()
{ m_List.clear(); }
//-------------------------------------------------------------------------
//! @brief push_back()のラッパー関数です.
//-------------------------------------------------------------------------
void PushBack( asdx::Application* pApp )
{ m_List.push_back( pApp ); }
//-------------------------------------------------------------------------
//! @brief push_front()のラッパー関数です.
//-------------------------------------------------------------------------
void PushFront( asdx::Application* pApp )
{ m_List.push_front( pApp ); }
//-------------------------------------------------------------------------
//! @brief pop_back()のラッパー関数です.
//-------------------------------------------------------------------------
void PopBack()
{ m_List.pop_back(); }
//-------------------------------------------------------------------------
//! @brief pop_front()のラッパー関数です.
//-------------------------------------------------------------------------
void PopFront()
{ m_List.pop_front(); }
//-------------------------------------------------------------------------
//! @brief clear()のラッパー関数です.
//-------------------------------------------------------------------------
void Clear()
{ m_List.clear(); }
//-------------------------------------------------------------------------
//! @brief remove()のラッパー関数です.
//-------------------------------------------------------------------------
void Remove( asdx::Application* pApp )
{ m_List.remove( pApp ); }
//-------------------------------------------------------------------------
//! @brief begin()のラッパー関数です.
//-------------------------------------------------------------------------
ListItr Begin()
{ return m_List.begin(); }
//-------------------------------------------------------------------------
//! @brief begin()のラッパー関数です(const版).
//-------------------------------------------------------------------------
ListCItr Begin() const
{ return m_List.begin(); }
//-------------------------------------------------------------------------
//! @brief end()のラッパー関数です.
//-------------------------------------------------------------------------
ListItr End()
{ return m_List.end(); }
//-------------------------------------------------------------------------
//! @brief end()のラッパー関数です(const版).
//-------------------------------------------------------------------------
ListCItr End() const
{ return m_List.end(); }
private:
//=========================================================================
// private variables.
//=========================================================================
List m_List; //!< リストです.
//=========================================================================
// private methods.
//=========================================================================
/* NOTHING */
};
///////////////////////////////////////////////////////////////////////////////
// AllocationTypeTable structure
///////////////////////////////////////////////////////////////////////////////
struct AllocationTypeTable
{
D3D12_DRED_ALLOCATION_TYPE Type;
const char* Tag;
};
// アプリケーションリスト.
ApplicationList g_AppList;
// オペレーションテーブル.
static const char* g_BreadcrumTable[] = {
"SETMARKER", // 0
"BEGINEVENT", // 1
"ENDEVENT", // 2
"DRAWINSTANCED", // 3
"DRAWINDEXEDINSTANCED", // 4
"EXECUTEINDIRECT", // 5
"DISPATCH", // 6
"COPYBUFFERREGION", // 7
"COPYTEXTUREREGION", // 8
"COPYRESOURCE", // 9
"COPYTILES", // 10
"RESOLVESUBRESOURCE", // 11
"CLEARRENDERTARGETVIEW", // 12
"CLEARUNORDEREDACCESSVIEW", // 13
"CLEARDEPTHSTENCILVIEW", // 14
"RESOURCEBARRIER", // 15
"EXECUTEBUNDLE", // 16
"PRESENT", // 17
"RESOLVEQUERYDATA", // 18
"BEGINSUBMISSION", // 19
"ENDSUBMISSION", // 20
"DECODEFRAME", // 21
"PROCESSFRAMES", // 22
"ATOMICCOPYBUFFERUINT", // 23
"ATOMICCOPYBUFFERUINT64", // 24
"RESOLVESUBRESOURCEREGION", // 25
"WRITEBUFFERIMMEDIATE", // 26
"DECODEFRAME1", // 27
"SETPROTECTEDRESOURCESESSION", // 28
"DECODEFRAME2", // 29
"PROCESSFRAMES1", // 30
"BUILDRAYTRACINGACCELERATIONSTRUCTURE", // 31
"EMITRAYTRACINGACCELERATIONSTRUCTUREPOSTBUILDINFO", // 32
"COPYRAYTRACINGACCELERATIONSTRUCTURE", // 33
"DISPATCHRAYS", // 34
"INITIALIZEMETACOMMAND", // 35
"EXECUTEMETACOMMAND", // 36
"ESTIMATEMOTION", // 37
"RESOLVEMOTIONVECTORHEAP", // 38
"SETPIPELINESTATE1", // 39
"INITIALIZEEXTENSIONCOMMAND", // 40
"EXECUTEEXTENSIONCOMMAND", // 41
"DISPATCHMESH", // 42
};
// アロケーションタイプテーブル.
static const AllocationTypeTable g_AllocationTypeTable[] = {
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_QUEUE , "COMMAND_QUEUE" }, // 19
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_ALLOCATOR , "COMMAND_ALLOCATOR" }, // 20
{ D3D12_DRED_ALLOCATION_TYPE_PIPELINE_STATE , "PIPELINE_STATE" }, // 21
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_LIST , "COMMAND_LIST" }, // 22
{ D3D12_DRED_ALLOCATION_TYPE_FENCE , "FENCE" }, // 23
{ D3D12_DRED_ALLOCATION_TYPE_DESCRIPTOR_HEAP , "DESCRIPTOR_HEAP" }, // 24
{ D3D12_DRED_ALLOCATION_TYPE_HEAP , "HEAP" }, // 25
{ D3D12_DRED_ALLOCATION_TYPE_QUERY_HEAP , "QUERY_HEAP" }, // 27
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_SIGNATURE , "COMMAND_SIGNATURE" }, // 28
{ D3D12_DRED_ALLOCATION_TYPE_PIPELINE_LIBRARY , "PIPELINE_LIBRARY" }, // 29
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER , "VIDEO_DECODER" }, // 30
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_PROCESSOR , "VIDEO_PROCESSOR" }, // 32
{ D3D12_DRED_ALLOCATION_TYPE_RESOURCE , "RESOURCE" }, // 34
{ D3D12_DRED_ALLOCATION_TYPE_PASS , "PASS" }, // 35
{ D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSION , "CRYPTOSESSION" }, // 36
{ D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSIONPOLICY , "CRYPTOSESSIONPOLICY" }, // 37
{ D3D12_DRED_ALLOCATION_TYPE_PROTECTEDRESOURCESESSION , "PROTECTEDRESOURCESESSION" }, // 38
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER_HEAP , "VIDEO_DECODER_HEAP" }, // 39
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_POOL , "COMMAND_POOL" }, // 40
{ D3D12_DRED_ALLOCATION_TYPE_COMMAND_RECORDER , "COMMAND_RECORDER" }, // 41
{ D3D12_DRED_ALLOCATION_TYPE_STATE_OBJECT , "STATE_OBJECT" }, // 42
{ D3D12_DRED_ALLOCATION_TYPE_METACOMMAND , "METACOMMAND" }, // 43
{ D3D12_DRED_ALLOCATION_TYPE_SCHEDULINGGROUP , "SCHEDULINGGROUP" }, // 44
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_ESTIMATOR , "VIDEO_MOTION_ESTIMATOR" }, // 45
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_VECTOR_HEAP , "VIDEO_MOTION_VECTOR_HEAP" }, // 46
{ D3D12_DRED_ALLOCATION_TYPE_VIDEO_EXTENSION_COMMAND , "VIDEO_EXTENSION_COMMAND" }, // 47
{ D3D12_DRED_ALLOCATION_TYPE_INVALID , "INVALID" }, // 0xffffffff
};
//-----------------------------------------------------------------------------
// 領域の交差を計算します.
//-----------------------------------------------------------------------------
inline int ComputeIntersectionArea
(
int ax1, int ay1,
int ax2, int ay2,
int bx1, int by1,
int bx2, int by2
)
{
return asdx::Max(0, asdx::Min(ax2, bx2) - asdx::Max(ax1, bx1))
* asdx::Max(0, asdx::Min(ay2, by2) - asdx::Max(ay1, by1));
}
//-----------------------------------------------------------------------------
// nullptrかどうかを考慮してdeleteします.
//-----------------------------------------------------------------------------
template<typename T>
void SafeDelete(T*& ptr)
{
if (ptr != nullptr)
{
delete ptr;
ptr = nullptr;
}
}
//-----------------------------------------------------------------------------
// nullptrかどうかを考慮してdelete[]します.
//-----------------------------------------------------------------------------
template<typename T>
void SafeDeleteArray(T*& ptr)
{
if (ptr != nullptr)
{
delete[] ptr;
ptr = nullptr;
}
}
//-----------------------------------------------------------------------------
// nullptrかどうかを考慮して解放処理を行います.
//-----------------------------------------------------------------------------
template<typename T>
void SafeRelease(T*& ptr)
{
if (ptr != nullptr)
{
ptr->Release();
ptr = nullptr;
}
}
//-----------------------------------------------------------------------------
// 色度を変換した値を取得します.
//-----------------------------------------------------------------------------
inline UINT GetCoord(float value)
{ return static_cast<UINT>(value * 50000.0f); }
//-----------------------------------------------------------------------------
// 輝度を変換した値を取得します.
//-----------------------------------------------------------------------------
inline UINT GetLuma(float value)
{ return static_cast<UINT>(value * 10000.0f); }
//-----------------------------------------------------------------------------
// D3D12_AUTO_BREADCRUMB_OPに対応する文字列を取得します.
//-----------------------------------------------------------------------------
const char* ToString(D3D12_AUTO_BREADCRUMB_OP value)
{ return g_BreadcrumTable[value]; }
//-----------------------------------------------------------------------------
// D3D12_DREAD_ALLOCATION_TYPEに対応する文字列を取得します.
//-----------------------------------------------------------------------------
const char* ToString(D3D12_DRED_ALLOCATION_TYPE value)
{
auto count = sizeof(g_AllocationTypeTable) / sizeof(g_AllocationTypeTable[0]);
for(auto i=0; i<count; ++i)
{
if (value == g_AllocationTypeTable[i].Type)
{ return g_AllocationTypeTable[i].Tag; }
}
// バージョンアップとかで列挙体が増えた場合にここに来る可能性がある.
return "UNKNOWN";
}
//-----------------------------------------------------------------------------
// ログ出力を行います.
//-----------------------------------------------------------------------------
void OutputLog(const D3D12_AUTO_BREADCRUMB_NODE1* pNode)
{
if (pNode == nullptr)
{ return; }
ILOGA("Breadcrumb Node 0x%x :", pNode);
ILOGA(" pCommandListDebugNameA = %s" , pNode->pCommandListDebugNameA);
ILOGW(" pCommandListDebugNameW = %ls" , pNode->pCommandListDebugNameW);
ILOGA(" pCommandQueueDebugNameA = %s" , pNode->pCommandQueueDebugNameA);
ILOGW(" pCommandQueueDebugNameW = %ls" , pNode->pCommandQueueDebugNameW);
ILOGA(" pCommandList = 0x%x" , pNode->pCommandList);
ILOGA(" pCommandQueue = 0x%x" , pNode->pCommandQueue);
ILOGA(" BreadcrumbCount = %u" , pNode->BreadcrumbCount);
ILOGA(" BreadcrumbContextCount = %u" , pNode->BreadcrumbContextsCount);
ILOGA(" pLastBreadcrumbValue = 0x%x (%u)", pNode->pLastBreadcrumbValue, *pNode->pLastBreadcrumbValue);
ILOGA(" pCommandHistory : ");
for(auto i=0u; i<pNode->BreadcrumbCount; ++i)
{ ILOGA(" %c Op[%u] = %s", ((i == *pNode->pLastBreadcrumbValue) ? '*' : ' '), i, ToString(pNode->pCommandHistory[i])); }
for(auto i=0u; i<pNode->BreadcrumbContextsCount; ++i)
{
auto ctx = pNode->pBreadcrumbContexts[i];
ILOGA(" Bredcrumb index = %u, string = %ls", ctx.BreadcrumbIndex, ctx.pContextString);
}
ILOGA(" pNext = 0x%x" , pNode->pNext);
}
//-----------------------------------------------------------------------------
// ログ出力を行います.
//-----------------------------------------------------------------------------
void OutputLog(const D3D12_DRED_ALLOCATION_NODE1* pNode)
{
if (pNode == nullptr)
{ return; }
ILOGA("Allocation Node 0x%x : " , pNode);
ILOGA(" ObjectNameA = %s" , pNode->ObjectNameA);
ILOGW(" ObjectNameW = %ls" , pNode->ObjectNameW);
ILOGA(" AllcationType = %s" , ToString(pNode->AllocationType));
ILOGA(" pNext = 0x%x", pNode->pNext);
}
//-----------------------------------------------------------------------------
// デバイス削除にエラーメッセージを表示します.
//-----------------------------------------------------------------------------
void DeviceRemovedHandler(ID3D12Device* pDevice)
{
asdx::RefPtr<ID3D12DeviceRemovedExtendedData1> pDred;
auto hr = pDevice->QueryInterface(IID_PPV_ARGS(pDred.GetAddress()));
if (FAILED(hr))
{
ELOG("Error : ID3D12Device::QueryInterface() Failed. errcode = 0x%x", hr);
return;
}
D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 autoBreadcrumbsOutput = {};
hr = pDred->GetAutoBreadcrumbsOutput1(&autoBreadcrumbsOutput);
if (SUCCEEDED(hr))
{
auto pNode = autoBreadcrumbsOutput.pHeadAutoBreadcrumbNode;
while(pNode != nullptr)
{
OutputLog(pNode);
pNode = pNode->pNext;
}
}
D3D12_DRED_PAGE_FAULT_OUTPUT1 pageFaultOutput = {};
hr = pDred->GetPageFaultAllocationOutput1(&pageFaultOutput);
if (SUCCEEDED(hr))
{
auto pNode = pageFaultOutput.pHeadRecentFreedAllocationNode;
while(pNode != nullptr)
{
OutputLog(pNode);
pNode = pNode->pNext;
}
pNode = pageFaultOutput.pHeadExistingAllocationNode;
while(pNode != nullptr)
{
OutputLog(pNode);
pNode = pNode->pNext;
}
}
}
//-----------------------------------------------------------------------------
// sRGBフォーマットかどうかチェックします.
//-----------------------------------------------------------------------------
bool IsSRGBFormat(DXGI_FORMAT value)
{
bool result = false;
switch(value)
{
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_BC1_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_BC2_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_BC3_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
{ result = true; }
break;
case DXGI_FORMAT_BC7_UNORM_SRGB:
{ result = true; }
break;
}
return result;
}
//-----------------------------------------------------------------------------
// 非sRGBフォーマットに変換します.
//-----------------------------------------------------------------------------
DXGI_FORMAT GetNoSRGBFormat(DXGI_FORMAT value)
{
DXGI_FORMAT result = value;
switch( value )
{
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
{ result = DXGI_FORMAT_R8G8B8A8_UNORM; }
break;
case DXGI_FORMAT_BC1_UNORM_SRGB:
{ result = DXGI_FORMAT_BC1_UNORM; }
break;
case DXGI_FORMAT_BC2_UNORM_SRGB:
{ result = DXGI_FORMAT_BC2_UNORM; }
break;
case DXGI_FORMAT_BC3_UNORM_SRGB:
{ result = DXGI_FORMAT_BC3_UNORM; }
break;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
{ result = DXGI_FORMAT_B8G8R8A8_UNORM; }
break;
case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
{ result = DXGI_FORMAT_B8G8R8X8_UNORM; }
break;
case DXGI_FORMAT_BC7_UNORM_SRGB:
{ result = DXGI_FORMAT_BC7_UNORM; }
break;
}
return result;
}
} // namespace /* anonymous */
namespace asdx {
// ウィンドウクラス名です.
#ifndef ASDX_WND_CLASSNAME
#define ASDX_WND_CLASSNAME TEXT("asdxWindowClass")
#endif//ASDX_WND_CLAASNAME
///////////////////////////////////////////////////////////////////////////////////////////////////
// Application class
///////////////////////////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// コンストラクタです.
//-----------------------------------------------------------------------------
Application::Application()
: m_hInst ( nullptr )
, m_hWnd ( nullptr )
, m_AllowTearing ( false )
, m_MultiSampleCount ( 1 )
, m_MultiSampleQuality ( 0 )
, m_SwapChainCount ( 2 )
, m_SwapChainFormat ( DXGI_FORMAT_R10G10B10A2_UNORM )
, m_DepthStencilFormat ( DXGI_FORMAT_D32_FLOAT )
, m_pSwapChain4 ( nullptr )
, m_SampleMask ( 0 )
, m_StencilRef ( 0 )
, m_Width ( 960 )
, m_Height ( 540 )
, m_AspectRatio ( 1.7777f )
, m_Title ( L"asdxApplication" )
, m_Timer ()
, m_FrameCount ( 0 )
, m_FPS ( 0.0f )
, m_LatestUpdateTime ( 0.0f )
, m_IsStopRendering ( false )
, m_IsStandbyMode ( false )
, m_hIcon ( nullptr )
, m_hMenu ( nullptr )
, m_hAccel ( nullptr )
{
// Corn Flower Blue.
m_ClearColor[0] = 0.392156899f;
m_ClearColor[1] = 0.584313750f;
m_ClearColor[2] = 0.929411829f;
m_ClearColor[3] = 1.000000000f;
m_DeviceDesc.EnableDebug = ASDX_DEV_VAR(true, false);
m_DeviceDesc.MaxColorTargetCount = 128;
m_DeviceDesc.MaxDepthTargetCount = 128;
m_DeviceDesc.MaxSamplerCount = 128;
m_DeviceDesc.MaxShaderResourceCount = 4096;
}
//-----------------------------------------------------------------------------
// 引数付きコンストラクタです.
//-----------------------------------------------------------------------------
Application::Application( LPCWSTR title, UINT width, UINT height, HICON hIcon, HMENU hMenu, HACCEL hAccel )
: m_hInst ( nullptr )
, m_hWnd ( nullptr )
, m_AllowTearing ( false )
, m_MultiSampleCount ( 1 )
, m_MultiSampleQuality ( 0 )
, m_SwapChainCount ( 2 )
, m_SwapChainFormat ( DXGI_FORMAT_R10G10B10A2_UNORM )
, m_DepthStencilFormat ( DXGI_FORMAT_D32_FLOAT )
, m_pSwapChain4 ( nullptr )
, m_Width ( width )
, m_Height ( height )
, m_AspectRatio ( (float)width/(float)height )
, m_Title ( title )
, m_Timer ()
, m_FrameCount ( 0 )
, m_FPS ( 0.0f )
, m_LatestUpdateTime ( 0.0f )
, m_IsStopRendering ( false )
, m_IsStandbyMode ( false )
, m_hIcon ( hIcon )
, m_hMenu ( hMenu )
{
// Corn Flower Blue.
m_ClearColor[0] = 0.392156899f;
m_ClearColor[1] = 0.584313750f;
m_ClearColor[2] = 0.929411829f;
m_ClearColor[3] = 1.000000000f;
m_DeviceDesc.EnableDebug = ASDX_DEV_VAR(true, false);
m_DeviceDesc.MaxColorTargetCount = 128;
m_DeviceDesc.MaxDepthTargetCount = 128;
m_DeviceDesc.MaxSamplerCount = 128;
m_DeviceDesc.MaxShaderResourceCount = 4096;
}
//-----------------------------------------------------------------------------
// デストラクタです.
//-----------------------------------------------------------------------------
Application::~Application()
{ TermApp(); }
//-----------------------------------------------------------------------------
// 描画停止フラグを設定します.
//-----------------------------------------------------------------------------
void Application::SetStopRendering( bool isStopRendering )
{
std::lock_guard<std::mutex> locker(m_Mutex);
m_IsStopRendering = isStopRendering;
}
//-----------------------------------------------------------------------------
// 描画停止フラグを取得します.
//-----------------------------------------------------------------------------
bool Application::IsStopRendering()
{
std::lock_guard<std::mutex> locker(m_Mutex);
return m_IsStopRendering;
}
//-----------------------------------------------------------------------------
// フレームカウントを取得します.
//-----------------------------------------------------------------------------
DWORD Application::GetFrameCount()
{
std::lock_guard<std::mutex> locker(m_Mutex);
return m_FrameCount;
}
//-----------------------------------------------------------------------------
// FPSを取得します.
//-----------------------------------------------------------------------------
FLOAT Application::GetFPS()
{
std::lock_guard<std::mutex> locker(m_Mutex);
return m_FPS;
}
//-----------------------------------------------------------------------------
// アプリケーションを初期化します.
//-----------------------------------------------------------------------------
bool Application::InitApp()
{
// COMライブラリの初期化.
HRESULT hr = CoInitialize( nullptr );
if ( FAILED(hr) )
{
DLOG( "Error : Com Library Initialize Failed." );
return false;
}
// COMライブラリのセキュリティレベルを設定.
hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL);
// セキュリティ設定の結果をチェック.
if ( FAILED(hr) )
{
DLOG( "Error : Com Library Initialize Security Failed." );
return false;
}
// ウィンドウの初期化.
if ( !InitWnd() )
{
DLOG( "Error : InitWnd() Failed." );
return false;
}
// Direct3Dの初期化.
if ( !InitD3D() )
{
DLOG( "Error : InitD3D() Failed." );
return false;
}
// アプリケーション固有の初期化.
if ( !OnInit() )
{
ELOG( "Error : OnInit() Failed." );
return false;
}
// ウィンドウを表示します.
ShowWindow( m_hWnd, SW_SHOWNORMAL );
UpdateWindow( m_hWnd );
// フォーカスを設定します.
SetFocus( m_hWnd );
// 正常終了.
return true;
}
//-----------------------------------------------------------------------------
// アプリケーションの終了処理.
//-----------------------------------------------------------------------------
void Application::TermApp()
{
// コマンドの完了を待機.
SystemWaitIdle();
// アプリケーション固有の終了処理.
OnTerm();
// Direct3Dの終了処理.
TermD3D();
// ウィンドウの終了処理.
TermWnd();
// COMライブラリの終了処理.
CoUninitialize();
}
//-----------------------------------------------------------------------------
// ウィンドウの初期化処理.
//-----------------------------------------------------------------------------
bool Application::InitWnd()
{
// インスタンスハンドルを取得.
HINSTANCE hInst = GetModuleHandle( nullptr );
if ( !hInst )
{
DLOG( "Error : GetModuleHandle() Failed. ");
return false;
}
// アイコンなしの場合はロード.
if ( m_hIcon == nullptr )
{
// 最初にみつかったものをアイコンとして設定する.
WCHAR exePath[MAX_PATH];
GetModuleFileName( NULL, exePath, MAX_PATH );
m_hIcon = ExtractIcon( hInst, exePath, 0 );
// それでも見つからなった場合.
if (m_hIcon == nullptr)
{ m_hIcon = LoadIcon( hInst, IDI_APPLICATION ); }
}
// 拡張ウィンドウクラスの設定.
WNDCLASSEXW wc;
wc.cbSize = sizeof( WNDCLASSEXW );
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MsgProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = m_hIcon;
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)( COLOR_WINDOW + 1 );
wc.lpszMenuName = NULL;
wc.lpszClassName = ASDX_WND_CLASSNAME;
wc.hIconSm = m_hIcon;
// ウィンドウクラスを登録します.
if ( !RegisterClassExW( &wc ) )
{
// エラーログ出力.
DLOG( "Error : RegisterClassEx() Failed." );
// 異常終了.
return false;
}
// インスタンスハンドルを設定.
m_hInst = hInst;
// 矩形の設定.
RECT rc = { 0, 0, static_cast<LONG>(m_Width), static_cast<LONG>(m_Height) };
#if 0 // リサイズしたくない場合.
//DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX;
#else // リサイズ許可.
DWORD style = WS_OVERLAPPEDWINDOW;
#endif
// 指定されたクライアント領域を確保するために必要なウィンドウ座標を計算します.
AdjustWindowRect( &rc, style, FALSE );
// ウィンドウを生成します.
m_hWnd = CreateWindowW(
ASDX_WND_CLASSNAME,
m_Title,
style,
CW_USEDEFAULT,
CW_USEDEFAULT,
( rc.right - rc.left ),
( rc.bottom - rc.top ),
NULL,
m_hMenu,
hInst,
NULL
);
// 生成チェック.
if ( !m_hWnd )
{
// エラーログ出力.
DLOG( "Error : CreateWindow() Failed." );
// 異常終了.
return false;
}
// アプリケーションリストに登録します.
g_AppList.PushBack( this );
// タイマーを開始します.
m_Timer.Start();
// 開始時刻を取得.
m_LatestUpdateTime = m_Timer.GetElapsedSec();
// 正常終了.
return true;
}
//-----------------------------------------------------------------------------
// ウィンドウの終了処理.
//-----------------------------------------------------------------------------
void Application::TermWnd()
{
// タイマーを止めます.
m_Timer.Stop();
// ウィンドウクラスの登録を解除.
if ( m_hInst != nullptr )
{ UnregisterClass( ASDX_WND_CLASSNAME, m_hInst ); }
if ( m_hAccel )
{ DestroyAcceleratorTable( m_hAccel ); }
if ( m_hMenu )
{ DestroyMenu( m_hMenu ); }
if ( m_hIcon )
{ DestroyIcon( m_hIcon ); }
// タイトル名をクリア.
m_Title = nullptr;
// ハンドルをクリア.
m_hInst = nullptr;
m_hWnd = nullptr;
m_hIcon = nullptr;
m_hMenu = nullptr;
m_hAccel = nullptr;
// アプリケーションリストから削除します.
g_AppList.Remove( this );
}
//-----------------------------------------------------------------------------
// Direct3Dの初期化処理.
//-----------------------------------------------------------------------------
bool Application::InitD3D()
{
HRESULT hr = S_OK;
// ウィンドウサイズを取得します.
RECT rc;
GetClientRect( m_hWnd, &rc );
UINT w = rc.right - rc.left;
UINT h = rc.bottom - rc.top;
// 取得したサイズを設定します.
m_Width = w;
m_Height = h;
// アスペクト比を算出します.
m_AspectRatio = (FLOAT)w / (FLOAT)h;
// デバイスの初期化.
if (!SystemInit(m_DeviceDesc))
{
ELOG("Error : GraphicsDeivce::Init() Failed.");
return false;
}
auto isSRGB = IsSRGBFormat(m_SwapChainFormat);
// スワップチェインの初期化
{
DXGI_RATIONAL refreshRate;
GetDisplayRefreshRate(refreshRate);
// スワップチェインの構成設定.
DXGI_SWAP_CHAIN_DESC1 desc = {};
desc.Width = w;
desc.Height = h;
desc.Format = GetNoSRGBFormat(m_SwapChainFormat);
desc.Stereo = FALSE;
desc.SampleDesc.Count = m_MultiSampleCount;
desc.SampleDesc.Quality = m_MultiSampleQuality;
desc.BufferCount = m_SwapChainCount;
desc.Scaling = DXGI_SCALING_STRETCH;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
desc.Flags = (m_AllowTearing) ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc = {};
fullScreenDesc.RefreshRate = refreshRate;
fullScreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
fullScreenDesc.Scaling = DXGI_MODE_SCALING_STRETCHED;
fullScreenDesc.Windowed = TRUE;
RefPtr<IDXGISwapChain1> pSwapChain1;
auto pQueue = GetGraphicsQueue()->GetQueue();
hr = GetDXGIFactory()->CreateSwapChainForHwnd(pQueue, m_hWnd, &desc, &fullScreenDesc, nullptr, pSwapChain1.GetAddress());
if (FAILED(hr))
{
ELOG("Error : IDXGIFactory2::CreateSwapChainForHwnd() Failed. errcode = 0x%x", hr);
return false;
}
if (m_AllowTearing)
{ GetDXGIFactory()->MakeWindowAssociation(m_hWnd, DXGI_MWA_NO_ALT_ENTER); }
// IDXGISwapChain4にキャスト.
hr = pSwapChain1->QueryInterface(IID_PPV_ARGS(m_pSwapChain4.GetAddress()));
if ( FAILED( hr ) )
{
m_pSwapChain4.Reset();
ELOG( "Warning : IDXGISwapChain4 Conversion Faild.");
return false;
}
else
{
wchar_t name[] = L"asdxSwapChain4\0";
m_pSwapChain4->SetPrivateData(WKPDID_D3DDebugObjectNameW, sizeof(name), name);
// HDR出力チェック.
CheckSupportHDR();
}
}
// カラーターゲットの初期化.
{
m_ColorTarget.resize(m_SwapChainCount);
for(auto i=0u; i<m_SwapChainCount; ++i)
{
if (!m_ColorTarget[i].Init(m_pSwapChain4.GetPtr(), i, isSRGB))
{
ELOG("Error : ColorTarget::Init() Failed.");
return false;
}
}
}
// 深度ターゲットの初期化.
{
TargetDesc desc;
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
desc.Alignment = 0;
desc.Width = w;
desc.Height = h;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = m_DepthStencilFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.InitState = D3D12_RESOURCE_STATE_DEPTH_WRITE;
if (!m_DepthTarget.Init(&desc))
{
ELOG("Error : DepthTarget::Init() Failed.");
return false;
}
}
if (!m_GfxCmdList.Init(GetD3D12Device(), D3D12_COMMAND_LIST_TYPE_DIRECT))
{
ELOG("Error : CommandList::Init() Failed.");
return false;
}
if (!m_CopyCmdList.Init(GetD3D12Device(), D3D12_COMMAND_LIST_TYPE_COPY))
{
ELOG("Error : CommandList::Init() Failed.");
return false;
}
// ビューポートの設定.
m_Viewport.Width = (FLOAT)w;
m_Viewport.Height = (FLOAT)h;
m_Viewport.MinDepth = 0.0f;
m_Viewport.MaxDepth = 1.0f;
m_Viewport.TopLeftX = 0;
m_Viewport.TopLeftY = 0;
// シザー矩形の設定.
m_ScissorRect.left = 0;
m_ScissorRect.right = w;
m_ScissorRect.top = 0;
m_ScissorRect.bottom = h;
return true;
}
//-----------------------------------------------------------------------------
// Direct3Dの終了処理.
//-----------------------------------------------------------------------------
void Application::TermD3D()
{
for(size_t i=0; i<m_ColorTarget.size(); ++i)
{
m_ColorTarget[i].Term();
}
m_ColorTarget.clear();
m_DepthTarget.Term();
m_pSwapChain4.Reset();
m_CopyCmdList.Term();
m_GfxCmdList.Term();
SystemTerm();
}
//-----------------------------------------------------------------------------
// メインループ処理.
//-----------------------------------------------------------------------------
void Application::MainLoop()
{
MSG msg = { 0 };
FrameEventArgs frameEventArgs;
auto frameCount = 0;
while( WM_QUIT != msg.message )
{
auto gotMsg = PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE );
if ( gotMsg )
{
auto ret = TranslateAccelerator( m_hWnd, m_hAccel, &msg );
if ( 0 == ret )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
double time;
double absTime;
double elapsedTime;
// 時間を取得.
m_Timer.GetValues( time, absTime, elapsedTime );
// 0.5秒ごとにFPSを更新.
auto interval = float( time - m_LatestUpdateTime );
if ( interval > 0.5 )
{
// FPSを算出.
m_FPS = frameCount / interval;
// 更新時間を設定.
m_LatestUpdateTime = time;
frameCount = 0;
}
frameEventArgs.FPS = 1.0f / (float)elapsedTime; // そのフレームにおけるFPS.
frameEventArgs.Time = time;
frameEventArgs.ElapsedTime = elapsedTime;
frameEventArgs.IsStopDraw = m_IsStopRendering;
// フレーム遷移処理.
OnFrameMove( frameEventArgs );
// 描画停止フラグが立っていない場合.
if ( !IsStopRendering() )
{
// フレーム描画処理.
OnFrameRender( frameEventArgs );
// フレームカウントをインクリメント.
m_FrameCount++;
}
frameCount++;
}
}
}
//-----------------------------------------------------------------------------
// アプリケーションを実行します.
//-----------------------------------------------------------------------------
void Application::Run()
{
// アプリケーションの初期化処理.
if ( InitApp() )
{
// メインループ処理.
MainLoop();
}
// アプリケーションの終了処理.
TermApp();
}
//-----------------------------------------------------------------------------
// キーイベント処理.
//-----------------------------------------------------------------------------
void Application::KeyEvent( const KeyEventArgs& param )
{
// キーイベント呼び出し.
OnKey( param );
}
//-----------------------------------------------------------------------------
// リサイズイベント処理.
//-----------------------------------------------------------------------------
void Application::ResizeEvent( const ResizeEventArgs& param )
{
if (m_pSwapChain4.GetPtr() == nullptr)
{ return; }
if (m_ColorTarget.empty())
{ return; }
if (m_DepthTarget.GetResource() == nullptr)
{ return; }
// マルチサンプル数以下になるとハングすることがあるので,処理をスキップする.
if ( param.Width <= m_MultiSampleCount
|| param.Height <= m_MultiSampleCount)
{ return; }
m_Width = param.Width;
m_Height = param.Height;
m_AspectRatio = param.AspectRatio;
// ビューポートの設定.
m_Viewport.Width = (FLOAT)m_Width;
m_Viewport.Height = (FLOAT)m_Height;
m_Viewport.MinDepth = 0.0f;
m_Viewport.MaxDepth = 1.0f;
m_Viewport.TopLeftX = 0;
m_Viewport.TopLeftY = 0;
// シザー矩形の設定.
m_ScissorRect.left = 0;
m_ScissorRect.right = m_Width;
m_ScissorRect.top = 0;
m_ScissorRect.bottom = m_Height;
if ( m_pSwapChain4 != nullptr )
{
// コマンドの完了を待機.
SystemWaitIdle();
// 描画ターゲットを解放.
for(size_t i=0; i<m_ColorTarget.size(); ++i)
{ m_ColorTarget[i].Term(); }
// 深度ステンシルバッファを解放.
m_DepthTarget.Term();
// 強制破棄.
ClearDisposer();
HRESULT hr = S_OK;
auto isSRGB = IsSRGBFormat(m_SwapChainFormat);
auto format = GetNoSRGBFormat(m_SwapChainFormat);
// バッファをリサイズ.
hr = m_pSwapChain4->ResizeBuffers( m_SwapChainCount, m_Width, m_Height, format, 0 );
if ( FAILED( hr ) )
{ DLOG( "Error : IDXGISwapChain::ResizeBuffer() Failed. errcode = 0x%x", hr ); }
for(auto i=0u; i<m_SwapChainCount; ++i)
{
if (!m_ColorTarget[i].Init(m_pSwapChain4.GetPtr(), i, isSRGB))
{ DLOG("Error : ColorTarget::Init() Failed."); }
}
TargetDesc desc;
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
desc.Alignment = 0;
desc.Width = m_Width;
desc.Height = m_Height;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = m_DepthStencilFormat;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.InitState = D3D12_RESOURCE_STATE_DEPTH_WRITE;
if ( !m_DepthTarget.Init(&desc))
{ DLOG( "Error : DepthStencilTarget::Create() Failed." ); }
}
// リサイズイベント呼び出し.
OnResize( param );
}
//-----------------------------------------------------------------------------
// マウスイベント処理.
//-----------------------------------------------------------------------------
void Application::MouseEvent( const MouseEventArgs& param )
{ OnMouse( param ); }
//-----------------------------------------------------------------------------
// ドロップイベント処理.
//------------------------------------------------------------------------------
void Application::DropEvent( const wchar_t** dropFiles, uint32_t fileNum )
{ OnDrop( dropFiles, fileNum ); }
//-----------------------------------------------------------------------------
// ウィンドウプロシージャ.
//-----------------------------------------------------------------------------
LRESULT CALLBACK Application::MsgProc( HWND hWnd, UINT uMsg, WPARAM wp, LPARAM lp )
{
PAINTSTRUCT ps;
HDC hdc;
if ( ( uMsg == WM_KEYDOWN )
|| ( uMsg == WM_SYSKEYDOWN )
|| ( uMsg == WM_KEYUP )
|| ( uMsg == WM_SYSKEYUP ) )
{
bool isKeyDown = ( uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN );
DWORD mask = ( 1 << 29 );
bool isAltDown =( ( lp & mask ) != 0 );
KeyEventArgs args;
args.KeyCode = uint32_t( wp );
args.IsAltDown = isAltDown;
args.IsKeyDown = isKeyDown;
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->KeyEvent( args );
}
}
// 古いWM_MOUSEWHEELの定義.
const UINT OLD_WM_MOUSEWHEEL = 0x020A;
if ( ( uMsg == WM_LBUTTONDOWN )
|| ( uMsg == WM_LBUTTONUP )
|| ( uMsg == WM_LBUTTONDBLCLK )
|| ( uMsg == WM_MBUTTONDOWN )
|| ( uMsg == WM_MBUTTONUP )
|| ( uMsg == WM_MBUTTONDBLCLK )
|| ( uMsg == WM_RBUTTONDOWN )
|| ( uMsg == WM_RBUTTONUP )
|| ( uMsg == WM_RBUTTONDBLCLK )
|| ( uMsg == WM_XBUTTONDOWN )
|| ( uMsg == WM_XBUTTONUP )
|| ( uMsg == WM_XBUTTONDBLCLK )
|| ( uMsg == WM_MOUSEHWHEEL ) // このWM_MOUSEWHEELは0x020Eを想定.
|| ( uMsg == WM_MOUSEMOVE )
|| ( uMsg == OLD_WM_MOUSEWHEEL ) )
{
int x = (short)LOWORD( lp );
int y = (short)HIWORD( lp );
int wheelDelta = 0;
if ( ( uMsg == WM_MOUSEHWHEEL )
|| ( uMsg == OLD_WM_MOUSEWHEEL ) )
{
POINT pt;
pt.x = x;
pt.y = y;
ScreenToClient( hWnd, &pt );
x = pt.x;
y = pt.y;
wheelDelta += (short)HIWORD( wp );
}
int buttonState = LOWORD( wp );
bool isLeftButtonDown = ( ( buttonState & MK_LBUTTON ) != 0 );
bool isRightButtonDown = ( ( buttonState & MK_RBUTTON ) != 0 );
bool isMiddleButtonDown = ( ( buttonState & MK_MBUTTON ) != 0 );
bool isSideButton1Down = ( ( buttonState & MK_XBUTTON1 ) != 0 );
bool isSideButton2Down = ( ( buttonState & MK_XBUTTON2 ) != 0 );
MouseEventArgs args;
args.X = x;
args.Y = y;
args.IsLeftButtonDown = isLeftButtonDown;
args.IsMiddleButtonDown = isMiddleButtonDown;
args.IsRightButtonDown = isRightButtonDown;
args.IsSideButton1Down = isSideButton1Down;
args.IsSideButton2Down = isSideButton2Down;
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->MouseEvent( args );
}
}
switch( uMsg )
{
case WM_CREATE:
{
// ドラッグアンドドロップ可能.
DragAcceptFiles(hWnd, TRUE);
}
break;
case WM_PAINT:
{
hdc = BeginPaint( hWnd, &ps );
EndPaint( hWnd, &ps );
}
break;
case WM_DESTROY:
{ PostQuitMessage( 0 ); }
break;
case WM_SIZE:
{
UINT w = (UINT)LOWORD( lp );
UINT h = (UINT)HIWORD( lp );
// ウインドウ非表示状態に移行する時に縦横1ピクセルのリサイズイベントが発行される
// マルチサンプル等の関係で縦横1ピクセルは問題が起こるので最少サイズを設定
ResizeEventArgs args;
args.Width = asdx::Max( w, (uint32_t)8 );
args.Height = asdx::Max( h, (uint32_t)8 );
args.AspectRatio = float( args.Width ) / args.Height;
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->ResizeEvent( args );
}
}
break;
case WM_DROPFILES:
{
// ドロップされたファイル数を取得.
uint32_t numFiles = DragQueryFileW((HDROP)wp, 0xFFFFFFFF, NULL, 0);
// 作業用のバッファを確保.
const WCHAR** dropFiles = new const WCHAR*[ numFiles ];
for (uint32_t i=0; i < numFiles; i++)
{
// ドロップされたファイル名を取得.
WCHAR* dropFile = new WCHAR[ MAX_PATH ];
DragQueryFileW((HDROP)wp, i, dropFile, MAX_PATH);
dropFiles[ i ] = dropFile;
}
// アプリケーションに通知.
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->DropEvent( dropFiles, numFiles );
}
// 作業用のバッファを解放.
for (uint32_t i=0; i < numFiles; i++)
{ SafeDelete( dropFiles[ i ] ); }
SafeDelete( dropFiles );
DragFinish((HDROP)wp);
}
break;
case WM_MOVE:
{
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->CheckSupportHDR();
}
}
break;
case WM_DISPLAYCHANGE:
{
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->CheckSupportHDR();
}
}
break;
case WM_CHAR:
{
auto keyCode = static_cast<uint32_t>( wp );
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{
(*itr)->OnTyping( keyCode );
}
}
break;
//case MM_MCINOTIFY:
// {
// // サウンドマネージャのコールバック.
// SndMgr::GetInstance().OnNofity( (uint32_t)lp, (uint32_t)wp );
// }
// break;
}
// ユーザーカスタマイズ用に呼び出し.
for( ApplicationList::ListItr itr = g_AppList.Begin(); itr != g_AppList.End(); itr++ )
{ (*itr)->OnMsgProc( hWnd, uMsg, wp, lp ); }
return DefWindowProc( hWnd, uMsg, wp, lp );
}
//-----------------------------------------------------------------------------
// 初期化時の処理.
//-----------------------------------------------------------------------------
bool Application::OnInit()
{
/* DO_NOTHING */
return true;
}
//-----------------------------------------------------------------------------
// 終了時の処理.
//-----------------------------------------------------------------------------
void Application::OnTerm()
{
/* DO_NOTHING */
}
//-----------------------------------------------------------------------------
// フレーム遷移時の処理.
//-----------------------------------------------------------------------------
void Application::OnFrameMove( FrameEventArgs& )
{
/* DO_NOTHING */
}
//-----------------------------------------------------------------------------
// フレーム描画字の処理.
//-----------------------------------------------------------------------------
void Application::OnFrameRender( FrameEventArgs& )
{
/* DO_NOTHING */
}
//-----------------------------------------------------------------------------
// コマンドを実行して,画面に表示します.
//-----------------------------------------------------------------------------
void Application::Present( uint32_t syncInterval )
{
HRESULT hr = S_OK;
// スタンバイモードかどうかチェック.
if ( m_IsStandbyMode )
{
// テストする.
hr = m_pSwapChain4->Present( syncInterval, DXGI_PRESENT_TEST );
// スタンバイモードが解除されたかをチェック.
if ( hr == S_OK )
{ m_IsStandbyMode = false; }
// 処理を中断.
return;
}
// 画面更新する.
hr = m_pSwapChain4->Present( syncInterval, 0 );
switch( hr )
{
// デバイスがリセットされた場合(=コマンドが正しくない場合)
case DXGI_ERROR_DEVICE_RESET:
{
// エラーログ出力.
ELOG( "Fatal Error : IDXGISwapChain::Present() Failed. ErrorCode = DXGI_ERROR_DEVICE_RESET." );
// エラー表示.
DeviceRemovedHandler(GetD3D12Device());
// 続行できないのでダイアログを表示.
MessageBoxW( m_hWnd, L"A Fatal Error Occured. Shutting down.", L"FATAL ERROR", MB_OK | MB_ICONERROR );
// 終了メッセージを送る.
PostQuitMessage( 1 );
}
break;
// デバイスが削除された場合(=GPUがぶっこ抜かれた場合かドライバーアップデート中,またはGPUクラッシュ時.)
case DXGI_ERROR_DEVICE_REMOVED:
{
// エラーログ出力.
ELOG( "Fatal Error : IDXGISwapChain::Present() Failed. ErrorCode = DXGI_ERROR_DEVICE_REMOVED." );
// エラー表示.
DeviceRemovedHandler(GetD3D12Device());
// 続行できないのでダイアログを表示.
MessageBoxW( m_hWnd, L"A Fatal Error Occured. Shutting down.", L"FATAL ERROR", MB_OK | MB_ICONERROR );
// 終了メッセージを送る.
PostQuitMessage( 2 );
}
break;
// 表示領域がなければスタンバイモードに入る.
case DXGI_STATUS_OCCLUDED:
{ m_IsStandbyMode = true; }
break;
// 現在のフレームバッファを表示する場合.
case S_OK:
{ /* DO_NOTHING */ }
break;
}
}
//-----------------------------------------------------------------------------
// ディスプレイがHDR出力をサポートしているかどうかチェックします.
//-----------------------------------------------------------------------------
void Application::CheckSupportHDR()
{
HRESULT hr = S_OK;
// ウィンドウ領域を取得.
RECT rect;
GetWindowRect(m_hWnd, &rect);
RefPtr<IDXGIAdapter1> pAdapter;
hr = GetDXGIFactory()->EnumAdapters1(0, pAdapter.GetAddress());
if (FAILED(hr))
{
ELOG("Error : IDXGIFactory1::EnumAdapters1() Failed.");
return;
}
UINT i = 0;
RefPtr<IDXGIOutput> currentOutput;
RefPtr<IDXGIOutput> bestOutput;
int bestIntersectArea = -1;
// 各ディスプレイを調べる.
while (pAdapter->EnumOutputs(i, currentOutput.ReleaseAndGetAddress()) != DXGI_ERROR_NOT_FOUND)
{
auto ax1 = rect.left;
auto ay1 = rect.top;
auto ax2 = rect.right;
auto ay2 = rect.bottom;
// ディスプレイの設定を取得.
DXGI_OUTPUT_DESC desc;
hr = currentOutput->GetDesc(&desc);
if (FAILED(hr))
{ return; }
auto bx1 = desc.DesktopCoordinates.left;
auto by1 = desc.DesktopCoordinates.top;
auto bx2 = desc.DesktopCoordinates.right;
auto by2 = desc.DesktopCoordinates.bottom;
// 領域が一致するかどうか調べる.
int intersectArea = ComputeIntersectionArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);
if (intersectArea > bestIntersectArea)
{
bestOutput = currentOutput;
bestIntersectArea = intersectArea;
}
i++;
}
// 一番適しているディスプレイ.
RefPtr<IDXGIOutput6> pOutput6;
hr = bestOutput->QueryInterface(IID_PPV_ARGS(pOutput6.GetAddress()));
if (FAILED(hr))
{
ELOG("Error : IDXGIOutput6 Conversion Failed.");
return;
}
// 出力設定を取得.
hr = pOutput6->GetDesc1(&m_DisplayDesc);
if (FAILED(hr))
{
ELOG("Error : IDXGIOutput6::GetDesc() Failed.");
return;
}
// 正常終了.
}
//-----------------------------------------------------------------------------
// HDR出力をサポートしているかどうかチェックします.
//-----------------------------------------------------------------------------
bool Application::IsSupportHDR() const
{ return m_DisplayDesc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; }
//-----------------------------------------------------------------------------
// ディスプレイ設定を取得します.
//-----------------------------------------------------------------------------
DXGI_OUTPUT_DESC1 Application::GetDisplayDesc() const
{ return m_DisplayDesc; }
//-----------------------------------------------------------------------------
// 色空間を設定します
//-----------------------------------------------------------------------------
bool Application::SetColorSpace(COLOR_SPACE value)
{
if (m_pSwapChain4.GetPtr() == nullptr)
{ return false; }
DXGI_HDR_METADATA_HDR10 metaData = {};
DXGI_COLOR_SPACE_TYPE colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
metaData.MinMasteringLuminance = GetLuma(m_DisplayDesc.MinLuminance);
metaData.MaxMasteringLuminance = GetLuma(m_DisplayDesc.MaxLuminance);
switch (value)
{
case COLOR_SPACE_NONE:
{
colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
metaData.RedPrimary[0] = GetCoord(m_DisplayDesc.RedPrimary[0]);
metaData.RedPrimary[1] = GetCoord(m_DisplayDesc.RedPrimary[1]);
metaData.GreenPrimary[0] = GetCoord(m_DisplayDesc.GreenPrimary[0]);
metaData.GreenPrimary[1] = GetCoord(m_DisplayDesc.GreenPrimary[1]);
metaData.BluePrimary[0] = GetCoord(m_DisplayDesc.BluePrimary[0]);
metaData.BluePrimary[1] = GetCoord(m_DisplayDesc.BluePrimary[1]);
metaData.WhitePoint[0] = GetCoord(m_DisplayDesc.WhitePoint[0]);
metaData.WhitePoint[1] = GetCoord(m_DisplayDesc.WhitePoint[1]);
}
break;
case COLOR_SPACE_SRGB:
{
colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
metaData.RedPrimary[0] = GetCoord(0.64000f);
metaData.RedPrimary[1] = GetCoord(0.33000f);
metaData.GreenPrimary[0] = GetCoord(0.30000f);
metaData.GreenPrimary[1] = GetCoord(0.60000f);
metaData.BluePrimary[0] = GetCoord(0.15000f);
metaData.BluePrimary[1] = GetCoord(0.06000f);
metaData.WhitePoint[0] = GetCoord(0.31270f);
metaData.WhitePoint[1] = GetCoord(0.32900f);
}
break;
case COLOR_SPACE_BT709:
{
colorSpace = DXGI_COLOR_SPACE_RGB_STUDIO_G24_NONE_P709;
metaData.RedPrimary[0] = GetCoord(0.64000f);
metaData.RedPrimary[1] = GetCoord(0.33000f);
metaData.GreenPrimary[0] = GetCoord(0.30000f);
metaData.GreenPrimary[1] = GetCoord(0.60000f);
metaData.BluePrimary[0] = GetCoord(0.15000f);
metaData.BluePrimary[1] = GetCoord(0.06000f);
metaData.WhitePoint[0] = GetCoord(0.31270f);
metaData.WhitePoint[1] = GetCoord(0.32900f);
}
break;
case COLOR_SPACE_BT2100_PQ:
{
colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
metaData.RedPrimary[0] = GetCoord(0.70800f);
metaData.RedPrimary[1] = GetCoord(0.29200f);
metaData.GreenPrimary[0] = GetCoord(0.17000f);
metaData.GreenPrimary[1] = GetCoord(0.79700f);
metaData.BluePrimary[0] = GetCoord(0.13100f);
metaData.BluePrimary[1] = GetCoord(0.04600f);
metaData.WhitePoint[0] = GetCoord(0.31270f);
metaData.WhitePoint[1] = GetCoord(0.32900f);
}
break;
case COLOR_SPACE_BT2100_HLG:
{
colorSpace = DXGI_COLOR_SPACE_YCBCR_FULL_GHLG_TOPLEFT_P2020;
metaData.RedPrimary[0] = GetCoord(0.70800f);
metaData.RedPrimary[1] = GetCoord(0.29200f);
metaData.GreenPrimary[0] = GetCoord(0.17000f);
metaData.GreenPrimary[1] = GetCoord(0.79700f);
metaData.BluePrimary[0] = GetCoord(0.13100f);
metaData.BluePrimary[1] = GetCoord(0.04600f);
metaData.WhitePoint[0] = GetCoord(0.31270f);
metaData.WhitePoint[1] = GetCoord(0.32900f);
}
break;
}
UINT flag = 0;
auto hr = m_pSwapChain4->CheckColorSpaceSupport(colorSpace, &flag);
if (FAILED(hr))
{
ELOG("Error : ISwapChain4::CheckColorSpaceSupport() Failed. errcode = 0x%x", hr);
return false;
}
if ((flag & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT) != DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)
{ return false; }
hr = m_pSwapChain4->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metaData), &metaData);
if (FAILED(hr))
{
ELOG("Error : ISwapChain4::SetHDRMetaData() Failed. errcode = 0x%x", hr);
return false;
}
hr = m_pSwapChain4->SetColorSpace1(colorSpace);
if (FAILED(hr))
{
ELOG("Error : ISwapChain4::SetColorSpace1() Failed. errcode = 0x%x", hr);
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// ディスプレイのリフレッシュレートを取得します.
//-----------------------------------------------------------------------------
bool Application::GetDisplayRefreshRate(DXGI_RATIONAL& result) const
{
auto hMonitor = MonitorFromWindow(m_hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFOEX monitorInfo;
monitorInfo.cbSize = sizeof(monitorInfo);
auto ret = GetMonitorInfo(hMonitor, &monitorInfo);
if (ret == 0)
{
ELOG("Error : GetMonitorInfo() Failed.");
return false;
}
DEVMODE devMode;
devMode.dmSize = sizeof(devMode);
devMode.dmDriverExtra = 0;
ret = EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
if (ret == 0)
{
ELOG("Error : EnumDisplaySettings() Failed.");
return false;
}
auto useDefaultRefreshRate = (1 == devMode.dmDisplayFrequency) || (0 == devMode.dmDisplayFrequency);
result.Numerator = (useDefaultRefreshRate) ? 0 : devMode.dmDisplayFrequency;
result.Denominator = (useDefaultRefreshRate) ? 0 : 1;
return true;
}
//-----------------------------------------------------------------------------
// スワップチェインのバックバッファ番号を取得します.
//-----------------------------------------------------------------------------
uint32_t Application::GetCurrentBackBufferIndex() const
{
if (m_pSwapChain4.GetPtr() == nullptr)
{ return 0; }
return m_pSwapChain4->GetCurrentBackBufferIndex();
}
//-----------------------------------------------------------------------------
// リサイズ時の処理.
//-----------------------------------------------------------------------------
void Application::OnResize( const ResizeEventArgs& )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// キーイベント時の処理.
//-----------------------------------------------------------------------------
void Application::OnKey( const KeyEventArgs& )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// マウスイベント時の処理.
//-----------------------------------------------------------------------------
void Application::OnMouse( const MouseEventArgs& )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// タイピングイベント時の処理.
//-----------------------------------------------------------------------------
void Application::OnTyping( uint32_t )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// ドロップ時の処理.
//------------------------------------------------------------------------------
void Application::OnDrop( const wchar_t**, uint32_t )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// メッセージプロシージャの処理.
//-----------------------------------------------------------------------------
void Application::OnMsgProc( HWND, UINT, WPARAM, LPARAM )
{ /* DO_NOTHING */ }
//-----------------------------------------------------------------------------
// フォーカスを持つかどうか判定します.
//-----------------------------------------------------------------------------
bool Application::HasFocus() const
{ return ( GetActiveWindow() == m_hWnd ); }
//------------------------------------------------------------------------------
// スタンバイモードかどうかチェックします.
//------------------------------------------------------------------------------
bool Application::IsStandByMode() const
{ return m_IsStandbyMode; }
} // namespace asdx
| 32.980545 | 132 | 0.450718 | ProjectAsura |
22b7ba5e81d2d7efb9193975d8083bd2b1f7aa24 | 30,303 | cpp | C++ | .References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/acf/GPUACF.cpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | .References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/acf/GPUACF.cpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | .References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/acf/GPUACF.cpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | /*!
@file GPUACF.cpp
@author David Hirvonen
@brief Declaration of OpenGL shader optimized Aggregated Channel Feature computation.
\copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved.
\license{This project is released under the 3 Clause BSD License.}
*/
#include "drishti/acf/GPUACF.h"
#include "ogles_gpgpu/common/proc/grayscale.h"
#include "ogles_gpgpu/common/proc/pyramid.h"
#include "ogles_gpgpu/common/proc/grad.h"
#include "ogles_gpgpu/common/proc/gauss.h"
#include "ogles_gpgpu/common/proc/gauss_opt.h"
#include "ogles_gpgpu/common/proc/transform.h"
#include "ogles_gpgpu/common/proc/tensor.h"
#include "ogles_gpgpu/common/proc/nms.h"
#include "ogles_gpgpu/common/proc/shitomasi.h"
#include "ogles_gpgpu/common/proc/flow.h"
// generic shaders
#include "drishti/graphics/gain.h"
#include "drishti/graphics/swizzle.h"
#include "drishti/graphics/rgb2luv.h"
#include "drishti/graphics/binomial.h"
// acf specific shader
#include "drishti/acf/gpu/swizzle2.h"
#include "drishti/acf/gpu/gradhist.h"
#include "drishti/acf/gpu/triangle.h"
#include "drishti/core/convert.h"
#include "drishti/core/timing.h"
#include "drishti/core/Logger.h"
#include "drishti/core/Parallel.h"
#include "drishti/core/make_unique.h"
#include "ogles_gpgpu/common/gl/memtransfer_optimized.h"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <chrono>
#include <array>
#include <sys/types.h> // for umask()
#include <sys/stat.h> // -/-
// clang-format off
#ifdef ANDROID
# define TEXTURE_FORMAT GL_RGBA
# define TEXTURE_FORMAT_IS_RGBA 1
#else
# define TEXTURE_FORMAT GL_BGRA
# define TEXTURE_FORMAT_IS_RGBA 0
#endif
// clang-format on
#define GPU_ACF_DEBUG_CHANNELS 0
#define DO_INLINE_MERGE 0
BEGIN_OGLES_GPGPU
struct ACF::Impl
{
Impl(void* glContext, const Size2d& size, const SizeVec& scales, FeatureKind kind, int grayWidth, int flowWidth, bool debug)
: m_featureKind(kind)
, m_size(size)
, m_debug(debug)
, m_doGray(grayWidth > 0)
, m_grayscaleScale(float(grayWidth) / float(size.width))
, m_doFlow(flowWidth > 0)
, m_flowScale(float(flowWidth) / float(size.width)) // TODO: not when using pyramid
{
initACF(scales, kind, debug);
if (m_doGray)
{
Size2d graySize(grayWidth, int(m_grayscaleScale * size.height + 0.5f));
reduceRgbSmoothProc = drishti::core::make_unique<ogles_gpgpu::NoopProc>();
reduceRgbSmoothProc->setOutputSize(graySize.width, graySize.height);
rgbSmoothProc->add(reduceRgbSmoothProc.get()); // ### OUTPUT ###
}
if (m_doFlow) // use the same scale as corners:
{
// Compute scale relative to bottom pyramid level in pyramidProc()
float pyramidToFlow = float(flowWidth) / scales[0].width;
// ((( Optical flow )))
flow = drishti::core::make_unique<ogles_gpgpu::FlowOptPipeline>(0.004, 1.0, false);
pyramidProc->add(flow.get());
flow->setOutputSize(pyramidToFlow);
#if TEXTURE_FORMAT_IS_RGBA
flowBgra = drishti::core::make_unique<ogles_gpgpu::SwizzleProc>();
flow->add(flowBgra.get());
flowBgraInterface = flowBgra.get();
#else
flowBgraInterface = flow.get();
#endif
}
if (m_doLuvTransfer)
{
// Add transposed Luv output for CPU processing (optional)
luvTransposeOut->setOutputRenderOrientation(RenderOrientationDiagonal);
rgb2luvProc->add(luvTransposeOut.get());
}
}
void initACF(const SizeVec& scales, FeatureKind kind, bool debug)
{
rotationProc = drishti::core::make_unique<ogles_gpgpu::NoopProc>();
rgbSmoothProc = drishti::core::make_unique<ogles_gpgpu::GaussOptProc>(2.0f);
rgb2luvProc = drishti::core::make_unique<ogles_gpgpu::Rgb2LuvProc>();
pyramidProc = drishti::core::make_unique<ogles_gpgpu::PyramidProc>(scales);
smoothProc = drishti::core::make_unique<ogles_gpgpu::GaussOptProc>(1);
reduceLuvProc = drishti::core::make_unique<ogles_gpgpu::NoopProc>();
gradProc = drishti::core::make_unique<ogles_gpgpu::GradProc>(1.0f);
reduceGradProc = drishti::core::make_unique<ogles_gpgpu::NoopProc>();
normProc = drishti::core::make_unique<ogles_gpgpu::GaussOptProc>(7, true, 0.005f);
gradHistProcA = drishti::core::make_unique<ogles_gpgpu::GradHistProc>(6, 0, 1.f);
gradHistProcB = drishti::core::make_unique<ogles_gpgpu::GradHistProc>(6, 4, 1.f);
gradHistProcASmooth = drishti::core::make_unique<ogles_gpgpu::GaussOptProc>(3.0f);
gradHistProcBSmooth = drishti::core::make_unique<ogles_gpgpu::GaussOptProc>(3.0f);
reduceGradHistProcASmooth = drishti::core::make_unique<ogles_gpgpu::NoopProc>(1.0f);
reduceGradHistProcBSmooth = drishti::core::make_unique<ogles_gpgpu::NoopProc>(1.0f);
// Reduce base LUV image to highest resolution used in pyramid:
rgb2luvProc->setOutputSize(scales[0].width, scales[0].height);
reduceGradProc->setOutputSize(0.25);
reduceLuvProc->setOutputSize(0.25);
reduceGradHistProcASmooth->setOutputSize(0.25);
reduceGradHistProcBSmooth->setOutputSize(0.25);
#if GPU_ACF_TRANSPOSE
reduceGradProc->setOutputRenderOrientation(RenderOrientationDiagonal);
reduceLuvProc->setOutputRenderOrientation(RenderOrientationDiagonal);
reduceGradHistProcASmooth->setOutputRenderOrientation(RenderOrientationDiagonal);
reduceGradHistProcBSmooth->setOutputRenderOrientation(RenderOrientationDiagonal);
#endif
pyramidProc->setInterpolation(ogles_gpgpu::TransformProc::BICUBIC);
rotationProc->add(rgbSmoothProc.get());
rgbSmoothProc->add(rgb2luvProc.get());
// ((( luv -> pyramid(luv) )))
rgb2luvProc->add(pyramidProc.get());
// ((( pyramid(luv) -> smooth(pyramid(luv)) )))
pyramidProc->add(smoothProc.get());
// ((( smooth(pyramid(luv)) -> {luv_out, MOXY} )))
smoothProc->add(reduceLuvProc.get()); // output 1/4 LUV
smoothProc->add(gradProc.get()); // MOXY
// ((( MOXY -> norm(M) ))
gradProc->add(normProc.get()); // norm(M)OX.
// ((( norm(M) -> {histA, histB} )))
normProc->add(reduceGradProc.get());
normProc->add(gradHistProcA.get());
normProc->add(gradHistProcB.get());
// ((( histA -> smooth(histA) )))
gradHistProcA->add(gradHistProcASmooth.get());
gradHistProcASmooth->add(reduceGradHistProcASmooth.get());
// ((( histB -> smooth(histB) )))
gradHistProcB->add(gradHistProcBSmooth.get());
gradHistProcBSmooth->add(reduceGradHistProcBSmooth.get());
switch (kind)
{
case kM012345:
// This uses two swizzle steps to creaet LG56 output
// Adding a 3 input texture swizzler might be slightly more efficient.
// ((( MERGE(luv, grad) )))
mergeProcLUVG = drishti::core::make_unique<MergeProc>(MergeProc::kSwizzleABC1);
reduceLuvProc->add(mergeProcLUVG.get(), 0);
reduceGradProc->add(mergeProcLUVG.get(), 1);
// ((( MERGE(lg, 56) )))
mergeProcLG56 = drishti::core::make_unique<MergeProc>(MergeProc::kSwizzleAD12);
mergeProcLUVG->add(mergeProcLG56.get(), 0);
reduceGradHistProcBSmooth->add(mergeProcLG56.get(), 1);
break;
case kLUVM012345:
// ((( MERGE(luv, grad) )))
mergeProcLUVG = drishti::core::make_unique<MergeProc>(MergeProc::kSwizzleABC1);
reduceLuvProc->add(mergeProcLUVG.get(), 0);
reduceGradProc->add(mergeProcLUVG.get(), 1);
break;
default:
CV_Assert(false);
}
if (debug)
{
// #### OUTPUT ###
normProcOut = drishti::core::make_unique<ogles_gpgpu::NoopProc>(0.33f);
gradProcOut = drishti::core::make_unique<ogles_gpgpu::NoopProc>(1.0f);
gradHistProcAOut = drishti::core::make_unique<ogles_gpgpu::NoopProc>(1.0f);
gradHistProcBOut = drishti::core::make_unique<ogles_gpgpu::NoopProc>(1.0f);
gradProc->add(gradProcOut.get()); // ### OUTPUT ###
normProc->add(normProcOut.get()); // ### OUTPUT ###
reduceGradHistProcBSmooth->add(gradHistProcBOut.get()); // ### OUTPUT ###
reduceGradHistProcASmooth->add(gradHistProcAOut.get()); // ### OUTPUT ###
}
}
// This provides a map for unpacking/swizzling OpenGL textures (i.e., RGBA or BGRA) to user
// memory using NEON optimized instructions.
ACF::ChannelSpecification getACFChannelSpecification(MatP& acf) const
{
// clang-format on
const auto& rgba = m_rgba;
switch (m_featureKind)
{
case kLUVM012345:
// 10 : { LUVMp; H0123p; H4567p } requires 3 textures
return ACF::ChannelSpecification
{
{{{acf[0],rgba[0]},{acf[1],rgba[1]},{acf[2],rgba[2]},{acf[3],rgba[3]}},mergeProcLUVG.get()},
{{{acf[4],rgba[0]},{acf[5],rgba[1]},{acf[6],rgba[2]},{acf[7],rgba[3]}},reduceGradHistProcASmooth.get()},
{{{acf[8],rgba[0]},{acf[9],rgba[1]}}, reduceGradHistProcBSmooth.get()}
};
case kM012345:
// 7: { Mp; H0123p; H4567p } requires only 2 textures
return ACF::ChannelSpecification
{
{{{acf[0],rgba[1]},{acf[5],rgba[2]},{acf[6],rgba[3]}}, mergeProcLG56.get()},
{{{acf[1],rgba[0]},{acf[2],rgba[1]},{acf[3],rgba[2]},{acf[4],rgba[3]}}, reduceGradHistProcASmooth.get()}
};
default: CV_Assert(false);
}
return ACF::ChannelSpecification();
// clang-format on
}
// ::: MEMBER VARIABLES :::
FeatureKind m_featureKind = kLUVM012345;
std::array<int, 4> m_rgba = { { 0, 1, 2, 3 } };
Size2d m_size;
bool m_debug = false;
// Retriev input image:
bool m_doAcfTransfer = true;
cv::Mat m_luv;
MatP m_luvPlanar;
bool m_doLuvTransfer = false;
bool m_hasLuvOutput = false;
// Grayscale stuff:
bool m_doGray = false;
float m_grayscaleScale = 1.0f;
bool m_hasGrayscaleOutput = false;
cv::Mat m_grayscale;
std::unique_ptr<ogles_gpgpu::NoopProc> rotationProc; // make sure we have an unmodified upright image
std::unique_ptr<ogles_gpgpu::GaussOptProc> rgbSmoothProc;
std::unique_ptr<ogles_gpgpu::NoopProc> reduceRgbSmoothProc; // reduce
std::unique_ptr<ogles_gpgpu::Rgb2LuvProc> rgb2luvProc;
std::unique_ptr<ogles_gpgpu::PyramidProc> pyramidProc;
std::unique_ptr<ogles_gpgpu::GaussOptProc> smoothProc; // (1);
std::unique_ptr<ogles_gpgpu::NoopProc> reduceLuvProc;
std::unique_ptr<ogles_gpgpu::GradProc> gradProc; // (1.0);
std::unique_ptr<ogles_gpgpu::NoopProc> reduceGradProc;
std::unique_ptr<ogles_gpgpu::GaussOptProc> normProc; // (5, true, 0.015);
std::unique_ptr<ogles_gpgpu::GradHistProc> gradHistProcA; // (6, 0, 1.f);
std::unique_ptr<ogles_gpgpu::GradHistProc> gradHistProcB; // (6, 4, 1.f);
std::unique_ptr<ogles_gpgpu::GaussOptProc> gradHistProcASmooth; // (1);
std::unique_ptr<ogles_gpgpu::GaussOptProc> gradHistProcBSmooth; // (1);
std::unique_ptr<ogles_gpgpu::NoopProc> reduceGradHistProcASmooth; // (1);
std::unique_ptr<ogles_gpgpu::NoopProc> reduceGradHistProcBSmooth; // (1);
// #### OUTPUT ###
std::unique_ptr<ogles_gpgpu::NoopProc> normProcOut; //(0.33);
std::unique_ptr<ogles_gpgpu::NoopProc> gradProcOut; //(16.0);
std::unique_ptr<ogles_gpgpu::NoopProc> gradHistProcAOut; //(1.0f);
std::unique_ptr<ogles_gpgpu::NoopProc> gradHistProcBOut; //(1.0f);
std::unique_ptr<ogles_gpgpu::NoopProc> luvTransposeOut; // transposed LUV output
// Multi-texture swizzle (one or the other for 8 vs 10 channels)
std::unique_ptr<ogles_gpgpu::MergeProc> mergeProcLUVG;
std::unique_ptr<ogles_gpgpu::MergeProc> mergeProcLG56;
uint64_t frameIndex = 0;
// Experimental (flow)
std::unique_ptr<Flow2Pipeline> flow;
std::unique_ptr<ogles_gpgpu::SwizzleProc> flowBgra; // (optional)
ogles_gpgpu::ProcInterface* flowBgraInterface = nullptr;
std::vector<Rect2d> m_crops;
// Flwo stuff:
bool m_hasFlowOutput = false;
bool m_doFlow = false;
float m_flowScale = 1.0f;
cv::Mat m_flow;
// Channel stuff:
cv::Mat m_channels;
bool m_hasChannelOutput = false;
bool needsTextures() const
{
bool status = false;
status |= m_doAcfTransfer && !m_hasChannelOutput;
status |= m_doGray && !m_hasGrayscaleOutput;
status |= m_doLuvTransfer && !m_hasLuvOutput;
status |= m_doFlow && ~m_hasFlowOutput;
return status;
}
std::shared_ptr<spdlog::logger> m_logger;
};
// ::::::::::: PUBLIC ::::::::::::::
// { 1280 x 960 } x 0.25 => 320x240
ACF::ACF(void* glContext, const Size2d& size, const SizeVec& scales, FeatureKind kind, int grayWidth, int flowWidth, bool debug)
: VideoSource(glContext)
{
impl = drishti::core::make_unique<Impl>(glContext, size, scales, kind, grayWidth, flowWidth, debug);
// ((( video -> smooth(luv) )))
set(impl->rotationProc.get());
}
ACF::~ACF()
{
// Required in Xcode 8.1 to supoprt instantiation of std::shared_ptr<ogles_gppgu::ACF>
// with forward declares std::unique_ptr<> member variables.
}
void ACF::tryEnablePlatformOptimizations()
{
Core::tryEnablePlatformOptimizations();
}
void ACF::setLogger(std::shared_ptr<spdlog::logger>& logger)
{
impl->m_logger = logger;
}
bool ACF::getChannelStatus()
{
return impl->m_hasChannelOutput;
}
bool ACF::getFlowStatus()
{
return impl->m_doFlow;
}
void ACF::setDoLuvTransfer(bool flag)
{
impl->m_doLuvTransfer = flag;
}
void ACF::setDoAcfTrasfer(bool flag)
{
impl->m_doAcfTransfer = flag;
}
// ACF base resolution to Grayscale image
float ACF::getGrayscaleScale() const
{
return impl->m_grayscaleScale;
}
// Scale of flow wrt inputimage
float ACF::getFlowScale() const
{
return impl->m_flowScale;
}
Flow2Pipeline* ACF::getFlowProc()
{
return impl->flow.get();
}
const std::array<int, 4>& ACF::getChannelOrder()
{
return impl->m_rgba;
}
ProcInterface* ACF::first()
{
return impl->rotationProc.get();
}
ProcInterface* ACF::getRgbSmoothProc()
{
return dynamic_cast<ProcInterface*>(impl->rgbSmoothProc.get());
}
void ACF::connect(std::shared_ptr<spdlog::logger>& logger)
{
impl->m_logger = logger;
}
void ACF::setRotation(int degrees)
{
first()->setOutputRenderOrientation(ogles_gpgpu::degreesToOrientation(degrees));
}
const cv::Mat& ACF::getGrayscale()
{
assert(impl->m_doGray);
return impl->m_grayscale;
}
std::vector<cv::Mat> ACF::getFlowPyramid()
{
// Build flow pyramid:
const float scale = float(impl->m_flow.rows) / float(impl->m_crops[0].height);
const cv::Rect bounds({ 0, 0 }, impl->m_flow.size());
std::vector<cv::Mat> flow(impl->m_crops.size());
for (int i = 0; i < impl->m_crops.size(); i++)
{
const auto& c = impl->m_crops[i];
cv::Rect2f crop(c.x, c.y, c.width, c.height);
cv::Rect roi(crop.tl() * scale, crop.br() * scale);
flow[i] = impl->m_flow(roi & bounds);
}
return flow;
}
/*
* Texture swizzling will be used to ensure BGRA format on texture read.
*/
const cv::Mat& ACF::getFlow()
{
return impl->m_flow;
}
void ACF::initLuvTransposeOutput()
{
// Add transposed Luv output for CPU processing (optional)
impl->luvTransposeOut = drishti::core::make_unique<ogles_gpgpu::NoopProc>();
impl->luvTransposeOut->setOutputRenderOrientation(RenderOrientationDiagonal);
impl->rgb2luvProc->add(impl->luvTransposeOut.get());
}
void ACF::operator()(const Size2d& size, void* pixelBuffer, bool useRawPixels, GLuint inputTexture, GLenum inputPixFormat)
{
FrameInput frame(size, pixelBuffer, useRawPixels, inputTexture, inputPixFormat);
return (*this)(frame);
}
// Implement virtual API to toggle detection + tracking:
void ACF::operator()(const FrameInput& frame)
{
// Inial pipeline filters:
// this -> rotationProc -> rgbSmoothProc -> rgb2luvProc -> pyramidProc
bool needsPyramid = (impl->m_doFlow || impl->m_doAcfTransfer);
bool needsLuv = (needsPyramid | impl->m_doLuvTransfer);
// Initial LUV transpose operation (upright image):
if (impl->m_doLuvTransfer & !impl->luvTransposeOut.get())
{
initLuvTransposeOutput();
}
if (impl->rgb2luvProc.get())
{
impl->rgb2luvProc->setActive(needsLuv);
}
if (impl->pyramidProc.get())
{
impl->pyramidProc->setActive(needsPyramid);
}
if (impl->flow.get())
{
impl->flow->setActive(impl->m_doFlow);
}
// smoothProc is the highest level unique ACF processing filter:
if (impl->smoothProc.get())
{
impl->smoothProc->setActive(impl->m_doAcfTransfer);
}
impl->frameIndex++;
VideoSource::operator()(frame); // call main method
}
void ACF::preConfig()
{
impl->m_hasLuvOutput = false;
impl->m_hasFlowOutput = false;
impl->m_hasChannelOutput = false;
impl->m_hasGrayscaleOutput = false;
}
void ACF::postConfig()
{
// Obtain the scaled image rois:
impl->m_crops.clear();
const auto& rois = impl->pyramidProc->getLevelCrops();
for (auto& r : rois)
{
// TODO: check rounding error (add clipping)?
impl->m_crops.emplace_back(r.x >> 2, r.y >> 2, r.width >> 2, r.height >> 2);
}
}
cv::Mat ACF::getImage(ProcInterface& proc, cv::Mat& frame)
{
if (dynamic_cast<MemTransferOptimized*>(proc.getMemTransferObj()))
{
MemTransfer::FrameDelegate delegate = [&](const Size2d& size, const void* pixels, size_t bytesPerRow) {
frame = cv::Mat(size.height, size.width, CV_8UC4, (void*)pixels, bytesPerRow).clone();
};
proc.getResultData(delegate);
}
else
{
frame.create(proc.getOutFrameH(), proc.getOutFrameW(), CV_8UC4); // noop if preallocated
proc.getResultData(frame.ptr());
}
return frame;
}
cv::Mat ACF::getImage(ProcInterface& proc)
{
cv::Mat frame;
return getImage(proc, frame);
}
bool ACF::processImage(ProcInterface& proc, MemTransfer::FrameDelegate& delegate)
{
bool status = false;
MemTransfer* pTransfer = proc.getMemTransferObj();
if (dynamic_cast<MemTransferOptimized*>(pTransfer))
{
proc.getResultData(delegate);
status = true;
}
return status;
}
// size_t bytesPerRow = proc.getMemTransferObj()->bytesPerRow();
// cv::Mat result(proc.getOutFrameH(), proc.getOutFrameW(), CV_8UC4);
// proc.getResultData(result.ptr());
// return result;
int ACF::getChannelCount() const
{
switch (impl->m_featureKind)
{
case kM012345:
return 7;
case kLUVM012345:
return 10;
default:
return 0;
}
}
std::vector<std::vector<Rect2d>> ACF::getCropRegions() const
{
// CReate array of channel rois for each pyramid level
size_t levelCount = impl->m_crops.size();
std::vector<std::vector<Rect2d>> crops(levelCount);
for (size_t i = 0; i < levelCount; i++)
{
crops[i] = getChannelCropRegions(int(i));
}
return crops;
}
// Copy the parameters from a reference pyramid
void ACF::fill(drishti::acf::Detector::Pyramid& Pout, const drishti::acf::Detector::Pyramid& Pin)
{
Pout.pPyramid = Pin.pPyramid;
Pout.nTypes = Pin.nTypes;
Pout.nScales = Pin.nScales;
Pout.info = Pin.info;
Pout.lambdas = Pin.lambdas;
Pout.scales = Pin.scales;
Pout.scaleshw = Pin.scaleshw;
auto crops = getCropRegions();
assert(crops.size() > 1);
Pout.rois.resize(crops.size());
for (int i = 0; i < crops.size(); i++)
{
Pout.rois[i].resize(crops[i].size());
for (int j = 0; j < crops[i].size(); j++)
{
const auto& r = crops[i][j];
Pout.rois[i][j] = cv::Rect(r.x, r.y, r.width, r.height);
}
}
fill(Pout);
}
// Channels crops are vertically concatenated in the master image:
std::vector<Rect2d> ACF::getChannelCropRegions(int level) const
{
assert(level < impl->m_crops.size());
#if GPU_ACF_TRANSPOSE
int step = impl->m_crops[0].height;
Rect2d roi = impl->m_crops[level];
std::swap(roi.x, roi.y);
std::swap(roi.width, roi.height);
std::vector<Rect2d> crops(getChannelCount(), roi);
for (int i = 1; i < getChannelCount(); i++)
{
crops[i].x += (step * i);
}
#else
std::vector<Rect2d> crops(getChannelCount(), impl->m_crops[level]);
for (int i = 1; i < getChannelCount(); i++)
{
crops[i].y += (impl->m_crops[0].height * i);
}
#endif
return crops;
}
void ACF::prepare()
{
}
using array_type = drishti::acf::Detector::Pyramid::array_type;
// Fill
void ACF::fill(drishti::acf::Detector::Pyramid& pyramid)
{
auto acf = getChannels();
// Build ACF input:
const auto regions = getCropRegions();
const int levelCount = static_cast<int>(regions.size());
const int channelCount = static_cast<int>(regions.front().size());
pyramid.nScales = int(levelCount);
// Create multiresolution representation:
auto& data = pyramid.data;
data.resize(levelCount);
for (int i = 0; i < levelCount; i++)
{
data[i].resize(1);
auto& channels = data[i][0];
channels.base() = acf;
channels.resize(int(channelCount));
for (int j = 0; j < channelCount; j++)
{
const auto& roi = regions[i][j];
channels[j] = acf({ roi.x, roi.y, roi.width, roi.height });
}
}
}
static void unpackImage(const cv::Mat4b& frame, std::vector<drishti::core::PlaneInfo>& dst)
{
switch (dst.front().plane.type())
{
case CV_8UC4:
dst.front().plane = frame.clone(); // deep copy
break;
case CV_8UC1:
drishti::core::unpack(frame, dst);
break;
case CV_32FC1:
drishti::core::convertU8ToF32(frame, dst);
break;
default:
break;
}
}
static void unpackImage(ProcInterface& proc, std::vector<drishti::core::PlaneInfo>& dst)
{
MemTransfer::FrameDelegate handler = [&](const Size2d& size, const void* pixels, size_t rowStride) {
cv::Mat4b frame(size.height, size.width, (cv::Vec4b*)pixels, rowStride);
switch (dst.front().plane.type())
{
case CV_8UC4:
dst.front().plane = frame.clone(); // deep copy
break;
case CV_8UC1:
drishti::core::unpack(frame, dst);
break;
case CV_32FC1:
drishti::core::convertU8ToF32(frame, dst);
break;
default:
break;
}
};
proc.getResultData(handler);
}
// NOTE: GPUACF::getLuvPlanar(), provides a direct/optimized alternative to
// the following CV_8UC4 access and conversion:
// const auto &LUVA = impl->m_acf->getLuv(); // BGRA
// cv::Mat LUV, LUVf;
// cv::cvtColor(LUVA, LUV, cv::COLOR_BGRA2RGB);
// LUV.convertTo(LUVf, CV_32FC3, 1.0/255.0);
// MatP LUVp(LUVf.t());
const MatP& ACF::getLuvPlanar()
{
CV_Assert(impl->m_hasLuvOutput);
return impl->m_luvPlanar;
}
const cv::Mat& ACF::getLuv()
{
impl->m_luv = getImage(*impl->rgb2luvProc);
return impl->m_luv;
}
cv::Mat ACF::getChannels()
{
// This needs to be done after full pipeline execution, but before
// the channels are retrieved.
impl->m_rgba = initChannelOrder();
cv::Mat result = getChannelsImpl();
return result;
}
// This provides a map for unpacking/swizzling OpenGL textures (i.e., RGBA or BGRA) to user
// memory using NEON optimized instructions.
ACF::ChannelSpecification ACF::getACFChannelSpecification(MatP& acf) const
{
return impl->getACFChannelSpecification(acf);
}
void ACF::release()
{
impl->m_grayscale.release();
impl->m_channels.release();
impl->m_flow.release();
}
std::array<int, 4> ACF::initChannelOrder()
{
// Default GL_BGRA so we can use GL_RGBA for comparisons
// since GL_BGRA is undefined on Android
std::array<int, 4> rgba = { { 2, 1, 0, 3 } };
if (pipeline->getMemTransferObj()->getOutputPixelFormat() == GL_RGBA) // assume BGRA
{
std::swap(rgba[0], rgba[2]);
}
return rgba;
}
cv::Mat ACF::getChannelsImpl()
{
using drishti::core::unpack;
const auto tag = DRISHTI_LOCATION_SIMPLE;
std::stringstream ss;
// clang-format off
drishti::core::ScopeTimeLogger scopeTimeLogger = [&](double elapsed)
{
if (impl->m_logger)
{
impl->m_logger->info("TIMING:{}:{};total={}", tag, ss.str(), elapsed);
}
}; // clang-format on
if (impl->needsTextures())
{
{ // Create a scope for glFlush() timing
drishti::core::ScopeTimeLogger glFinishTimer = [&](double t) { ss << "glFlush=" << t << ";"; };
if (auto pTransfer = dynamic_cast<MemTransferOptimized*>(impl->rgb2luvProc->getMemTransferObj()))
{
pTransfer->flush();
}
else
{
glFlush();
}
}
prepare();
if (m_timer)
{
m_timer("read begin");
}
ACF::ChannelSpecification planeIndex;
const auto& rgba = impl->m_rgba; // alias
cv::Mat flow;
MatP acf, gray, luv;
if (impl->m_doAcfTransfer)
{
const auto acfSize = impl->reduceGradHistProcASmooth->getOutFrameSize();
acf.create({ acfSize.width, acfSize.height }, CV_8UC1, getChannelCount(), GPU_ACF_TRANSPOSE);
planeIndex = getACFChannelSpecification(acf);
}
if (impl->m_doGray)
{
// Here we use the green channel:
const auto graySize = impl->reduceRgbSmoothProc->getOutFrameSize();
gray.create({ graySize.width, graySize.height }, CV_8UC1, 1);
PlaneInfoVec grayInfo{ { gray[0], rgba[0] } };
planeIndex.emplace_back(grayInfo, impl->reduceRgbSmoothProc.get());
}
if (impl->m_doLuvTransfer)
{
const float alpha = 1.0f / 255.0f;
const auto luvSize = impl->luvTransposeOut->getOutFrameSize();
luv.create({ luvSize.width, luvSize.height }, CV_32FC1, 3);
PlaneInfoVec luvInfo{ { luv[0], rgba[0], alpha }, { luv[1], rgba[1], alpha }, { luv[2], rgba[2], alpha } };
planeIndex.emplace_back(luvInfo, impl->luvTransposeOut.get());
}
if (impl->m_doFlow)
{
const auto flowSize = impl->flowBgraInterface->getOutFrameSize();
flow.create(flowSize.height, flowSize.width, CV_8UC4);
PlaneInfoVec flowInfo{ { flow } };
planeIndex.emplace_back(flowInfo, impl->flowBgraInterface);
}
// We can use either the direct MemTransferOptimized access, or glReadPixels()
if (dynamic_cast<MemTransferOptimized*>(impl->rgb2luvProc->getMemTransferObj()))
{
drishti::core::ScopeTimeLogger unpackTimer = [&](double t) { ss << "unpack=" << t << ";"; };
// TODO: confirm in documentation that ios texture caches can be queried in parallel
// Experimentally this seems to be the case.
// clang-format off
drishti::core::ParallelHomogeneousLambda harness = [&](int i)
{
planeIndex[i].second->getMemTransferObj()->setOutputPixelFormat(TEXTURE_FORMAT);
unpackImage(*planeIndex[i].second, planeIndex[i].first);
}; // clang-format on
#if OGLES_GPGPU_IOS
// iOS texture cache can be queried in parallel:
cv::parallel_for_({ 0, int(planeIndex.size()) }, harness);
#else
harness({ 0, int(planeIndex.size()) });
#endif
}
else
{
drishti::core::ScopeTimeLogger unpackTimer = [&](double t) { ss << "unpack=" << t << ";"; };
// clang-format off
drishti::core::ParallelHomogeneousLambda harness = [&](int i)
{
planeIndex[i].second->getMemTransferObj()->setOutputPixelFormat(TEXTURE_FORMAT);
unpackImage(getImage(*planeIndex[i].second), planeIndex[i].first);
}; // clang-format on
harness({ 0, int(planeIndex.size()) });
}
if (impl->m_doAcfTransfer)
{
impl->m_channels = acf.base();
impl->m_hasChannelOutput = true;
}
if (impl->m_doGray)
{
impl->m_grayscale = gray[0];
impl->m_hasGrayscaleOutput = true;
}
if (impl->m_doLuvTransfer)
{
impl->m_luvPlanar = luv;
impl->m_hasLuvOutput = true;
}
if (impl->m_doFlow)
{
impl->m_flow = flow;
impl->m_hasFlowOutput = true;
}
if (m_timer)
{
m_timer("read end");
}
}
return impl->m_channels;
}
ACF::FeatureKind getFeatureKind(const drishti::acf::Detector::Options::Pyramid::Chns& chns)
{
const auto& pColor = chns.pColor.get();
const auto& pGradMag = chns.pGradMag.get();
const auto& pGradHist = chns.pGradHist.get();
// Currently all supported GPU ACF channel types have trailing M012345
if (!(pGradMag.enabled && pGradHist.enabled && (pGradHist.nOrients == 6)))
{
return ACF::kUnknown;
}
if (pColor.enabled)
{
if (pColor.colorSpace.get() == "luv")
{
return ACF::kLUVM012345;
}
else
{
return ACF::kUnknown;
}
}
else
{
return ACF::kM012345;
}
return ACF::kUnknown; // compiler warning
}
END_OGLES_GPGPU
| 31.631524 | 128 | 0.618784 | roscopecoltran |
22baf5c6472ce3fb08d66673fcc75c6206009eb6 | 727 | cpp | C++ | src/ofxPixelObject.cpp | BlueJayLouche/ofxSACN_led_mapper | a8f889c78d654c16fe4acae1b98b26e266707257 | [
"MIT"
] | null | null | null | src/ofxPixelObject.cpp | BlueJayLouche/ofxSACN_led_mapper | a8f889c78d654c16fe4acae1b98b26e266707257 | [
"MIT"
] | null | null | null | src/ofxPixelObject.cpp | BlueJayLouche/ofxSACN_led_mapper | a8f889c78d654c16fe4acae1b98b26e266707257 | [
"MIT"
] | null | null | null | //
// ofxPixelObject.cpp
// sACN_Mapped
//
// Created by bluejaylouche on 19/7/21.
//
// Adapted from: https://github.com/DHaylock/ofxOPC
#include "ofxPixelObject.hpp"
//--------------------------------------------------------------
vector <ofColor> ofxPixelObject::colorData()
{
// Transmit Data
return colors;
}
//--------------------------------------------------------------
vector<glm::vec2> ofxPixelObject::getPixelCoordinates()
{
colors.clear();
return pos;
}
//--------------------------------------------------------------
void ofxPixelObject::drawGrabRegion(bool hideArea)
{
}
//--------------------------------------------------------------
void ofxPixelObject::draw(int x, int y)
{
}
| 22.71875 | 64 | 0.440165 | BlueJayLouche |
22beb06fd41d6bdf985a1e5f93853dda9cf18408 | 1,781 | cpp | C++ | Day_90.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | 8 | 2021-02-07T16:31:28.000Z | 2021-06-11T18:53:23.000Z | Day_90.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | null | null | null | Day_90.cpp | iamakkkhil/DailyCoding | 8422ddbcc2a179f3fd449871e2241ad94a845efb | [
"MIT"
] | 1 | 2021-05-25T17:17:58.000Z | 2021-05-25T17:17:58.000Z | /*
DAY 90: Queue using two Stacks.
https://www.geeksforgeeks.org/queue-using-stacks/
QUESTION : Implement a Queue using 2 stacks s1 and s2 .
A Query Q is of 2 Types
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop element from queue and print the poped element)
Example 1:
Input:
5
1 2 1 3 2 1 4 2
Output:
2 3
Explanation:
In the first testcase
1 2 the queue will be {2}
1 3 the queue will be {2 3}
2 poped element will be 2 the queue
will be {3}
1 4 the queue will be {3 4}
2 poped element will be 3.
Example 2:
Input:
4
1 2 2 2 1 4
Output:
2 -1
Explanation:
In the second testcase
1 2 the queue will be {2}
2 poped element will be 2 and
then the queue will be empty
2 the queue is empty and hence -1
1 4 the queue will be {4}.
Expected Time Complexity : O(1) for push() and O(N) for pop() or O(N) for push() and
O(1) for pop()
Expected Auxilliary Space : O(1).
Constraints:
1 <= Q <= 100
1 <= x <= 100
*/
/* The structure of the class is
class StackQueue{
private:
// These are STL stacks ( http://goo.gl/LxlRZQ )
stack<int> s1;
stack<int> s2;
public:
void push(int);
int pop();
}; */
//Function to push an element in queue by using 2 stacks.
void StackQueue :: push(int x)
{
// Your Code
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
s2.push(x);
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}
//Function to pop an element from queue by using 2 stacks.
int StackQueue :: pop()
{
// Your Code
if (s1.empty()) return -1;
int top_ele = s1.top();
s1.pop();
return top_ele;
}
| 20.011236 | 92 | 0.590118 | iamakkkhil |
22bec18cbd71877d96e755c44e00553e11785b18 | 2,178 | cpp | C++ | oclint-rules/rules/convention/InvertedLogicRule.cpp | BGU-AiDnD/oclint | 484fed44ca0e34532745b3d4f04124cbf5bb42fa | [
"BSD-3-Clause"
] | 3,128 | 2015-01-01T06:00:31.000Z | 2022-03-29T23:43:20.000Z | oclint-rules/rules/convention/InvertedLogicRule.cpp | BGU-AiDnD/oclint | 484fed44ca0e34532745b3d4f04124cbf5bb42fa | [
"BSD-3-Clause"
] | 432 | 2015-01-03T15:43:08.000Z | 2022-03-29T02:32:48.000Z | oclint-rules/rules/convention/InvertedLogicRule.cpp | BGU-AiDnD/oclint | 484fed44ca0e34532745b3d4f04124cbf5bb42fa | [
"BSD-3-Clause"
] | 454 | 2015-01-06T03:11:12.000Z | 2022-03-22T05:49:38.000Z | #include "oclint/AbstractASTVisitorRule.h"
#include "oclint/RuleSet.h"
using namespace std;
using namespace clang;
using namespace oclint;
class InvertedLogicRule : public AbstractASTVisitorRule<InvertedLogicRule>
{
private:
bool isInvertedLogic(Expr *condExpr)
{
BinaryOperator *binaryOperator = dyn_cast_or_null<BinaryOperator>(condExpr);
UnaryOperator *unaryOperator = dyn_cast_or_null<UnaryOperator>(condExpr);
return (binaryOperator && binaryOperator->getOpcode() == BO_NE) ||
(unaryOperator && unaryOperator->getOpcode() == UO_LNot);
}
public:
virtual const string name() const override
{
return "inverted logic";
}
virtual int priority() const override
{
return 3;
}
virtual const string category() const override
{
return "convention";
}
#ifdef DOCGEN
virtual const std::string since() const override
{
return "0.4";
}
virtual const std::string description() const override
{
return "An inverted logic is hard to understand.";
}
virtual const std::string example() const override
{
return R"rst(
.. code-block:: cpp
int example(int a)
{
int i;
if (a != 0) // if (a == 0)
{ // {
i = 1; // i = 0;
} // }
else // else
{ // {
i = 0; // i = 1;
} // }
return !i ? -1 : 1; // return i ? 1 : -1;
}
)rst";
}
#endif
bool VisitIfStmt(IfStmt *ifStmt)
{
if (ifStmt->getElse() && isInvertedLogic(ifStmt->getCond()))
{
addViolation(ifStmt->getCond(), this);
}
return true;
}
bool VisitConditionalOperator(ConditionalOperator *conditionalOperator)
{
if (isInvertedLogic(conditionalOperator->getCond()))
{
addViolation(conditionalOperator->getCond(), this);
}
return true;
}
};
static RuleSet rules(new InvertedLogicRule());
| 23.934066 | 84 | 0.537649 | BGU-AiDnD |
22c13a06d5f81495bc5e3e2f13a8a9ffd6cf7ef8 | 792 | cpp | C++ | src/alphabeta.cpp | Isameru/rookmole | d93b73b3771ff34b95ab630bfc3c66e899cac480 | [
"MIT"
] | null | null | null | src/alphabeta.cpp | Isameru/rookmole | d93b73b3771ff34b95ab630bfc3c66e899cac480 | [
"MIT"
] | null | null | null | src/alphabeta.cpp | Isameru/rookmole | d93b73b3771ff34b95ab630bfc3c66e899cac480 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) Mariusz Łapiński <gmail:isameru>
██████╗ ██████╗ ██████╗ ██╗ ██╗███╗ ███╗ ██████╗ ██╗ ███████╗
██╔══██╗██╔═══██╗██╔═══██╗██║ ██╔╝████╗ ████║██╔═══██╗██║ ██╔════╝
██████╔╝██║ ██║██║ ██║█████╔╝ ██╔████╔██║██║ ██║██║ █████╗
██╔══██╗██║ ██║██║ ██║██╔═██╗ ██║╚██╔╝██║██║ ██║██║ ██╔══╝
██║ ██║╚██████╔╝╚██████╔╝██║ ██╗██║ ╚═╝ ██║╚██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝
*/
#include "rookmole/alphabeta.h"
namespace rookmole {
//=≡=-=♔=-=≡=-=♕=-=≡=-=♖=-=≡=-=♗=-=≡=-=♘=-=≡=-=♙=-=≡=-=♚=-=≡=-=♛=-=≡=-=♜=-=≡=-=♝=-=≡=-=♞=-=≡=-=♟︎=-
//=≡=-=♔=-=≡=-=♕=-=≡=-=♖=-=≡=-=♗=-=≡=-=♘=-=≡=-=♙=-=≡=-=♚=-=≡=-=♛=-=≡=-=♜=-=≡=-=♝=-=≡=-=♞=-=≡=-=♟︎=-
} // namespace rookmole
| 36 | 99 | 0.133838 | Isameru |
42ef672c79b79129801f447209221d49f6662d0a | 2,263 | cpp | C++ | src/kpr/TimerTaskManager.cpp | hooligan520/rocketmq-clent4cpp-linux | 2f891c979229dfd78707150fa626ca3822f2d006 | [
"Apache-2.0"
] | 22 | 2017-02-17T14:28:17.000Z | 2021-02-25T10:09:04.000Z | src/kpr/TimerTaskManager.cpp | hooligan520/rocketmq-clent4cpp-linux | 2f891c979229dfd78707150fa626ca3822f2d006 | [
"Apache-2.0"
] | 2 | 2017-04-29T05:57:38.000Z | 2017-11-20T03:49:48.000Z | src/kpr/TimerTaskManager.cpp | hooligan520/rocketmq-clent4cpp-linux | 2f891c979229dfd78707150fa626ca3822f2d006 | [
"Apache-2.0"
] | 10 | 2017-02-08T03:06:57.000Z | 2020-04-18T01:48:53.000Z | /**
* Copyright (C) 2013 kangliqiang ,kangliq@163.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimerTaskManager.h"
#include "ThreadPool.h"
#include "ScopedLock.h"
namespace kpr
{
TimerTaskManager::TimerTaskManager()
{
}
TimerTaskManager::~TimerTaskManager()
{
}
int TimerTaskManager::Init(int maxThreadCount, int checklnteval)
{
try
{
m_pThreadPool = new ThreadPool("TimerThreadPool", 5, 5, maxThreadCount);
m_timerThread = new TimerThread("TimerThread", checklnteval);
m_timerThread->Start();
}
catch (...)
{
return -1;
}
return 0;
}
unsigned int TimerTaskManager::RegisterTimer(unsigned int initialDelay, unsigned int elapse, TimerTaskPtr pTask)
{
unsigned int id = m_timerThread->RegisterTimer(initialDelay, elapse, this, true);
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
m_timerTasks[id] = pTask;
return id;
}
bool TimerTaskManager::UnRegisterTimer(unsigned int timerId)
{
bool ret = m_timerThread->UnRegisterTimer(timerId);
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
m_timerTasks.erase(timerId);
return ret;
}
bool TimerTaskManager::ResetTimer(unsigned int timerId)
{
return m_timerThread->ResetTimer(timerId);
}
void TimerTaskManager::OnTimeOut(unsigned int timerId)
{
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
std::map<unsigned int, TimerTaskPtr>::iterator it = m_timerTasks.find(timerId);
if (it != m_timerTasks.end())
{
if (!it->second->IsProcessing())
{
it->second->SetProcessing(true);
m_pThreadPool->AddWork((it->second).ptr());
}
}
}
void TimerTaskManager::Stop()
{
m_timerThread->Stop();
m_timerThread->Join();
m_pThreadPool->Destroy();
}
}
| 24.597826 | 112 | 0.695095 | hooligan520 |
42efbd12c2e2db86eaa4d9a661f7a09220e5eeb6 | 10,269 | cc | C++ | RecoLocalTracker/SiPixelRecHits/plugins/SiPixelRecHitConverter.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | RecoLocalTracker/SiPixelRecHits/plugins/SiPixelRecHitConverter.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | RecoLocalTracker/SiPixelRecHits/plugins/SiPixelRecHitConverter.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | /** SiPixelRecHitConverter.cc
* ------------------------------------------------------
* Description: see SiPixelRecHitConverter.h
* Authors: P. Maksimovic (JHU), V.Chiochia (Uni Zurich)
* History: Feb 27, 2006 - initial version
* May 30, 2006 - edm::DetSetVector and edm::Ref
* Aug 30, 2007 - edmNew::DetSetVector
* Jan 31, 2008 - change to use Lorentz angle from DB (Lotte Wilke)
* ------------------------------------------------------
*/
//---------------------------------------------------------------------------
//! \class SiPixelRecHitConverter
//!
//! \brief EDProducer to covert SiPixelClusters into SiPixelRecHits
//!
//! SiPixelRecHitConverter is an EDProducer subclass (i.e., a module)
//! which orchestrates the conversion of SiPixelClusters into SiPixelRecHits.
//! Consequently, the input is a edm::DetSetVector<SiPixelCluster> and the output is
//! SiPixelRecHitCollection.
//!
//! SiPixelRecHitConverter invokes one of descendents from
//! ClusterParameterEstimator (templated on SiPixelCluster), e.g.
//! CPEFromDetPosition (which is the only available option
//! right now). SiPixelRecHitConverter loads the SiPixelClusterCollection,
//! and then iterates over DetIds, invoking the chosen CPE's methods
//! localPosition() and localError() to perform the correction (some of which
//! may be rather involved). A RecHit is made on the spot, and appended
//! to the output collection.
//!
//! The calibrations are not loaded at the moment,
//! although that is being planned for the near future.
//!
//! \author Porting from ORCA by Petar Maksimovic (JHU). Implementation of the
//! DetSetVector by V.Chiochia (Zurich University).
//!
//! \version v2, May 30, 2006
//! change to use Lorentz angle from DB Lotte Wilke, Jan. 31st, 2008
//!
//---------------------------------------------------------------------------
//--- Base class for CPEs:
#include "RecoLocalTracker/SiPixelRecHits/interface/PixelCPEBase.h"
//--- Geometry + DataFormats
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "DataFormats/SiPixelCluster/interface/SiPixelCluster.h"
#include "DataFormats/TrackerRecHit2D/interface/SiPixelRecHitCollection.h"
#include "DataFormats/Common/interface/DetSetVector.h"
//--- Framework
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "FWCore/Utilities/interface/EDPutToken.h"
#include "FWCore/Utilities/interface/ESGetToken.h"
// Geometry
#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
#include "Geometry/CommonDetUnit/interface/PixelGeomDetUnit.h"
// Data Formats
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/DetSet2RangeMap.h"
// STL
#include <vector>
#include <memory>
#include <string>
#include <iostream>
// MessageLogger
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "RecoLocalTracker/Records/interface/TkPixelCPERecord.h"
using namespace std;
namespace cms {
class SiPixelRecHitConverter : public edm::stream::EDProducer<> {
public:
//--- Constructor, virtual destructor (just in case)
explicit SiPixelRecHitConverter(const edm::ParameterSet& conf);
~SiPixelRecHitConverter() override;
//--- Factory method to make CPE's depending on the ParameterSet
//--- Not sure if we need to make more than one CPE to run concurrently
//--- on different parts of the detector (e.g., one for the barrel and the
//--- one for the forward). The way the CPE's are written now, it's
//--- likely we can use one (and they will switch internally), or
//--- make two of the same but configure them differently. We need a more
//--- realistic use case...
//--- The top-level event method.
void produce(edm::Event& e, const edm::EventSetup& c) override;
//--- Execute the position estimator algorithm(s).
//--- New interface with DetSetVector
void run(const edmNew::DetSetVector<SiPixelCluster>& input,
SiPixelRecHitCollectionNew& output,
TrackerGeometry const& geom);
void run(edm::Handle<edmNew::DetSetVector<SiPixelCluster>> inputhandle,
SiPixelRecHitCollectionNew& output,
TrackerGeometry const& geom);
private:
// TO DO: maybe allow a map of pointers?
/// const PixelClusterParameterEstimator * cpe_; // what we got (for now, one ptr to base class)
PixelCPEBase const* cpe_ = nullptr; // What we got (for now, one ptr to base class)
edm::InputTag const src_;
edm::EDGetTokenT<edmNew::DetSetVector<SiPixelCluster>> const tPixelCluster_;
edm::EDPutTokenT<SiPixelRecHitCollection> const tPut_;
edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord> const tTrackerGeom_;
edm::ESGetToken<PixelClusterParameterEstimator, TkPixelCPERecord> const tCPE_;
bool m_newCont; // save also in emdNew::DetSetVector
};
//---------------------------------------------------------------------------
//! Constructor: set the ParameterSet and defer all thinking to setupCPE().
//---------------------------------------------------------------------------
SiPixelRecHitConverter::SiPixelRecHitConverter(edm::ParameterSet const& conf)
: src_(conf.getParameter<edm::InputTag>("src")),
tPixelCluster_(consumes<edmNew::DetSetVector<SiPixelCluster>>(src_)),
tPut_(produces<SiPixelRecHitCollection>()),
tTrackerGeom_(esConsumes<TrackerGeometry, TrackerDigiGeometryRecord>()),
tCPE_(esConsumes<PixelClusterParameterEstimator, TkPixelCPERecord>(
edm::ESInputTag("", conf.getParameter<std::string>("CPE")))) {}
// Destructor
SiPixelRecHitConverter::~SiPixelRecHitConverter() {}
//---------------------------------------------------------------------------
//! The "Event" entrypoint: gets called by framework for every event
//---------------------------------------------------------------------------
void SiPixelRecHitConverter::produce(edm::Event& e, const edm::EventSetup& es) {
// Step A.1: get input data
edm::Handle<edmNew::DetSetVector<SiPixelCluster>> input;
e.getByToken(tPixelCluster_, input);
// Step A.2: get event setup
auto const& geom = es.getData(tTrackerGeom_);
// Step B: create empty output collection
SiPixelRecHitCollectionNew output;
// Step B*: create CPE
cpe_ = dynamic_cast<const PixelCPEBase*>(&es.getData(tCPE_));
// Step C: Iterate over DetIds and invoke the strip CPE algorithm
// on each DetUnit
run(input, output, geom);
output.shrink_to_fit();
e.emplace(tPut_, std::move(output));
}
//---------------------------------------------------------------------------
//! Iterate over DetUnits, then over Clusters and invoke the CPE on each,
//! and make a RecHit to store the result.
//! New interface reading DetSetVector by V.Chiochia (May 30th, 2006)
//---------------------------------------------------------------------------
void SiPixelRecHitConverter::run(edm::Handle<edmNew::DetSetVector<SiPixelCluster>> inputhandle,
SiPixelRecHitCollectionNew& output,
TrackerGeometry const& geom) {
if (!cpe_) {
edm::LogError("SiPixelRecHitConverter") << " at least one CPE is not ready -- can't run!";
// TO DO: throw an exception here? The user may want to know...
assert(0);
return; // clusterizer is invalid, bail out
}
int numberOfDetUnits = 0;
int numberOfClusters = 0;
const edmNew::DetSetVector<SiPixelCluster>& input = *inputhandle;
edmNew::DetSetVector<SiPixelCluster>::const_iterator DSViter = input.begin();
for (; DSViter != input.end(); DSViter++) {
numberOfDetUnits++;
unsigned int detid = DSViter->detId();
DetId detIdObject(detid);
const GeomDetUnit* genericDet = geom.idToDetUnit(detIdObject);
const PixelGeomDetUnit* pixDet = dynamic_cast<const PixelGeomDetUnit*>(genericDet);
assert(pixDet);
SiPixelRecHitCollectionNew::FastFiller recHitsOnDetUnit(output, detid);
edmNew::DetSet<SiPixelCluster>::const_iterator clustIt = DSViter->begin(), clustEnd = DSViter->end();
for (; clustIt != clustEnd; clustIt++) {
numberOfClusters++;
std::tuple<LocalPoint, LocalError, SiPixelRecHitQuality::QualWordType> tuple =
cpe_->getParameters(*clustIt, *genericDet);
LocalPoint lp(std::get<0>(tuple));
LocalError le(std::get<1>(tuple));
SiPixelRecHitQuality::QualWordType rqw(std::get<2>(tuple));
// Create a persistent edm::Ref to the cluster
edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> cluster =
edmNew::makeRefTo(inputhandle, clustIt);
// Make a RecHit and add it to the DetSet
// old : recHitsOnDetUnit.push_back( new SiPixelRecHit( lp, le, detIdObject, &*clustIt) );
SiPixelRecHit hit(lp, le, rqw, *genericDet, cluster);
//
// Now save it =================
recHitsOnDetUnit.push_back(hit);
// =============================
// std::cout << "SiPixelRecHitConverterVI " << numberOfClusters << ' '<< lp << " " << le << std::endl;
} // <-- End loop on Clusters
// LogDebug("SiPixelRecHitConverter")
//std::cout << "SiPixelRecHitConverterVI "
// << " Found " << recHitsOnDetUnit.size() << " RecHits on " << detid //;
// << std::endl;
} // <-- End loop on DetUnits
// LogDebug ("SiPixelRecHitConverter")
// std::cout << "SiPixelRecHitConverterVI "
// << cpeName_ << " converted " << numberOfClusters
// << " SiPixelClusters into SiPixelRecHits, in "
// << numberOfDetUnits << " DetUnits." //;
// << std::endl;
}
} // end of namespace cms
using cms::SiPixelRecHitConverter;
DEFINE_FWK_MODULE(SiPixelRecHitConverter);
| 42.609959 | 110 | 0.645146 | SWuchterl |
42efc8c6d1796bfa80677ea5a109b1bbda8f5662 | 4,849 | cpp | C++ | src/Utilities/tests/test_parser.cpp | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | null | null | null | src/Utilities/tests/test_parser.cpp | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | null | null | null | src/Utilities/tests/test_parser.cpp | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | null | null | null | #//////////////////////////////////////////////////////////////////////////////////////
#// This file is distributed under the University of Illinois/NCSA Open Source License.
#// See LICENSE file in top directory for details.
#//
#// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
#//
#// File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
#//
#// File created by: Mark Dewing, markdewing@gmail.com, University of Illinois at Urbana-Champaign
#//////////////////////////////////////////////////////////////////////////////////////
#include "catch.hpp"
#include "Utilities/SimpleParser.h"
#include <stdio.h>
#include <string>
#include <sstream>
#include <vector>
using std::string;
using std::vector;
namespace qmcplusplus {
TEST_CASE("parsewords_empty", "[utilities]")
{
string input = "";
vector<string> outlist;
unsigned int num = parsewords(input.c_str(), outlist);
REQUIRE(num == 0);
REQUIRE(outlist.size() == 0);
}
struct ParseCase
{
string input; // input string
vector<string> output; // expected tokens
string extra_split; // extra characters to split on
ParseCase(const string &in) : input(in) {}
ParseCase(const string &in, const vector<string> &out) : input(in), output(out) {}
ParseCase(const string &in, const vector<string> &out, const string &extra) : input(in), output(out), extra_split(extra) {}
};
typedef vector<ParseCase> ParseCaseVector_t;
TEST_CASE("parsewords", "[utilities]")
{
ParseCaseVector_t tlist =
{
// Input string, list of expected tokens, extra split characters
{"a", {"a"}, },
{"b=", {"b"}, },
{"=c", {"c"}, },
{"d=e", {"d","e"}, },
{"f,g", {"f","g"}, },
{"h\ti,j", {"h","i","j"}, },
{"k|m", {"k|m"}, },
{"n|o", {"n","o"}, "|"}
};
for (auto &tc : tlist) {
SECTION(string("Parsing string: ") + tc.input) {
vector<string> outlist;
unsigned int num = parsewords(tc.input.c_str(), outlist, tc.extra_split);
REQUIRE(num == tc.output.size());
REQUIRE(outlist.size() == tc.output.size());
for (int i = 0; i < tc.output.size(); i++) {
REQUIRE(outlist[i] == tc.output[i]);
}
}
}
}
TEST_CASE("readLine", "[utilities]")
{
ParseCaseVector_t tlist =
{
// Input string, list of expected tokens, extra split characters
{"", {""}},
{"one", {"one"}},
{"one\ntwo", {"one","two"}},
{"one;two", {"one","two"}},
{"one\\\ntwo", {"onetwo"}},
{"one\\ two", {"one\\ two"}},
{"12345678901234567890extra", {"1234567890123456789"}}, // assuming bufLen=20 below
};
for (auto &tc : tlist) {
SECTION(string("Parsing string: ") + tc.input) {
const int bufLen = 20;
char buf[bufLen];
std::istringstream input(tc.input);
for (int i = 0; i < tc.output.size(); i++) {
char *out = readLine(buf, bufLen, input);
REQUIRE(buf == tc.output[i]);
if (i == tc.output.size()-1) {
REQUIRE(out == NULL);
} else {
REQUIRE(out != NULL);
}
}
}
}
}
TEST_CASE("getwords", "[utilities]")
{
ParseCaseVector_t tlist =
{
// Input string, list of expected tokens, extra split characters
{"one\n", {"one"}},
{"one,two\n", {"one","two"}},
{"one|two\n", {"one|two"}},
{"a|b\n", {"a","b"}, "|"},
};
for (auto &tc : tlist) {
SECTION(string("Parsing input: ") + tc.input) {
vector<string> outlist;
std::istringstream input(tc.input);
int num = getwords(outlist, input, 0, tc.extra_split);
REQUIRE(num == tc.output.size());
REQUIRE(outlist.size() == tc.output.size());
for (int i = 0; i < tc.output.size(); i++) {
REQUIRE(outlist[i] == tc.output[i]);
}
}
}
}
TEST_CASE("getwordsWithMergedNumbers", "[utilities]")
{
// 1.0-2.0 -> 1.0 -2.0
// 105 C 5 Z 0.000000 0.000000 -0.567800-103.884284 -2.142253
ParseCaseVector_t tlist =
{
// Input string, list of expected tokens, extra split characters
{"1\n", {"1"}},
{"1 2\n", {"1","2"}},
{"1.0 -2.0\n", {"1.0","-2.0"}},
{"1.0-2.0\n", {"1.0","-2.0"}},
{"-1.0-2.0-3.0\n", {"-1.0","-2.0","-3.0"}},
{"105 C 5 Z 0.000000 0.000000 -0.567800-103.884284 -2.142253\n", {"105","C","5","Z","0.000000","0.000000","-0.567800","-103.884284","-2.142253"}}
};
for (auto &tc : tlist) {
SECTION(string("Parsing input: ") + tc.input) {
vector<string> outlist;
std::istringstream input(tc.input);
int num = getwordsWithMergedNumbers(outlist, input);
REQUIRE(num == tc.output.size());
REQUIRE(outlist.size() == tc.output.size());
for (int i = 0; i < tc.output.size(); i++) {
REQUIRE(outlist[i] == tc.output[i]);
}
}
}
}
}
| 28.863095 | 149 | 0.532068 | bwvdg |
42f060a507ace5f9dc44c2790a1b9437d42127ed | 1,626 | cpp | C++ | src/Gui/Settings/SettingsWidget.cpp | AndrzejWoronko/WebPassWare | 9af0df61a9279f1ffe8561714656265f4bec7939 | [
"MIT"
] | null | null | null | src/Gui/Settings/SettingsWidget.cpp | AndrzejWoronko/WebPassWare | 9af0df61a9279f1ffe8561714656265f4bec7939 | [
"MIT"
] | null | null | null | src/Gui/Settings/SettingsWidget.cpp | AndrzejWoronko/WebPassWare | 9af0df61a9279f1ffe8561714656265f4bec7939 | [
"MIT"
] | null | null | null | #include "SettingsWidget.h"
SettingsWidget::SettingsWidget(QWidget *parent) : QWidget (parent)
{
setGraphicElements();
setGraphicSettings();
setConnections();
}
SettingsWidget::~SettingsWidget()
{
safe_delete(m_look_widget)
safe_delete(m_database_widget)
safe_delete(m_list)
safe_delete(m_layout)
safe_delete(m_splitter)
safe_delete(m_mainLayout)
}
void SettingsWidget::setGraphicElements(QWidget *parent)
{
m_splitter = new CSplitter(QString("SettingsSplitter"), Qt::Horizontal, this);
m_look_widget = new SettingsLookController(parent);
m_database_widget = new SettingsDatabaseViewController(parent);
this->setLayout(m_mainLayout = new CVBoxLayout());
createListWidget();
m_splitter->addWidget(m_list);
m_layout = new QStackedLayout(m_splitter);
m_layout->addWidget(m_look_widget->getView());
m_layout->addWidget(m_database_widget->getView());
m_splitter->setLayout(m_layout);
m_mainLayout->addWidget(m_splitter);
}
void SettingsWidget::setGraphicSettings()
{
m_list->setCurrentRow(0);
}
void SettingsWidget::createListWidget()
{
m_list = new CListWidget(m_splitter);
m_list->addItem(tr("Wygląd"), tr("Ustawienia wyglądu"), ICON("Settings"), QSize(50,50));
m_list->addItem(tr("Baza danych"), tr("Parametry połączenia z bazą danych"), ICON("Database-settings"), QSize(50,50));
m_list->setTabKeyNavigation(true);
//TODO WYMIAR LISTY Z KONFIGURACJI
m_list->setMinimumWidth(200);
}
void SettingsWidget::setConnections()
{
connect(m_list, SIGNAL(currentRowChanged(int)), m_layout, SLOT(setCurrentIndex(int)));
}
| 28.526316 | 122 | 0.735547 | AndrzejWoronko |
42f5d1312109441a9d02860cd74c28eed0da86c8 | 2,960 | hpp | C++ | ComponentFramework/SystemHandlerTemplate.hpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | 7 | 2015-06-21T20:23:12.000Z | 2020-01-04T20:20:56.000Z | ComponentFramework/SystemHandlerTemplate.hpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | null | null | null | ComponentFramework/SystemHandlerTemplate.hpp | autious/kravall_entity_component_framework | a4380ea9135c2ad7aac444c0d52837eb1a43319d | [
"MIT"
] | null | null | null | #ifndef SRC_CORE_COMPONENTFRAMEWORK_SYSTEMHANDLER_H
#define SRC_CORE_COMPONENTFRAMEWORK_SYSTEMHANDLER_H
#include "BaseSystem.hpp"
#include "PVector.hpp"
#include <TemplateUtility/TemplateIndex.hpp>
#include <array>
#include <utility>
#include <vector>
#include <Timer.hpp>
#define GNAME( name ) #name
namespace Core
{
/*!
SystemHandler, stores systems, calls them and handles callbacks from EntityHandler to Systems.
Can be created and called every frame to apply the registered systems transformation on
registered entities
*/
template<typename... Args>
class SystemHandlerTemplate
{
public:
static const int SYSTEM_COUNT = sizeof...(Args);
/*!
Standard constructur, creates systemhandler
*/
SystemHandlerTemplate( )
{
m_systems = {{(new Args())...}};
}
~SystemHandlerTemplate()
{
}
/*!
Returns how many systems were compiled into the systemhandler
*/
int GetSystemCount()
{
return SYSTEM_COUNT;
}
/*!
Main update loop, called every frame to update all systems
*/
void Update( float delta )
{
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
m_timer.Start();
m_systems[i]->Update( delta );
m_timer.Stop();
std::chrono::microseconds diff = m_timer.GetDelta();
m_frameTimes[i] = diff;
}
}
/*!
Intended to be called by EntityHandler when entities are created, modified or removed.
*/
void CallChangedEntity( Entity id, Aspect old_asp, Aspect new_asp )
{
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
m_systems[i]->ChangedEntity( id, old_asp, new_asp );
}
};
/*!
This function primarily exist for testing purposes,
don't use it without thinking about it first.
*/
BaseSystem *GetSystem( int id )
{
return m_systems[id];
}
template <typename System>
System* GetSystem()
{
return reinterpret_cast<System*>(m_systems[Index<System, std::tuple<Args...>>::value]);
}
std::vector<std::pair<const char*,std::chrono::microseconds>> GetFrameTime()
{
std::vector<std::pair<const char*,std::chrono::microseconds>> ar;
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
ar.push_back( std::pair<const char*, std::chrono::microseconds>( m_systems[i]->GetHumanName(), m_frameTimes[i] ) );
}
return ar;
}
private:
std::array<BaseSystem*,SYSTEM_COUNT> m_systems;
std::array<std::chrono::microseconds,SYSTEM_COUNT> m_frameTimes;
HighresTimer m_timer;
};
}
#endif
| 25.517241 | 131 | 0.556757 | autious |
42f82baaa8b1c4c175089148c6959535148f32b9 | 228,601 | cpp | C++ | GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | /* Generated code for Python source for module 'oauthlib.oauth2.rfc6749.grant_types.refresh_token'
* created by Nuitka version 0.5.28.2
*
* This code is in part copyright 2017 Kay Hayen.
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The _module_oauthlib$oauth2$rfc6749$grant_types$refresh_token is a Python object pointer of module type. */
/* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
PyDictObject *moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
/* The module constants used, if any. */
extern PyObject *const_str_plain_validate_token_request;
extern PyObject *const_str_plain_scopes;
extern PyObject *const_str_plain_headers;
extern PyObject *const_str_plain_metaclass;
extern PyObject *const_tuple_str_plain_errors_str_plain_utils_tuple;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain_request;
extern PyObject *const_str_plain_getLogger;
static PyObject *const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5;
extern PyObject *const_dict_empty;
extern PyObject *const_str_plain_refresh_token;
static PyObject *const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple;
extern PyObject *const_str_plain___file__;
extern PyObject *const_str_plain_json;
extern PyObject *const_dict_b8647fd2e1f76fc4a4a7d9f73ab075f3;
static PyObject *const_str_plain_original_scopes;
extern PyObject *const_str_plain_client_id;
extern PyObject *const_str_plain_scope;
extern PyObject *const_str_digest_db863ae963136937930c789e9568c079;
extern PyObject *const_str_plain_pre_token;
extern PyObject *const_str_plain_validator;
static PyObject *const_str_digest_012be4d46b429a4aec730cf0f5831f69;
extern PyObject *const_str_plain_utils;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain_create_token;
extern PyObject *const_str_plain_absolute_import;
extern PyObject *const_str_plain_description;
extern PyObject *const_str_plain_save_token;
static PyObject *const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98;
extern PyObject *const_str_digest_1781891970018ef9597f363946d7327b;
extern PyObject *const_str_plain_modifier;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_plain_validate_grant_type;
extern PyObject *const_str_plain_s;
static PyObject *const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple;
extern PyObject *const_str_angle_genexpr;
extern PyObject *const_str_plain_OAuth2Error;
extern PyObject *const_str_plain___qualname__;
static PyObject *const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93;
extern PyObject *const_str_digest_b9c4baf879ebd882d40843df3a4dead7;
static PyObject *const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b;
extern PyObject *const_str_digest_a97b46010ba2d7a042fbaf3749619f69;
static PyObject *const_str_digest_7d87b8a7beb472784c8f817c5cf003af;
extern PyObject *const_str_plain_all;
extern PyObject *const_str_plain_authenticate_client_id;
extern PyObject *const_str_plain_e;
extern PyObject *const_str_plain_create_token_response;
extern PyObject *const_str_plain_validate_refresh_token;
static PyObject *const_str_digest_db37fe24851f7ebc30f9e552d120d953;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_status_code;
extern PyObject *const_str_plain___loader__;
extern PyObject *const_str_plain_errors;
extern PyObject *const_str_plain_InvalidClientError;
static PyObject *const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39;
extern PyObject *const_tuple_str_plain_RequestValidator_tuple;
extern PyObject *const_str_plain_grant_type;
extern PyObject *const_str_plain_token;
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_digest_6d6a615162e89eb148ba9bf8dbfc06d3;
extern PyObject *const_str_plain_scope_to_list;
static PyObject *const_tuple_22acf86284f4127a5583eccb3d24d717_tuple;
extern PyObject *const_str_plain_get_original_scopes;
extern PyObject *const_tuple_str_plain_GrantTypeBase_tuple;
static PyObject *const_str_digest_98c3ffb3273d178290c8022fb1d11588;
extern PyObject *const_str_digest_08fe0cb1e68b13e3e2a5584b97ab8c6f;
extern PyObject *const_str_digest_cd3e142ba7edbf373f9af32f193dc8b0;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_request_validator;
extern PyObject *const_str_plain_dumps;
extern PyObject *const_tuple_none_true_tuple;
extern PyObject *const_str_plain_log;
static PyObject *const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2;
extern PyObject *const_str_plain_GrantTypeBase;
extern PyObject *const_tuple_80aaca258c5d96cc6d36a8af840923ea_tuple;
extern PyObject *const_str_plain_RequestValidator;
extern PyObject *const_str_plain_base;
extern PyObject *const_str_plain_UnsupportedGrantTypeError;
extern PyObject *const_str_plain_post_token;
extern PyObject *const_int_pos_200;
extern PyObject *const_str_plain_InvalidRequestError;
extern PyObject *const_str_digest_12db482c55f456d3fa96605a189c21fd;
static PyObject *const_str_digest_eb1c78d62a3d3030bb88e6017862dd99;
extern PyObject *const_str_plain___cached__;
extern PyObject *const_str_plain_InvalidScopeError;
extern PyObject *const_str_plain___class__;
extern PyObject *const_str_plain___module__;
extern PyObject *const_str_plain_RefreshTokenGrant;
extern PyObject *const_str_plain_debug;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain_is_within_original_scope;
extern PyObject *const_str_plain_authenticate_client;
extern PyObject *const_int_pos_1;
static PyObject *const_str_digest_0a85429d17cf7c1498bc5d74cde5deef;
static PyObject *const_str_digest_593f75e6de3a53b8e237ecdc0b168189;
extern PyObject *const_str_plain_token_handler;
extern PyObject *const_str_plain_client_authentication_required;
extern PyObject *const_str_plain___prepare__;
extern PyObject *const_str_plain___init__;
extern PyObject *const_str_plain_client;
extern PyObject *const_str_plain_Pragma;
extern PyObject *const_str_digest_8731f29ba21067fcd86e2560f48c09b4;
extern PyObject *const_str_plain_self;
static PyObject *const_str_digest_46e1c89fb94f5988723754dea0b7370c;
extern PyObject *const_str_digest_468773523eb8e0ab1a2621d8a4b4fbf2;
extern PyObject *const_str_plain_kwargs;
static PyObject *const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple;
extern PyObject *const_str_plain_custom_validators;
extern PyObject *const_str_plain_InvalidGrantError;
extern PyObject *const_int_pos_2;
static PyObject *const_str_digest_50648c8293be1086ed1e6a8fd752ea07;
extern PyObject *const_str_plain_logging;
extern PyObject *const_str_empty;
static PyObject *const_str_plain_issue_new_refresh_tokens;
static PyObject *const_str_digest_5cace64d74a86e3d077a283b714130f4;
extern PyObject *const_str_plain__token_modifiers;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 = UNSTREAM_STRING( &constant_bin[ 1721206 ], 49, 0 );
const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple = PyTuple_New( 5 );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 0, const_str_plain_self ); Py_INCREF( const_str_plain_self );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 1, const_str_plain_request_validator ); Py_INCREF( const_str_plain_request_validator );
const_str_plain_issue_new_refresh_tokens = UNSTREAM_STRING( &constant_bin[ 1721255 ], 24, 1 );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 2, const_str_plain_issue_new_refresh_tokens ); Py_INCREF( const_str_plain_issue_new_refresh_tokens );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 3, const_str_plain_kwargs ); Py_INCREF( const_str_plain_kwargs );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 4, const_str_plain___class__ ); Py_INCREF( const_str_plain___class__ );
const_str_plain_original_scopes = UNSTREAM_STRING( &constant_bin[ 1721279 ], 15, 1 );
const_str_digest_012be4d46b429a4aec730cf0f5831f69 = UNSTREAM_STRING( &constant_bin[ 1721294 ], 104, 0 );
const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98 = UNSTREAM_STRING( &constant_bin[ 1721398 ], 40, 0 );
const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple = PyTuple_New( 3 );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 0, const_str_digest_b9c4baf879ebd882d40843df3a4dead7 ); Py_INCREF( const_str_digest_b9c4baf879ebd882d40843df3a4dead7 );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 1, const_str_plain_s ); Py_INCREF( const_str_plain_s );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 2, const_str_plain_original_scopes ); Py_INCREF( const_str_plain_original_scopes );
const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93 = UNSTREAM_STRING( &constant_bin[ 1721438 ], 26, 0 );
const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b = UNSTREAM_STRING( &constant_bin[ 1721464 ], 43, 0 );
const_str_digest_7d87b8a7beb472784c8f817c5cf003af = UNSTREAM_STRING( &constant_bin[ 1721507 ], 36, 0 );
const_str_digest_db37fe24851f7ebc30f9e552d120d953 = UNSTREAM_STRING( &constant_bin[ 1721543 ], 39, 0 );
const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39 = UNSTREAM_STRING( &constant_bin[ 1721582 ], 41, 0 );
const_tuple_22acf86284f4127a5583eccb3d24d717_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 0, const_str_plain_self ); Py_INCREF( const_str_plain_self );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 1, const_str_plain_request ); Py_INCREF( const_str_plain_request );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 2, const_str_plain_validator ); Py_INCREF( const_str_plain_validator );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 3, const_str_plain_original_scopes ); Py_INCREF( const_str_plain_original_scopes );
const_str_digest_98c3ffb3273d178290c8022fb1d11588 = UNSTREAM_STRING( &constant_bin[ 1721623 ], 52, 0 );
const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2 = UNSTREAM_STRING( &constant_bin[ 1721675 ], 32, 0 );
const_str_digest_eb1c78d62a3d3030bb88e6017862dd99 = UNSTREAM_STRING( &constant_bin[ 1721707 ], 42, 0 );
const_str_digest_0a85429d17cf7c1498bc5d74cde5deef = UNSTREAM_STRING( &constant_bin[ 1721749 ], 59, 0 );
const_str_digest_593f75e6de3a53b8e237ecdc0b168189 = UNSTREAM_STRING( &constant_bin[ 1721808 ], 37, 0 );
const_str_digest_46e1c89fb94f5988723754dea0b7370c = UNSTREAM_STRING( &constant_bin[ 1721845 ], 43, 0 );
const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple = PyTuple_New( 1 );
PyTuple_SET_ITEM( const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple, 0, const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 ); Py_INCREF( const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 );
const_str_digest_50648c8293be1086ed1e6a8fd752ea07 = UNSTREAM_STRING( &constant_bin[ 1721888 ], 58, 0 );
const_str_digest_5cace64d74a86e3d077a283b714130f4 = UNSTREAM_STRING( &constant_bin[ 1721946 ], 943, 0 );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_oauthlib$oauth2$rfc6749$grant_types$refresh_token( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_d97b4b0e63e7446557f598731ac2685c;
static PyCodeObject *codeobj_fecfc1a1477f82e7708776ac673a0656;
static PyCodeObject *codeobj_b955a297be0011278f93db2870abd52a;
static PyCodeObject *codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c;
static PyCodeObject *codeobj_63747e9cb9a8f20473e6b2eb0348134b;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_98c3ffb3273d178290c8022fb1d11588 );
codeobj_d97b4b0e63e7446557f598731ac2685c = MAKE_CODEOBJ( module_filename_obj, const_str_angle_genexpr, 121, const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 1, 0, CO_GENERATOR | CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_fecfc1a1477f82e7708776ac673a0656 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_50648c8293be1086ed1e6a8fd752ea07, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_b955a297be0011278f93db2870abd52a = MAKE_CODEOBJ( module_filename_obj, const_str_plain___init__, 25, const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 3, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARKEYWORDS | CO_FUTURE_UNICODE_LITERALS );
codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c = MAKE_CODEOBJ( module_filename_obj, const_str_plain_create_token_response, 33, const_tuple_80aaca258c5d96cc6d36a8af840923ea_tuple, 3, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_63747e9cb9a8f20473e6b2eb0348134b = MAKE_CODEOBJ( module_filename_obj, const_str_plain_validate_token_request, 74, const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 2, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
}
// The module function declarations.
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
static PyObject *oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator, PyObject *yield_return_value );
#else
static void oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator );
#endif
NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_11_complex_call_helper_pos_keywords_star_dict( PyObject **python_pars );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( PyObject *defaults );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( );
// The module function definitions.
static PyObject *impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_self = python_pars[ 0 ];
PyObject *par_request_validator = python_pars[ 1 ];
PyObject *par_issue_new_refresh_tokens = python_pars[ 2 ];
PyObject *par_kwargs = python_pars[ 3 ];
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_value_1;
PyObject *tmp_dircall_arg1_1;
PyObject *tmp_dircall_arg2_1;
PyObject *tmp_dircall_arg3_1;
PyObject *tmp_dircall_arg4_1;
PyObject *tmp_object_name_1;
int tmp_res;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_tuple_element_1;
PyObject *tmp_type_name_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_b955a297be0011278f93db2870abd52a = NULL;
struct Nuitka_FrameObject *frame_b955a297be0011278f93db2870abd52a;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_b955a297be0011278f93db2870abd52a, codeobj_b955a297be0011278f93db2870abd52a, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_b955a297be0011278f93db2870abd52a = cache_frame_b955a297be0011278f93db2870abd52a;
// Push the new frame as the currently active one.
pushFrameStack( frame_b955a297be0011278f93db2870abd52a );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_b955a297be0011278f93db2870abd52a ) == 2 ); // Frame stack
// Framed code:
tmp_type_name_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant );
if (unlikely( tmp_type_name_1 == NULL ))
{
tmp_type_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant );
}
if ( tmp_type_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "RefreshTokenGrant" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_object_name_1 = par_self;
CHECK_OBJECT( tmp_object_name_1 );
tmp_source_name_1 = BUILTIN_SUPER( tmp_type_name_1, tmp_object_name_1 );
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_dircall_arg1_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain___init__ );
Py_DECREF( tmp_source_name_1 );
if ( tmp_dircall_arg1_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_dircall_arg2_1 = PyTuple_New( 1 );
tmp_tuple_element_1 = par_request_validator;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request_validator" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 29;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_dircall_arg2_1, 0, tmp_tuple_element_1 );
tmp_dircall_arg3_1 = _PyDict_NewPresized( 1 );
tmp_dict_key_1 = const_str_plain_issue_new_refresh_tokens;
tmp_dict_value_1 = par_issue_new_refresh_tokens;
if ( tmp_dict_value_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
Py_DECREF( tmp_dircall_arg3_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "issue_new_refresh_tokens" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_dircall_arg3_1, tmp_dict_key_1, tmp_dict_value_1 );
assert( !(tmp_res != 0) );
tmp_dircall_arg4_1 = par_kwargs;
if ( tmp_dircall_arg4_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
Py_DECREF( tmp_dircall_arg3_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "kwargs" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_dircall_arg4_1 );
{
PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1, tmp_dircall_arg4_1};
tmp_unused = impl___internal__$$$function_11_complex_call_helper_pos_keywords_star_dict( dir_call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
#if 0
RESTORE_FRAME_EXCEPTION( frame_b955a297be0011278f93db2870abd52a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_b955a297be0011278f93db2870abd52a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_b955a297be0011278f93db2870abd52a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_b955a297be0011278f93db2870abd52a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_b955a297be0011278f93db2870abd52a, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_b955a297be0011278f93db2870abd52a,
type_description_1,
par_self,
par_request_validator,
par_issue_new_refresh_tokens,
par_kwargs,
NULL
);
// Release cached frame.
if ( frame_b955a297be0011278f93db2870abd52a == cache_frame_b955a297be0011278f93db2870abd52a )
{
Py_DECREF( frame_b955a297be0011278f93db2870abd52a );
}
cache_frame_b955a297be0011278f93db2870abd52a = NULL;
assertFrameObject( frame_b955a297be0011278f93db2870abd52a );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
tmp_return_value = Py_None;
Py_INCREF( tmp_return_value );
goto try_return_handler_1;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__ );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request_validator );
par_request_validator = NULL;
Py_XDECREF( par_issue_new_refresh_tokens );
par_issue_new_refresh_tokens = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request_validator );
par_request_validator = NULL;
Py_XDECREF( par_issue_new_refresh_tokens );
par_issue_new_refresh_tokens = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__ );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_self = python_pars[ 0 ];
PyObject *par_request = python_pars[ 1 ];
PyObject *par_token_handler = python_pars[ 2 ];
PyObject *var_headers = NULL;
PyObject *var_e = NULL;
PyObject *var_token = NULL;
PyObject *var_modifier = NULL;
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
PyObject *exception_keeper_type_4;
PyObject *exception_keeper_value_4;
PyTracebackObject *exception_keeper_tb_4;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4;
PyObject *exception_keeper_type_5;
PyObject *exception_keeper_value_5;
PyTracebackObject *exception_keeper_tb_5;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_5;
PyObject *exception_preserved_type_1;
PyObject *exception_preserved_value_1;
PyTracebackObject *exception_preserved_tb_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_name_1;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_right_1;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_key_2;
PyObject *tmp_dict_value_1;
PyObject *tmp_dict_value_2;
int tmp_exc_match_exception_match_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_next_source_1;
int tmp_res;
bool tmp_result;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
PyObject *tmp_source_name_4;
PyObject *tmp_source_name_5;
PyObject *tmp_source_name_6;
PyObject *tmp_source_name_7;
PyObject *tmp_source_name_8;
PyObject *tmp_source_name_9;
PyObject *tmp_source_name_10;
PyObject *tmp_source_name_11;
PyObject *tmp_source_name_12;
PyObject *tmp_source_name_13;
PyObject *tmp_source_name_14;
PyObject *tmp_tuple_element_1;
PyObject *tmp_tuple_element_2;
PyObject *tmp_tuple_element_3;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c = NULL;
struct Nuitka_FrameObject *frame_4fb8fb5c300d19c3880e6efcc7e0f90c;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
tmp_assign_source_1 = PyDict_Copy( const_dict_b8647fd2e1f76fc4a4a7d9f73ab075f3 );
assert( var_headers == NULL );
var_headers = tmp_assign_source_1;
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c, codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_4fb8fb5c300d19c3880e6efcc7e0f90c = cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c;
// Push the new frame as the currently active one.
pushFrameStack( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_4fb8fb5c300d19c3880e6efcc7e0f90c ) == 2 ); // Frame stack
// Framed code:
// Tried code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_debug );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_args_element_name_1 = const_str_digest_593f75e6de3a53b8e237ecdc0b168189;
tmp_args_element_name_2 = par_request;
if ( tmp_args_element_name_2 == NULL )
{
Py_DECREF( tmp_called_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 58;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
tmp_source_name_2 = par_self;
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_validate_token_request );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_args_element_name_3 = par_request;
if ( tmp_args_element_name_3 == NULL )
{
Py_DECREF( tmp_called_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 59;
{
PyObject *call_args[] = { tmp_args_element_name_3 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_called_name_2 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Preserve existing published exception.
exception_preserved_type_1 = PyThreadState_GET()->exc_type;
Py_XINCREF( exception_preserved_type_1 );
exception_preserved_value_1 = PyThreadState_GET()->exc_value;
Py_XINCREF( exception_preserved_value_1 );
exception_preserved_tb_1 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback;
Py_XINCREF( exception_preserved_tb_1 );
if ( exception_keeper_tb_1 == NULL )
{
exception_keeper_tb_1 = MAKE_TRACEBACK( frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_keeper_lineno_1 );
}
else if ( exception_keeper_lineno_1 != 0 )
{
exception_keeper_tb_1 = ADD_TRACEBACK( exception_keeper_tb_1, frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_keeper_lineno_1 );
}
NORMALIZE_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
PyException_SetTraceback( exception_keeper_value_1, (PyObject *)exception_keeper_tb_1 );
PUBLISH_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 );
// Tried code:
tmp_compare_left_1 = PyThreadState_GET()->exc_type;
tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_3 == NULL ))
{
tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
tmp_compare_right_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_OAuth2Error );
if ( tmp_compare_right_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
tmp_exc_match_exception_match_1 = EXCEPTION_MATCH_BOOL( tmp_compare_left_1, tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compare_right_1 );
exception_lineno = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
Py_DECREF( tmp_compare_right_1 );
if ( tmp_exc_match_exception_match_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_assign_source_2 = PyThreadState_GET()->exc_value;
assert( var_e == NULL );
Py_INCREF( tmp_assign_source_2 );
var_e = tmp_assign_source_2;
// Tried code:
tmp_return_value = PyTuple_New( 3 );
tmp_tuple_element_1 = var_headers;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "headers" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_return_value, 0, tmp_tuple_element_1 );
tmp_source_name_4 = var_e;
CHECK_OBJECT( tmp_source_name_4 );
tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_json );
if ( tmp_tuple_element_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_return_value, 1, tmp_tuple_element_1 );
tmp_source_name_5 = var_e;
if ( tmp_source_name_5 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "e" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_status_code );
if ( tmp_tuple_element_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_return_value, 2, tmp_tuple_element_1 );
goto try_return_handler_4;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_4:;
Py_XDECREF( var_e );
var_e = NULL;
goto try_return_handler_3;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( var_e );
var_e = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto try_except_handler_3;
// End of try:
goto branch_end_1;
branch_no_1:;
tmp_result = RERAISE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
if (unlikely( tmp_result == false ))
{
exception_lineno = 57;
}
if (exception_tb && exception_tb->tb_frame == &frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame) frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = exception_tb->tb_lineno;
type_description_1 = "ooooooo";
goto try_except_handler_3;
branch_end_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_3:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
goto frame_return_exit_1;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto frame_exception_exit_1;
// End of try:
// End of try:
try_end_1:;
tmp_source_name_6 = par_token_handler;
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token_handler" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_create_token );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_name_1 = PyTuple_New( 1 );
tmp_tuple_element_2 = par_request;
if ( tmp_tuple_element_2 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_2 );
tmp_kw_name_1 = _PyDict_NewPresized( 2 );
tmp_dict_key_1 = const_str_plain_refresh_token;
tmp_source_name_7 = par_self;
if ( tmp_source_name_7 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_dict_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_issue_new_refresh_tokens );
if ( tmp_dict_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_lineno = 64;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 );
Py_DECREF( tmp_dict_value_1 );
assert( !(tmp_res != 0) );
tmp_dict_key_2 = const_str_plain_save_token;
tmp_dict_value_2 = Py_False;
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_2, tmp_dict_value_2 );
assert( !(tmp_res != 0) );
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 63;
tmp_assign_source_3 = CALL_FUNCTION( tmp_called_name_3, tmp_args_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_1 );
if ( tmp_assign_source_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
assert( var_token == NULL );
var_token = tmp_assign_source_3;
tmp_source_name_8 = par_self;
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain__token_modifiers );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_assign_source_4 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_4;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_5 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_5 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "ooooooo";
exception_lineno = 66;
goto try_except_handler_5;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_5;
Py_XDECREF( old );
}
tmp_assign_source_6 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_6 );
{
PyObject *old = var_modifier;
var_modifier = tmp_assign_source_6;
Py_INCREF( var_modifier );
Py_XDECREF( old );
}
tmp_called_name_4 = var_modifier;
CHECK_OBJECT( tmp_called_name_4 );
tmp_args_element_name_4 = var_token;
if ( tmp_args_element_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 67;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 67;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 67;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
{
PyObject *old = var_token;
var_token = tmp_assign_source_7;
Py_XDECREF( old );
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
goto loop_start_1;
loop_end_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_5:;
exception_keeper_type_4 = exception_type;
exception_keeper_value_4 = exception_value;
exception_keeper_tb_4 = exception_tb;
exception_keeper_lineno_4 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_4;
exception_value = exception_keeper_value_4;
exception_tb = exception_keeper_tb_4;
exception_lineno = exception_keeper_lineno_4;
goto frame_exception_exit_1;
// End of try:
try_end_2:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_source_name_10 = par_self;
if ( tmp_source_name_10 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_source_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_request_validator );
if ( tmp_source_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_save_token );
Py_DECREF( tmp_source_name_9 );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_token;
if ( tmp_args_element_name_5 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_6 = par_request;
if ( tmp_args_element_name_6 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 68;
{
PyObject *call_args[] = { tmp_args_element_name_5, tmp_args_element_name_6 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_11 == NULL ))
{
tmp_source_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_debug );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_7 = const_str_digest_46e1c89fb94f5988723754dea0b7370c;
tmp_source_name_12 = par_request;
if ( tmp_source_name_12 == NULL )
{
Py_DECREF( tmp_called_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_12, const_str_plain_client_id );
if ( tmp_args_element_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_6 );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_source_name_13 = par_request;
if ( tmp_source_name_13 == NULL )
{
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_13, const_str_plain_client );
if ( tmp_args_element_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_10 = var_token;
if ( tmp_args_element_name_10 == NULL )
{
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
Py_DECREF( tmp_args_element_name_9 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 70;
{
PyObject *call_args[] = { tmp_args_element_name_7, tmp_args_element_name_8, tmp_args_element_name_9, tmp_args_element_name_10 };
tmp_unused = CALL_FUNCTION_WITH_ARGS4( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
Py_DECREF( tmp_args_element_name_9 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_return_value = PyTuple_New( 3 );
tmp_tuple_element_3 = var_headers;
if ( tmp_tuple_element_3 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "headers" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_return_value, 0, tmp_tuple_element_3 );
tmp_source_name_14 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_json );
if (unlikely( tmp_source_name_14 == NULL ))
{
tmp_source_name_14 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_json );
}
if ( tmp_source_name_14 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "json" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_14, const_str_plain_dumps );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_token;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_return_value );
Py_DECREF( tmp_called_name_7 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 72;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_tuple_element_3 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_called_name_7 );
if ( tmp_tuple_element_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
PyTuple_SET_ITEM( tmp_return_value, 1, tmp_tuple_element_3 );
tmp_tuple_element_3 = const_int_pos_200;
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_return_value, 2, tmp_tuple_element_3 );
goto frame_return_exit_1;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_4fb8fb5c300d19c3880e6efcc7e0f90c,
type_description_1,
par_self,
par_request,
par_token_handler,
var_headers,
var_e,
var_token,
var_modifier
);
// Release cached frame.
if ( frame_4fb8fb5c300d19c3880e6efcc7e0f90c == cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c )
{
Py_DECREF( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
}
cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c = NULL;
assertFrameObject( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( par_token_handler );
par_token_handler = NULL;
Py_XDECREF( var_headers );
var_headers = NULL;
Py_XDECREF( var_e );
var_e = NULL;
Py_XDECREF( var_token );
var_token = NULL;
Py_XDECREF( var_modifier );
var_modifier = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_5 = exception_type;
exception_keeper_value_5 = exception_value;
exception_keeper_tb_5 = exception_tb;
exception_keeper_lineno_5 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( par_token_handler );
par_token_handler = NULL;
Py_XDECREF( var_headers );
var_headers = NULL;
Py_XDECREF( var_e );
var_e = NULL;
Py_XDECREF( var_token );
var_token = NULL;
Py_XDECREF( var_modifier );
var_modifier = NULL;
// Re-raise.
exception_type = exception_keeper_type_5;
exception_value = exception_keeper_value_5;
exception_tb = exception_keeper_tb_5;
exception_lineno = exception_keeper_lineno_5;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
static PyObject *impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( struct Nuitka_FunctionObject const *self, PyObject **python_pars )
{
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_self = python_pars[ 0 ];
PyObject *par_request = python_pars[ 1 ];
PyObject *var_validator = NULL;
struct Nuitka_CellObject *var_original_scopes = PyCell_EMPTY();
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *tmp_for_loop_2__for_iterator = NULL;
PyObject *tmp_for_loop_2__iter_value = NULL;
PyObject *tmp_genexpr_1__$0 = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
int tmp_and_left_truth_1;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_value_1;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
PyObject *tmp_args_element_name_7;
PyObject *tmp_args_element_name_8;
PyObject *tmp_args_element_name_9;
PyObject *tmp_args_element_name_10;
PyObject *tmp_args_element_name_11;
PyObject *tmp_args_element_name_12;
PyObject *tmp_args_element_name_13;
PyObject *tmp_args_element_name_14;
PyObject *tmp_args_element_name_15;
PyObject *tmp_args_element_name_16;
PyObject *tmp_args_element_name_17;
PyObject *tmp_args_element_name_18;
PyObject *tmp_args_element_name_19;
PyObject *tmp_args_element_name_20;
PyObject *tmp_args_element_name_21;
PyObject *tmp_args_element_name_22;
PyObject *tmp_args_element_name_23;
PyObject *tmp_args_element_name_24;
PyObject *tmp_args_element_name_25;
PyObject *tmp_args_element_name_26;
PyObject *tmp_args_element_name_27;
PyObject *tmp_args_element_name_28;
PyObject *tmp_args_element_name_29;
PyObject *tmp_args_element_name_30;
PyObject *tmp_args_element_name_31;
PyObject *tmp_args_element_name_32;
PyObject *tmp_args_element_name_33;
PyObject *tmp_assattr_name_1;
PyObject *tmp_assattr_name_2;
PyObject *tmp_assattr_target_1;
PyObject *tmp_assattr_target_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
PyObject *tmp_called_name_4;
PyObject *tmp_called_name_5;
PyObject *tmp_called_name_6;
PyObject *tmp_called_name_7;
PyObject *tmp_called_name_8;
PyObject *tmp_called_name_9;
PyObject *tmp_called_name_10;
PyObject *tmp_called_name_11;
PyObject *tmp_called_name_12;
PyObject *tmp_called_name_13;
PyObject *tmp_called_name_14;
PyObject *tmp_called_name_15;
PyObject *tmp_called_name_16;
PyObject *tmp_called_name_17;
PyObject *tmp_called_name_18;
PyObject *tmp_called_name_19;
PyObject *tmp_called_name_20;
PyObject *tmp_called_name_21;
PyObject *tmp_called_name_22;
PyObject *tmp_called_name_23;
PyObject *tmp_called_name_24;
int tmp_cmp_NotEq_1;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_cond_truth_1;
int tmp_cond_truth_2;
int tmp_cond_truth_3;
int tmp_cond_truth_4;
int tmp_cond_truth_5;
int tmp_cond_truth_6;
PyObject *tmp_cond_value_1;
PyObject *tmp_cond_value_2;
PyObject *tmp_cond_value_3;
PyObject *tmp_cond_value_4;
PyObject *tmp_cond_value_5;
PyObject *tmp_cond_value_6;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_key_2;
PyObject *tmp_dict_key_3;
PyObject *tmp_dict_key_4;
PyObject *tmp_dict_key_5;
PyObject *tmp_dict_key_6;
PyObject *tmp_dict_key_7;
PyObject *tmp_dict_value_1;
PyObject *tmp_dict_value_2;
PyObject *tmp_dict_value_3;
PyObject *tmp_dict_value_4;
PyObject *tmp_dict_value_5;
PyObject *tmp_dict_value_6;
PyObject *tmp_dict_value_7;
bool tmp_is_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_iter_arg_2;
PyObject *tmp_iter_arg_3;
PyObject *tmp_kw_name_1;
PyObject *tmp_kw_name_2;
PyObject *tmp_kw_name_3;
PyObject *tmp_kw_name_4;
PyObject *tmp_kw_name_5;
PyObject *tmp_kw_name_6;
PyObject *tmp_next_source_1;
PyObject *tmp_next_source_2;
PyObject *tmp_operand_name_1;
PyObject *tmp_operand_name_2;
PyObject *tmp_outline_return_value_1;
PyObject *tmp_raise_type_1;
PyObject *tmp_raise_type_2;
PyObject *tmp_raise_type_3;
PyObject *tmp_raise_type_4;
PyObject *tmp_raise_type_5;
PyObject *tmp_raise_type_6;
int tmp_res;
bool tmp_result;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_source_name_2;
PyObject *tmp_source_name_3;
PyObject *tmp_source_name_4;
PyObject *tmp_source_name_5;
PyObject *tmp_source_name_6;
PyObject *tmp_source_name_7;
PyObject *tmp_source_name_8;
PyObject *tmp_source_name_9;
PyObject *tmp_source_name_10;
PyObject *tmp_source_name_11;
PyObject *tmp_source_name_12;
PyObject *tmp_source_name_13;
PyObject *tmp_source_name_14;
PyObject *tmp_source_name_15;
PyObject *tmp_source_name_16;
PyObject *tmp_source_name_17;
PyObject *tmp_source_name_18;
PyObject *tmp_source_name_19;
PyObject *tmp_source_name_20;
PyObject *tmp_source_name_21;
PyObject *tmp_source_name_22;
PyObject *tmp_source_name_23;
PyObject *tmp_source_name_24;
PyObject *tmp_source_name_25;
PyObject *tmp_source_name_26;
PyObject *tmp_source_name_27;
PyObject *tmp_source_name_28;
PyObject *tmp_source_name_29;
PyObject *tmp_source_name_30;
PyObject *tmp_source_name_31;
PyObject *tmp_source_name_32;
PyObject *tmp_source_name_33;
PyObject *tmp_source_name_34;
PyObject *tmp_source_name_35;
PyObject *tmp_source_name_36;
PyObject *tmp_source_name_37;
PyObject *tmp_source_name_38;
PyObject *tmp_source_name_39;
PyObject *tmp_source_name_40;
PyObject *tmp_source_name_41;
PyObject *tmp_source_name_42;
PyObject *tmp_source_name_43;
PyObject *tmp_source_name_44;
PyObject *tmp_source_name_45;
PyObject *tmp_source_name_46;
PyObject *tmp_source_name_47;
PyObject *tmp_source_name_48;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_63747e9cb9a8f20473e6b2eb0348134b = NULL;
struct Nuitka_FrameObject *frame_63747e9cb9a8f20473e6b2eb0348134b;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
tmp_outline_return_value_1 = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_63747e9cb9a8f20473e6b2eb0348134b, codeobj_63747e9cb9a8f20473e6b2eb0348134b, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_63747e9cb9a8f20473e6b2eb0348134b = cache_frame_63747e9cb9a8f20473e6b2eb0348134b;
// Push the new frame as the currently active one.
pushFrameStack( frame_63747e9cb9a8f20473e6b2eb0348134b );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_63747e9cb9a8f20473e6b2eb0348134b ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = par_request;
CHECK_OBJECT( tmp_source_name_1 );
tmp_compare_left_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_grant_type );
if ( tmp_compare_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 76;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_right_1 = const_str_plain_refresh_token;
tmp_cmp_NotEq_1 = RICH_COMPARE_BOOL_NE( tmp_compare_left_1, tmp_compare_right_1 );
if ( tmp_cmp_NotEq_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compare_left_1 );
exception_lineno = 76;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_compare_left_1 );
if ( tmp_cmp_NotEq_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_UnsupportedGrantTypeError );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_1 = _PyDict_NewPresized( 1 );
tmp_dict_key_1 = const_str_plain_request;
tmp_dict_value_1 = par_request;
if ( tmp_dict_value_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 77;
tmp_raise_type_1 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_1 );
Py_DECREF( tmp_kw_name_1 );
if ( tmp_raise_type_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_1;
exception_lineno = 77;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_1:;
tmp_source_name_4 = par_self;
if ( tmp_source_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_custom_validators );
if ( tmp_source_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_pre_token );
Py_DECREF( tmp_source_name_3 );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_1 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_1;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_2 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_2 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
exception_lineno = 79;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_2;
Py_XDECREF( old );
}
tmp_assign_source_3 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_3 );
{
PyObject *old = var_validator;
var_validator = tmp_assign_source_3;
Py_INCREF( var_validator );
Py_XDECREF( old );
}
tmp_called_name_2 = var_validator;
CHECK_OBJECT( tmp_called_name_2 );
tmp_args_element_name_1 = par_request;
if ( tmp_args_element_name_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 80;
type_description_1 = "oooc";
goto try_except_handler_2;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 80;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 80;
type_description_1 = "oooc";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_source_name_5 = par_request;
if ( tmp_source_name_5 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 82;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_left_2 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_refresh_token );
if ( tmp_compare_left_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 82;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_right_2 = Py_None;
tmp_is_1 = ( tmp_compare_left_2 == tmp_compare_right_2 );
Py_DECREF( tmp_compare_left_2 );
if ( tmp_is_1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_6 == NULL ))
{
tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_InvalidRequestError );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_2 = _PyDict_NewPresized( 2 );
tmp_dict_key_2 = const_str_plain_description;
tmp_dict_value_2 = const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2;
tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_2, tmp_dict_value_2 );
assert( !(tmp_res != 0) );
tmp_dict_key_3 = const_str_plain_request;
tmp_dict_value_3 = par_request;
if ( tmp_dict_value_3 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_kw_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 85;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_3, tmp_dict_value_3 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 83;
tmp_raise_type_2 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_3, tmp_kw_name_2 );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_kw_name_2 );
if ( tmp_raise_type_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_2;
exception_lineno = 83;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_2:;
tmp_source_name_8 = par_self;
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain_request_validator );
if ( tmp_source_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_client_authentication_required );
Py_DECREF( tmp_source_name_7 );
if ( tmp_called_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_2 = par_request;
if ( tmp_args_element_name_2 == NULL )
{
Py_DECREF( tmp_called_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 94;
{
PyObject *call_args[] = { tmp_args_element_name_2 };
tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
Py_DECREF( tmp_called_name_4 );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_3;
}
else
{
goto branch_no_3;
}
branch_yes_3:;
tmp_source_name_9 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_9 == NULL ))
{
tmp_source_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_9 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_debug );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = const_str_digest_468773523eb8e0ab1a2621d8a4b4fbf2;
tmp_args_element_name_4 = par_request;
if ( tmp_args_element_name_4 == NULL )
{
Py_DECREF( tmp_called_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 95;
{
PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_5, call_args );
}
Py_DECREF( tmp_called_name_5 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = par_self;
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_10 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_request_validator );
if ( tmp_source_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_authenticate_client );
Py_DECREF( tmp_source_name_10 );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = par_request;
if ( tmp_args_element_name_5 == NULL )
{
Py_DECREF( tmp_called_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 96;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_cond_value_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
if ( tmp_cond_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_2 );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == 1 )
{
goto branch_no_4;
}
else
{
goto branch_yes_4;
}
branch_yes_4:;
tmp_source_name_12 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_12 == NULL ))
{
tmp_source_name_12 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_12 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_12, const_str_plain_debug );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_6 = const_str_digest_7d87b8a7beb472784c8f817c5cf003af;
tmp_args_element_name_7 = par_request;
if ( tmp_args_element_name_7 == NULL )
{
Py_DECREF( tmp_called_name_7 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 97;
{
PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_called_name_7 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_13 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_13 == NULL ))
{
tmp_source_name_13 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_13 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_13, const_str_plain_InvalidClientError );
if ( tmp_called_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_3 = _PyDict_NewPresized( 1 );
tmp_dict_key_4 = const_str_plain_request;
tmp_dict_value_4 = par_request;
if ( tmp_dict_value_4 == NULL )
{
Py_DECREF( tmp_called_name_8 );
Py_DECREF( tmp_kw_name_3 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_3, tmp_dict_key_4, tmp_dict_value_4 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 98;
tmp_raise_type_3 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_8, tmp_kw_name_3 );
Py_DECREF( tmp_called_name_8 );
Py_DECREF( tmp_kw_name_3 );
if ( tmp_raise_type_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_3;
exception_lineno = 98;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_4:;
goto branch_end_3;
branch_no_3:;
tmp_source_name_15 = par_self;
if ( tmp_source_name_15 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_15, const_str_plain_request_validator );
if ( tmp_source_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_14, const_str_plain_authenticate_client_id );
Py_DECREF( tmp_source_name_14 );
if ( tmp_called_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_16 = par_request;
if ( tmp_source_name_16 == NULL )
{
Py_DECREF( tmp_called_name_9 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_16, const_str_plain_client_id );
if ( tmp_args_element_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_9 );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = par_request;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_called_name_9 );
Py_DECREF( tmp_args_element_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 99;
{
PyObject *call_args[] = { tmp_args_element_name_8, tmp_args_element_name_9 };
tmp_cond_value_3 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_9, call_args );
}
Py_DECREF( tmp_called_name_9 );
Py_DECREF( tmp_args_element_name_8 );
if ( tmp_cond_value_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_3 = CHECK_IF_TRUE( tmp_cond_value_3 );
if ( tmp_cond_truth_3 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_3 );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_3 );
if ( tmp_cond_truth_3 == 1 )
{
goto branch_no_5;
}
else
{
goto branch_yes_5;
}
branch_yes_5:;
tmp_source_name_17 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_17 == NULL ))
{
tmp_source_name_17 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_17 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_10 = LOOKUP_ATTRIBUTE( tmp_source_name_17, const_str_plain_debug );
if ( tmp_called_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_10 = const_str_digest_12db482c55f456d3fa96605a189c21fd;
tmp_args_element_name_11 = par_request;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_called_name_10 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_10, tmp_args_element_name_11 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_10, call_args );
}
Py_DECREF( tmp_called_name_10 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_18 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_18 == NULL ))
{
tmp_source_name_18 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_18 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_11 = LOOKUP_ATTRIBUTE( tmp_source_name_18, const_str_plain_InvalidClientError );
if ( tmp_called_name_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_4 = _PyDict_NewPresized( 1 );
tmp_dict_key_5 = const_str_plain_request;
tmp_dict_value_5 = par_request;
if ( tmp_dict_value_5 == NULL )
{
Py_DECREF( tmp_called_name_11 );
Py_DECREF( tmp_kw_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_4, tmp_dict_key_5, tmp_dict_value_5 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 101;
tmp_raise_type_4 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_11, tmp_kw_name_4 );
Py_DECREF( tmp_called_name_11 );
Py_DECREF( tmp_kw_name_4 );
if ( tmp_raise_type_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_4;
exception_lineno = 101;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_5:;
branch_end_3:;
tmp_source_name_19 = par_self;
if ( tmp_source_name_19 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_12 = LOOKUP_ATTRIBUTE( tmp_source_name_19, const_str_plain_validate_grant_type );
if ( tmp_called_name_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = par_request;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_called_name_12 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 104;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_12, call_args );
}
Py_DECREF( tmp_called_name_12 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_20 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_20 == NULL ))
{
tmp_source_name_20 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_20 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_13 = LOOKUP_ATTRIBUTE( tmp_source_name_20, const_str_plain_debug );
if ( tmp_called_name_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_13 = const_str_digest_eb1c78d62a3d3030bb88e6017862dd99;
tmp_source_name_21 = par_request;
if ( tmp_source_name_21 == NULL )
{
Py_DECREF( tmp_called_name_13 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_21, const_str_plain_refresh_token );
if ( tmp_args_element_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_13 );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_22 = par_request;
if ( tmp_source_name_22 == NULL )
{
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_15 = LOOKUP_ATTRIBUTE( tmp_source_name_22, const_str_plain_client );
if ( tmp_args_element_name_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 107;
{
PyObject *call_args[] = { tmp_args_element_name_13, tmp_args_element_name_14, tmp_args_element_name_15 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_13, call_args );
}
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
Py_DECREF( tmp_args_element_name_15 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_24 = par_self;
if ( tmp_source_name_24 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_24, const_str_plain_request_validator );
if ( tmp_source_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_23, const_str_plain_validate_refresh_token );
Py_DECREF( tmp_source_name_23 );
if ( tmp_called_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_25 = par_request;
if ( tmp_source_name_25 == NULL )
{
Py_DECREF( tmp_called_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_16 = LOOKUP_ATTRIBUTE( tmp_source_name_25, const_str_plain_refresh_token );
if ( tmp_args_element_name_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_14 );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_26 = par_request;
if ( tmp_source_name_26 == NULL )
{
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_17 = LOOKUP_ATTRIBUTE( tmp_source_name_26, const_str_plain_client );
if ( tmp_args_element_name_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_18 = par_request;
if ( tmp_args_element_name_18 == NULL )
{
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
Py_DECREF( tmp_args_element_name_17 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 109;
{
PyObject *call_args[] = { tmp_args_element_name_16, tmp_args_element_name_17, tmp_args_element_name_18 };
tmp_cond_value_4 = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_14, call_args );
}
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
Py_DECREF( tmp_args_element_name_17 );
if ( tmp_cond_value_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_4 = CHECK_IF_TRUE( tmp_cond_value_4 );
if ( tmp_cond_truth_4 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_4 );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_4 );
if ( tmp_cond_truth_4 == 1 )
{
goto branch_no_6;
}
else
{
goto branch_yes_6;
}
branch_yes_6:;
tmp_source_name_27 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_27 == NULL ))
{
tmp_source_name_27 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_27 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_15 = LOOKUP_ATTRIBUTE( tmp_source_name_27, const_str_plain_debug );
if ( tmp_called_name_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_19 = const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39;
tmp_source_name_28 = par_request;
if ( tmp_source_name_28 == NULL )
{
Py_DECREF( tmp_called_name_15 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_20 = LOOKUP_ATTRIBUTE( tmp_source_name_28, const_str_plain_refresh_token );
if ( tmp_args_element_name_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_15 );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_29 = par_request;
if ( tmp_source_name_29 == NULL )
{
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_21 = LOOKUP_ATTRIBUTE( tmp_source_name_29, const_str_plain_client );
if ( tmp_args_element_name_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 111;
{
PyObject *call_args[] = { tmp_args_element_name_19, tmp_args_element_name_20, tmp_args_element_name_21 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_15, call_args );
}
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
Py_DECREF( tmp_args_element_name_21 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_30 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_30 == NULL ))
{
tmp_source_name_30 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_30 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_16 = LOOKUP_ATTRIBUTE( tmp_source_name_30, const_str_plain_InvalidGrantError );
if ( tmp_called_name_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_5 = _PyDict_NewPresized( 1 );
tmp_dict_key_6 = const_str_plain_request;
tmp_dict_value_6 = par_request;
if ( tmp_dict_value_6 == NULL )
{
Py_DECREF( tmp_called_name_16 );
Py_DECREF( tmp_kw_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_5, tmp_dict_key_6, tmp_dict_value_6 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 113;
tmp_raise_type_5 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_16, tmp_kw_name_5 );
Py_DECREF( tmp_called_name_16 );
Py_DECREF( tmp_kw_name_5 );
if ( tmp_raise_type_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_5;
exception_lineno = 113;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_6:;
tmp_source_name_31 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils );
if (unlikely( tmp_source_name_31 == NULL ))
{
tmp_source_name_31 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_utils );
}
if ( tmp_source_name_31 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "utils" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_17 = LOOKUP_ATTRIBUTE( tmp_source_name_31, const_str_plain_scope_to_list );
if ( tmp_called_name_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_33 = par_self;
if ( tmp_source_name_33 == NULL )
{
Py_DECREF( tmp_called_name_17 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_32 = LOOKUP_ATTRIBUTE( tmp_source_name_33, const_str_plain_request_validator );
if ( tmp_source_name_32 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_18 = LOOKUP_ATTRIBUTE( tmp_source_name_32, const_str_plain_get_original_scopes );
Py_DECREF( tmp_source_name_32 );
if ( tmp_called_name_18 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_34 = par_request;
if ( tmp_source_name_34 == NULL )
{
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_34, const_str_plain_refresh_token );
if ( tmp_args_element_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_24 = par_request;
if ( tmp_args_element_name_24 == NULL )
{
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
Py_DECREF( tmp_args_element_name_23 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 116;
{
PyObject *call_args[] = { tmp_args_element_name_23, tmp_args_element_name_24 };
tmp_args_element_name_22 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_18, call_args );
}
Py_DECREF( tmp_called_name_18 );
Py_DECREF( tmp_args_element_name_23 );
if ( tmp_args_element_name_22 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 115;
{
PyObject *call_args[] = { tmp_args_element_name_22 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_17, call_args );
}
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_args_element_name_22 );
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
{
PyObject *old = PyCell_GET( var_original_scopes );
PyCell_SET( var_original_scopes, tmp_assign_source_4 );
Py_XDECREF( old );
}
tmp_source_name_35 = par_request;
if ( tmp_source_name_35 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_value_5 = LOOKUP_ATTRIBUTE( tmp_source_name_35, const_str_plain_scope );
if ( tmp_cond_value_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_5 = CHECK_IF_TRUE( tmp_cond_value_5 );
if ( tmp_cond_truth_5 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_5 );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_5 );
if ( tmp_cond_truth_5 == 1 )
{
goto branch_yes_7;
}
else
{
goto branch_no_7;
}
branch_yes_7:;
tmp_source_name_36 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils );
if (unlikely( tmp_source_name_36 == NULL ))
{
tmp_source_name_36 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_utils );
}
if ( tmp_source_name_36 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "utils" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_19 = LOOKUP_ATTRIBUTE( tmp_source_name_36, const_str_plain_scope_to_list );
if ( tmp_called_name_19 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_37 = par_request;
if ( tmp_source_name_37 == NULL )
{
Py_DECREF( tmp_called_name_19 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_25 = LOOKUP_ATTRIBUTE( tmp_source_name_37, const_str_plain_scope );
if ( tmp_args_element_name_25 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_19 );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 120;
{
PyObject *call_args[] = { tmp_args_element_name_25 };
tmp_assattr_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_19, call_args );
}
Py_DECREF( tmp_called_name_19 );
Py_DECREF( tmp_args_element_name_25 );
if ( tmp_assattr_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assattr_target_1 = par_request;
if ( tmp_assattr_target_1 == NULL )
{
Py_DECREF( tmp_assattr_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_result = SET_ATTRIBUTE( tmp_assattr_target_1, const_str_plain_scopes, tmp_assattr_name_1 );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_assattr_name_1 );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_assattr_name_1 );
tmp_called_name_20 = LOOKUP_BUILTIN( const_str_plain_all );
assert( tmp_called_name_20 != NULL );
tmp_source_name_38 = par_request;
if ( tmp_source_name_38 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_2 = LOOKUP_ATTRIBUTE( tmp_source_name_38, const_str_plain_scopes );
if ( tmp_iter_arg_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_5 = MAKE_ITERATOR( tmp_iter_arg_2 );
Py_DECREF( tmp_iter_arg_2 );
if ( tmp_assign_source_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_genexpr_1__$0 == NULL );
tmp_genexpr_1__$0 = tmp_assign_source_5;
// Tried code:
tmp_outline_return_value_1 = Nuitka_Generator_New(
oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context,
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
const_str_angle_genexpr,
#if PYTHON_VERSION >= 350
const_str_digest_0a85429d17cf7c1498bc5d74cde5deef,
#endif
codeobj_d97b4b0e63e7446557f598731ac2685c,
2
);
((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[0] = PyCell_NEW0( tmp_genexpr_1__$0 );
((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[1] = var_original_scopes;
Py_INCREF( ((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[1] );
assert( Py_SIZE( tmp_outline_return_value_1 ) >= 2 );
goto try_return_handler_3;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
// Return handler code:
try_return_handler_3:;
CHECK_OBJECT( (PyObject *)tmp_genexpr_1__$0 );
Py_DECREF( tmp_genexpr_1__$0 );
tmp_genexpr_1__$0 = NULL;
goto outline_result_1;
// End of try:
CHECK_OBJECT( (PyObject *)tmp_genexpr_1__$0 );
Py_DECREF( tmp_genexpr_1__$0 );
tmp_genexpr_1__$0 = NULL;
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
outline_result_1:;
tmp_args_element_name_26 = tmp_outline_return_value_1;
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 121;
{
PyObject *call_args[] = { tmp_args_element_name_26 };
tmp_operand_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_20, call_args );
}
Py_DECREF( tmp_args_element_name_26 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_and_left_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 );
Py_DECREF( tmp_operand_name_1 );
if ( tmp_and_left_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 );
if ( tmp_and_left_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
if ( tmp_and_left_truth_1 == 1 )
{
goto and_right_1;
}
else
{
goto and_left_1;
}
and_right_1:;
tmp_source_name_40 = par_self;
if ( tmp_source_name_40 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_39 = LOOKUP_ATTRIBUTE( tmp_source_name_40, const_str_plain_request_validator );
if ( tmp_source_name_39 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_21 = LOOKUP_ATTRIBUTE( tmp_source_name_39, const_str_plain_is_within_original_scope );
Py_DECREF( tmp_source_name_39 );
if ( tmp_called_name_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_41 = par_request;
if ( tmp_source_name_41 == NULL )
{
Py_DECREF( tmp_called_name_21 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_27 = LOOKUP_ATTRIBUTE( tmp_source_name_41, const_str_plain_scopes );
if ( tmp_args_element_name_27 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_21 );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_42 = par_request;
if ( tmp_source_name_42 == NULL )
{
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_28 = LOOKUP_ATTRIBUTE( tmp_source_name_42, const_str_plain_refresh_token );
if ( tmp_args_element_name_28 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_29 = par_request;
if ( tmp_args_element_name_29 == NULL )
{
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
Py_DECREF( tmp_args_element_name_28 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 122;
{
PyObject *call_args[] = { tmp_args_element_name_27, tmp_args_element_name_28, tmp_args_element_name_29 };
tmp_operand_name_2 = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_21, call_args );
}
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
Py_DECREF( tmp_args_element_name_28 );
if ( tmp_operand_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_2 );
Py_DECREF( tmp_operand_name_2 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_value_6 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_6 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_6 = CHECK_IF_TRUE( tmp_cond_value_6 );
if ( tmp_cond_truth_6 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
if ( tmp_cond_truth_6 == 1 )
{
goto branch_yes_8;
}
else
{
goto branch_no_8;
}
branch_yes_8:;
tmp_source_name_43 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_43 == NULL ))
{
tmp_source_name_43 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_43 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_22 = LOOKUP_ATTRIBUTE( tmp_source_name_43, const_str_plain_debug );
if ( tmp_called_name_22 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_30 = const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b;
tmp_source_name_44 = par_request;
if ( tmp_source_name_44 == NULL )
{
Py_DECREF( tmp_called_name_22 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_31 = LOOKUP_ATTRIBUTE( tmp_source_name_44, const_str_plain_refresh_token );
if ( tmp_args_element_name_31 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_22 );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_45 = par_request;
if ( tmp_source_name_45 == NULL )
{
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_32 = LOOKUP_ATTRIBUTE( tmp_source_name_45, const_str_plain_scopes );
if ( tmp_args_element_name_32 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 124;
{
PyObject *call_args[] = { tmp_args_element_name_30, tmp_args_element_name_31, tmp_args_element_name_32 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_22, call_args );
}
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
Py_DECREF( tmp_args_element_name_32 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_46 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_46 == NULL ))
{
tmp_source_name_46 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_46 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_46, const_str_plain_InvalidScopeError );
if ( tmp_called_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_6 = _PyDict_NewPresized( 1 );
tmp_dict_key_7 = const_str_plain_request;
tmp_dict_value_7 = par_request;
if ( tmp_dict_value_7 == NULL )
{
Py_DECREF( tmp_called_name_23 );
Py_DECREF( tmp_kw_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_6, tmp_dict_key_7, tmp_dict_value_7 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 126;
tmp_raise_type_6 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_23, tmp_kw_name_6 );
Py_DECREF( tmp_called_name_23 );
Py_DECREF( tmp_kw_name_6 );
if ( tmp_raise_type_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_6;
exception_lineno = 126;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_8:;
goto branch_end_7;
branch_no_7:;
if ( var_original_scopes == NULL )
{
tmp_assattr_name_2 = NULL;
}
else
{
tmp_assattr_name_2 = PyCell_GET( var_original_scopes );
}
if ( tmp_assattr_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_scopes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assattr_target_2 = par_request;
if ( tmp_assattr_target_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_result = SET_ATTRIBUTE( tmp_assattr_target_2, const_str_plain_scopes, tmp_assattr_name_2 );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
branch_end_7:;
tmp_source_name_48 = par_self;
if ( tmp_source_name_48 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_47 = LOOKUP_ATTRIBUTE( tmp_source_name_48, const_str_plain_custom_validators );
if ( tmp_source_name_47 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_3 = LOOKUP_ATTRIBUTE( tmp_source_name_47, const_str_plain_post_token );
Py_DECREF( tmp_source_name_47 );
if ( tmp_iter_arg_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_6 = MAKE_ITERATOR( tmp_iter_arg_3 );
Py_DECREF( tmp_iter_arg_3 );
if ( tmp_assign_source_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_2__for_iterator == NULL );
tmp_for_loop_2__for_iterator = tmp_assign_source_6;
// Tried code:
loop_start_2:;
tmp_next_source_2 = tmp_for_loop_2__for_iterator;
CHECK_OBJECT( tmp_next_source_2 );
tmp_assign_source_7 = ITERATOR_NEXT( tmp_next_source_2 );
if ( tmp_assign_source_7 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_2;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
exception_lineno = 130;
goto try_except_handler_4;
}
}
{
PyObject *old = tmp_for_loop_2__iter_value;
tmp_for_loop_2__iter_value = tmp_assign_source_7;
Py_XDECREF( old );
}
tmp_assign_source_8 = tmp_for_loop_2__iter_value;
CHECK_OBJECT( tmp_assign_source_8 );
{
PyObject *old = var_validator;
var_validator = tmp_assign_source_8;
Py_INCREF( var_validator );
Py_XDECREF( old );
}
tmp_called_name_24 = var_validator;
CHECK_OBJECT( tmp_called_name_24 );
tmp_args_element_name_33 = par_request;
if ( tmp_args_element_name_33 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 131;
type_description_1 = "oooc";
goto try_except_handler_4;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 131;
{
PyObject *call_args[] = { tmp_args_element_name_33 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_24, call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 131;
type_description_1 = "oooc";
goto try_except_handler_4;
}
Py_DECREF( tmp_unused );
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto try_except_handler_4;
}
goto loop_start_2;
loop_end_2:;
goto try_end_2;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto frame_exception_exit_1;
// End of try:
try_end_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_63747e9cb9a8f20473e6b2eb0348134b );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_63747e9cb9a8f20473e6b2eb0348134b );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_63747e9cb9a8f20473e6b2eb0348134b, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_63747e9cb9a8f20473e6b2eb0348134b, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_63747e9cb9a8f20473e6b2eb0348134b,
type_description_1,
par_self,
par_request,
var_validator,
var_original_scopes
);
// Release cached frame.
if ( frame_63747e9cb9a8f20473e6b2eb0348134b == cache_frame_63747e9cb9a8f20473e6b2eb0348134b )
{
Py_DECREF( frame_63747e9cb9a8f20473e6b2eb0348134b );
}
cache_frame_63747e9cb9a8f20473e6b2eb0348134b = NULL;
assertFrameObject( frame_63747e9cb9a8f20473e6b2eb0348134b );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
Py_XDECREF( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = NULL;
tmp_return_value = Py_None;
Py_INCREF( tmp_return_value );
goto try_return_handler_1;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( var_validator );
var_validator = NULL;
CHECK_OBJECT( (PyObject *)var_original_scopes );
Py_DECREF( var_original_scopes );
var_original_scopes = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( var_validator );
var_validator = NULL;
CHECK_OBJECT( (PyObject *)var_original_scopes );
Py_DECREF( var_original_scopes );
var_original_scopes = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return NULL;
function_return_exit:
CHECK_OBJECT( tmp_return_value );
assert( had_error || !ERROR_OCCURRED() );
return tmp_return_value;
}
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
struct oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_locals {
PyObject *var_s
PyObject *tmp_iter_value_0
PyObject *exception_type
PyObject *exception_value
PyTracebackObject *exception_tb
int exception_lineno
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
int exception_keeper_lineno_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_next_source_1;
char const *type_description_1
};
#endif
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
static PyObject *oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator, PyObject *yield_return_value )
#else
static void oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator )
#endif
{
CHECK_OBJECT( (PyObject *)generator );
assert( Nuitka_Generator_Check( (PyObject *)generator ) );
// Local variable initialization
PyObject *var_s = NULL;
PyObject *tmp_iter_value_0 = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_next_source_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_generator = NULL;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Dispatch to yield based on return label index:
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_generator, codeobj_d97b4b0e63e7446557f598731ac2685c, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *) );
generator->m_frame = cache_frame_generator;
// Mark the frame object as in use, ref count 1 will be up for reuse.
Py_INCREF( generator->m_frame );
assert( Py_REFCNT( generator->m_frame ) == 2 ); // Frame stack
#if PYTHON_VERSION >= 340
generator->m_frame->m_frame.f_gen = (PyObject *)generator;
#endif
Py_CLEAR( generator->m_frame->m_frame.f_back );
generator->m_frame->m_frame.f_back = PyThreadState_GET()->frame;
Py_INCREF( generator->m_frame->m_frame.f_back );
PyThreadState_GET()->frame = &generator->m_frame->m_frame;
Py_INCREF( generator->m_frame );
Nuitka_Frame_MarkAsExecuting( generator->m_frame );
#if PYTHON_VERSION >= 300
// Accept currently existing exception as the one to publish again when we
// yield or yield from.
PyThreadState *thread_state = PyThreadState_GET();
generator->m_frame->m_frame.f_exc_type = thread_state->exc_type;
if ( generator->m_frame->m_frame.f_exc_type == Py_None ) generator->m_frame->m_frame.f_exc_type = NULL;
Py_XINCREF( generator->m_frame->m_frame.f_exc_type );
generator->m_frame->m_frame.f_exc_value = thread_state->exc_value;
Py_XINCREF( generator->m_frame->m_frame.f_exc_value );
generator->m_frame->m_frame.f_exc_traceback = thread_state->exc_traceback;
Py_XINCREF( generator->m_frame->m_frame.f_exc_traceback );
#endif
// Framed code:
// Tried code:
loop_start_1:;
if ( generator->m_closure[0] == NULL )
{
tmp_next_source_1 = NULL;
}
else
{
tmp_next_source_1 = PyCell_GET( generator->m_closure[0] );
}
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_1 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_1 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "Noc";
exception_lineno = 121;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_iter_value_0;
tmp_iter_value_0 = tmp_assign_source_1;
Py_XDECREF( old );
}
tmp_assign_source_2 = tmp_iter_value_0;
CHECK_OBJECT( tmp_assign_source_2 );
{
PyObject *old = var_s;
var_s = tmp_assign_source_2;
Py_INCREF( var_s );
Py_XDECREF( old );
}
tmp_compexpr_left_1 = var_s;
CHECK_OBJECT( tmp_compexpr_left_1 );
if ( generator->m_closure[1] == NULL )
{
tmp_compexpr_right_1 = NULL;
}
else
{
tmp_compexpr_right_1 = PyCell_GET( generator->m_closure[1] );
}
if ( tmp_compexpr_right_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "original_scopes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
tmp_expression_name_1 = SEQUENCE_CONTAINS( tmp_compexpr_left_1, tmp_compexpr_right_1 );
if ( tmp_expression_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
Py_INCREF( tmp_expression_name_1 );
tmp_unused = GENERATOR_YIELD( generator, tmp_expression_name_1 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_iter_value_0 );
tmp_iter_value_0 = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Nuitka_Frame_MarkAsNotExecuting( generator->m_frame );
#if PYTHON_VERSION >= 300
Py_CLEAR( generator->m_frame->m_frame.f_exc_type );
Py_CLEAR( generator->m_frame->m_frame.f_exc_value );
Py_CLEAR( generator->m_frame->m_frame.f_exc_traceback );
#endif
// Allow re-use of the frame again.
Py_DECREF( generator->m_frame );
goto frame_no_exception_1;
frame_exception_exit_1:;
// If it's not an exit exception, consider and create a traceback for it.
if ( !EXCEPTION_MATCH_GENERATOR( exception_type ) )
{
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( generator->m_frame, exception_lineno );
}
else if ( exception_tb->tb_frame != &generator->m_frame->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, generator->m_frame, exception_lineno );
}
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)generator->m_frame,
type_description_1,
NULL,
var_s,
generator->m_closure[1]
);
// Release cached frame.
if ( generator->m_frame == cache_frame_generator )
{
Py_DECREF( generator->m_frame );
}
cache_frame_generator = NULL;
assertFrameObject( generator->m_frame );
}
#if PYTHON_VERSION >= 300
Py_CLEAR( generator->m_frame->m_frame.f_exc_type );
Py_CLEAR( generator->m_frame->m_frame.f_exc_value );
Py_CLEAR( generator->m_frame->m_frame.f_exc_traceback );
#endif
Py_DECREF( generator->m_frame );
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( var_s );
var_s = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto function_exception_exit;
// End of try:
try_end_2:;
Py_XDECREF( tmp_iter_value_0 );
tmp_iter_value_0 = NULL;
Py_XDECREF( var_s );
var_s = NULL;
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
return NULL;
#else
generator->m_yielded = NULL;
return;
#endif
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
return NULL;
#else
generator->m_yielded = NULL;
return;
#endif
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( PyObject *defaults )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__,
const_str_plain___init__,
#if PYTHON_VERSION >= 330
const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93,
#endif
codeobj_b955a297be0011278f93db2870abd52a,
defaults,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
Py_None,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response,
const_str_plain_create_token_response,
#if PYTHON_VERSION >= 330
const_str_digest_db37fe24851f7ebc30f9e552d120d953,
#endif
codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
const_str_digest_5cace64d74a86e3d077a283b714130f4,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request,
const_str_plain_validate_token_request,
#if PYTHON_VERSION >= 330
const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98,
#endif
codeobj_63747e9cb9a8f20473e6b2eb0348134b,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
Py_None,
0
);
return (PyObject *)result;
}
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_oauthlib$oauth2$rfc6749$grant_types$refresh_token =
{
PyModuleDef_HEAD_INIT,
"oauthlib.oauth2.rfc6749.grant_types.refresh_token", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PYTHON_VERSION >= 300
extern PyObject *metapath_based_loader;
#endif
#if PYTHON_VERSION >= 330
extern PyObject *const_str_plain___loader__;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
#if PYTHON_VERSION >= 350
extern void _initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
extern void _initCompiledAsyncgenTypes();
#endif
// The exported interface to CPython. On import of the module, this function
// gets called. It has to have an exact function name, in cases it's a shared
// library export. This is hidden behind the MOD_INIT_DECL.
MOD_INIT_DECL( oauthlib$oauth2$rfc6749$grant_types$refresh_token )
{
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if ( _init_done )
{
return MOD_RETURN_VALUE( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
}
else
{
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION >= 350
_initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
_initCompiledAsyncgenTypes();
#endif
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("oauthlib.oauth2.rfc6749.grant_types.refresh_token: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("oauthlib.oauth2.rfc6749.grant_types.refresh_token: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initoauthlib$oauth2$rfc6749$grant_types$refresh_token" );
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
#if PYTHON_VERSION < 300
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token = Py_InitModule4(
"oauthlib.oauth2.rfc6749.grant_types.refresh_token", // Module Name
NULL, // No methods initially, all are added
// dynamically in actual module code only.
NULL, // No __doc__ is initially set, as it could
// not contain NUL this way, added early in
// actual code.
NULL, // No self for modules, we don't use it.
PYTHON_API_VERSION
);
#else
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token = PyModule_Create( &mdef_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
#endif
moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token = MODULE_DICT( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
CHECK_OBJECT( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
{
int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
assert( r != -1 );
}
#endif
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if ( GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict( value );
#endif
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *outline_0_var___class__ = NULL;
PyObject *outline_0_var___qualname__ = NULL;
PyObject *outline_0_var___module__ = NULL;
PyObject *outline_0_var___doc__ = NULL;
PyObject *outline_0_var___init__ = NULL;
PyObject *outline_0_var_create_token_response = NULL;
PyObject *outline_0_var_validate_token_request = NULL;
PyObject *tmp_class_creation_1__bases = NULL;
PyObject *tmp_class_creation_1__class_decl_dict = NULL;
PyObject *tmp_class_creation_1__metaclass = NULL;
PyObject *tmp_class_creation_1__prepared = NULL;
PyObject *tmp_import_from_1__module = NULL;
PyObject *tmp_import_from_2__module = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
PyObject *exception_keeper_type_4;
PyObject *exception_keeper_value_4;
PyTracebackObject *exception_keeper_tb_4;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_name_1;
PyObject *tmp_args_name_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_assign_source_9;
PyObject *tmp_assign_source_10;
PyObject *tmp_assign_source_11;
PyObject *tmp_assign_source_12;
PyObject *tmp_assign_source_13;
PyObject *tmp_assign_source_14;
PyObject *tmp_assign_source_15;
PyObject *tmp_assign_source_16;
PyObject *tmp_assign_source_17;
PyObject *tmp_assign_source_18;
PyObject *tmp_assign_source_19;
PyObject *tmp_assign_source_20;
PyObject *tmp_assign_source_21;
PyObject *tmp_assign_source_22;
PyObject *tmp_assign_source_23;
PyObject *tmp_assign_source_24;
PyObject *tmp_assign_source_25;
PyObject *tmp_assign_source_26;
PyObject *tmp_assign_source_27;
PyObject *tmp_assign_source_28;
PyObject *tmp_assign_source_29;
PyObject *tmp_bases_name_1;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
int tmp_cmp_In_1;
int tmp_cmp_In_2;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_defaults_1;
PyObject *tmp_dict_name_1;
PyObject *tmp_dictdel_dict;
PyObject *tmp_dictdel_key;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_fromlist_name_2;
PyObject *tmp_fromlist_name_3;
PyObject *tmp_fromlist_name_4;
PyObject *tmp_fromlist_name_5;
PyObject *tmp_globals_name_1;
PyObject *tmp_globals_name_2;
PyObject *tmp_globals_name_3;
PyObject *tmp_globals_name_4;
PyObject *tmp_globals_name_5;
PyObject *tmp_hasattr_attr_1;
PyObject *tmp_hasattr_source_1;
PyObject *tmp_import_name_from_1;
PyObject *tmp_import_name_from_2;
PyObject *tmp_import_name_from_3;
PyObject *tmp_import_name_from_4;
PyObject *tmp_import_name_from_5;
PyObject *tmp_import_name_from_6;
PyObject *tmp_key_name_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_kw_name_2;
PyObject *tmp_level_name_1;
PyObject *tmp_level_name_2;
PyObject *tmp_level_name_3;
PyObject *tmp_level_name_4;
PyObject *tmp_level_name_5;
PyObject *tmp_locals_name_1;
PyObject *tmp_locals_name_2;
PyObject *tmp_locals_name_3;
PyObject *tmp_locals_name_4;
PyObject *tmp_locals_name_5;
PyObject *tmp_metaclass_name_1;
PyObject *tmp_name_name_1;
PyObject *tmp_name_name_2;
PyObject *tmp_name_name_3;
PyObject *tmp_name_name_4;
PyObject *tmp_name_name_5;
PyObject *tmp_outline_return_value_1;
int tmp_res;
bool tmp_result;
PyObject *tmp_set_locals;
PyObject *tmp_source_name_1;
PyObject *tmp_subscribed_name_1;
PyObject *tmp_subscript_name_1;
PyObject *tmp_tuple_element_1;
PyObject *tmp_tuple_element_2;
PyObject *tmp_tuple_element_3;
PyObject *tmp_type_arg_1;
struct Nuitka_FrameObject *frame_fecfc1a1477f82e7708776ac673a0656;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_outline_return_value_1 = NULL;
// Locals dictionary setup.
PyObject *locals_dict_1 = PyDict_New();
// Module code.
tmp_assign_source_1 = const_str_digest_8731f29ba21067fcd86e2560f48c09b4;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_fecfc1a1477f82e7708776ac673a0656 = MAKE_MODULE_FRAME( codeobj_fecfc1a1477f82e7708776ac673a0656, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_fecfc1a1477f82e7708776ac673a0656 );
assert( Py_REFCNT( frame_fecfc1a1477f82e7708776ac673a0656 ) == 2 );
// Framed code:
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 1;
{
PyObject *module = PyImport_ImportModule("importlib._bootstrap");
if (likely( module != NULL ))
{
tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );
}
else
{
tmp_called_name_1 = NULL;
}
}
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5;
tmp_args_element_name_2 = metapath_based_loader;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 1;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_digest_08fe0cb1e68b13e3e2a5584b97ab8c6f;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 6;
tmp_assign_source_7 = PyImport_ImportModule("__future__");
assert( tmp_assign_source_7 != NULL );
assert( tmp_import_from_1__module == NULL );
Py_INCREF( tmp_assign_source_7 );
tmp_import_from_1__module = tmp_assign_source_7;
// Tried code:
tmp_import_name_from_1 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_1 );
tmp_assign_source_8 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_absolute_import );
if ( tmp_assign_source_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_absolute_import, tmp_assign_source_8 );
tmp_import_name_from_2 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_2 );
tmp_assign_source_9 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_unicode_literals );
if ( tmp_assign_source_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 6;
goto try_except_handler_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_9 );
goto try_end_1;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
Py_XDECREF( tmp_import_from_1__module );
tmp_import_from_1__module = NULL;
tmp_name_name_1 = const_str_plain_json;
tmp_globals_name_1 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = Py_None;
tmp_level_name_1 = const_int_0;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 8;
tmp_assign_source_10 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );
if ( tmp_assign_source_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 8;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_json, tmp_assign_source_10 );
tmp_name_name_2 = const_str_plain_logging;
tmp_globals_name_2 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = Py_None;
tmp_level_name_2 = const_int_0;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 9;
tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );
if ( tmp_assign_source_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 9;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_logging, tmp_assign_source_11 );
tmp_name_name_3 = const_str_empty;
tmp_globals_name_3 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_3 = Py_None;
tmp_fromlist_name_3 = const_tuple_str_plain_errors_str_plain_utils_tuple;
tmp_level_name_3 = const_int_pos_2;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 11;
tmp_assign_source_12 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 );
if ( tmp_assign_source_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto frame_exception_exit_1;
}
assert( tmp_import_from_2__module == NULL );
tmp_import_from_2__module = tmp_assign_source_12;
// Tried code:
tmp_import_name_from_3 = tmp_import_from_2__module;
CHECK_OBJECT( tmp_import_name_from_3 );
tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_errors );
if ( tmp_assign_source_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto try_except_handler_2;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors, tmp_assign_source_13 );
tmp_import_name_from_4 = tmp_import_from_2__module;
CHECK_OBJECT( tmp_import_name_from_4 );
tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_utils );
if ( tmp_assign_source_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto try_except_handler_2;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils, tmp_assign_source_14 );
goto try_end_2;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_import_from_2__module );
tmp_import_from_2__module = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto frame_exception_exit_1;
// End of try:
try_end_2:;
Py_XDECREF( tmp_import_from_2__module );
tmp_import_from_2__module = NULL;
tmp_name_name_4 = const_str_plain_request_validator;
tmp_globals_name_4 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_4 = Py_None;
tmp_fromlist_name_4 = const_tuple_str_plain_RequestValidator_tuple;
tmp_level_name_4 = const_int_pos_2;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 12;
tmp_import_name_from_5 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 );
if ( tmp_import_name_from_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_RequestValidator );
Py_DECREF( tmp_import_name_from_5 );
if ( tmp_assign_source_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RequestValidator, tmp_assign_source_15 );
tmp_name_name_5 = const_str_plain_base;
tmp_globals_name_5 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_5 = Py_None;
tmp_fromlist_name_5 = const_tuple_str_plain_GrantTypeBase_tuple;
tmp_level_name_5 = const_int_pos_1;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 13;
tmp_import_name_from_6 = IMPORT_MODULE5( tmp_name_name_5, tmp_globals_name_5, tmp_locals_name_5, tmp_fromlist_name_5, tmp_level_name_5 );
if ( tmp_import_name_from_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_GrantTypeBase );
Py_DECREF( tmp_import_name_from_6 );
if ( tmp_assign_source_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_GrantTypeBase, tmp_assign_source_16 );
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_logging );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_logging );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "logging" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 15;
goto frame_exception_exit_1;
}
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 15;
tmp_assign_source_17 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_1, const_str_plain_getLogger, &PyTuple_GET_ITEM( const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple, 0 ) );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 15;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log, tmp_assign_source_17 );
// Tried code:
tmp_assign_source_18 = PyTuple_New( 1 );
tmp_tuple_element_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_GrantTypeBase );
if (unlikely( tmp_tuple_element_1 == NULL ))
{
tmp_tuple_element_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_GrantTypeBase );
}
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_assign_source_18 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "GrantTypeBase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 18;
goto try_except_handler_3;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_assign_source_18, 0, tmp_tuple_element_1 );
assert( tmp_class_creation_1__bases == NULL );
tmp_class_creation_1__bases = tmp_assign_source_18;
tmp_assign_source_19 = PyDict_New();
assert( tmp_class_creation_1__class_decl_dict == NULL );
tmp_class_creation_1__class_decl_dict = tmp_assign_source_19;
tmp_compare_left_1 = const_str_plain_metaclass;
tmp_compare_right_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_compare_right_1 );
tmp_cmp_In_1 = PySequence_Contains( tmp_compare_right_1, tmp_compare_left_1 );
assert( !(tmp_cmp_In_1 == -1) );
if ( tmp_cmp_In_1 == 1 )
{
goto condexpr_true_1;
}
else
{
goto condexpr_false_1;
}
condexpr_true_1:;
tmp_dict_name_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_dict_name_1 );
tmp_key_name_1 = const_str_plain_metaclass;
tmp_metaclass_name_1 = DICT_GET_ITEM( tmp_dict_name_1, tmp_key_name_1 );
if ( tmp_metaclass_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_1;
condexpr_false_1:;
tmp_cond_value_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_cond_value_1 );
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
if ( tmp_cond_truth_1 == 1 )
{
goto condexpr_true_2;
}
else
{
goto condexpr_false_2;
}
condexpr_true_2:;
tmp_subscribed_name_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_subscribed_name_1 );
tmp_subscript_name_1 = const_int_0;
tmp_type_arg_1 = LOOKUP_SUBSCRIPT( tmp_subscribed_name_1, tmp_subscript_name_1 );
if ( tmp_type_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
tmp_metaclass_name_1 = BUILTIN_TYPE1( tmp_type_arg_1 );
Py_DECREF( tmp_type_arg_1 );
if ( tmp_metaclass_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_2;
condexpr_false_2:;
tmp_metaclass_name_1 = (PyObject *)&PyType_Type;
Py_INCREF( tmp_metaclass_name_1 );
condexpr_end_2:;
condexpr_end_1:;
tmp_bases_name_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_bases_name_1 );
tmp_assign_source_20 = SELECT_METACLASS( tmp_metaclass_name_1, tmp_bases_name_1 );
if ( tmp_assign_source_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_metaclass_name_1 );
exception_lineno = 18;
goto try_except_handler_3;
}
Py_DECREF( tmp_metaclass_name_1 );
assert( tmp_class_creation_1__metaclass == NULL );
tmp_class_creation_1__metaclass = tmp_assign_source_20;
tmp_compare_left_2 = const_str_plain_metaclass;
tmp_compare_right_2 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_compare_right_2 );
tmp_cmp_In_2 = PySequence_Contains( tmp_compare_right_2, tmp_compare_left_2 );
assert( !(tmp_cmp_In_2 == -1) );
if ( tmp_cmp_In_2 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_dictdel_dict = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_dictdel_dict );
tmp_dictdel_key = const_str_plain_metaclass;
tmp_result = DICT_REMOVE_ITEM( tmp_dictdel_dict, tmp_dictdel_key );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
branch_no_1:;
tmp_hasattr_source_1 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_hasattr_source_1 );
tmp_hasattr_attr_1 = const_str_plain___prepare__;
tmp_res = PyObject_HasAttr( tmp_hasattr_source_1, tmp_hasattr_attr_1 );
if ( tmp_res == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
if ( tmp_res == 1 )
{
goto condexpr_true_3;
}
else
{
goto condexpr_false_3;
}
condexpr_true_3:;
tmp_source_name_1 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_source_name_1 );
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain___prepare__ );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
tmp_args_name_1 = PyTuple_New( 2 );
tmp_tuple_element_2 = const_str_plain_RefreshTokenGrant;
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_2 );
tmp_tuple_element_2 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_tuple_element_2 );
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_2 );
tmp_kw_name_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_kw_name_1 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 18;
tmp_assign_source_21 = CALL_FUNCTION( tmp_called_name_2, tmp_args_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_2 );
Py_DECREF( tmp_args_name_1 );
if ( tmp_assign_source_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_3;
condexpr_false_3:;
tmp_assign_source_21 = PyDict_New();
condexpr_end_3:;
assert( tmp_class_creation_1__prepared == NULL );
tmp_class_creation_1__prepared = tmp_assign_source_21;
tmp_set_locals = tmp_class_creation_1__prepared;
CHECK_OBJECT( tmp_set_locals );
Py_DECREF(locals_dict_1);
locals_dict_1 = tmp_set_locals;
Py_INCREF( tmp_set_locals );
tmp_assign_source_23 = const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5;
assert( outline_0_var___module__ == NULL );
Py_INCREF( tmp_assign_source_23 );
outline_0_var___module__ = tmp_assign_source_23;
tmp_assign_source_24 = const_str_digest_012be4d46b429a4aec730cf0f5831f69;
assert( outline_0_var___doc__ == NULL );
Py_INCREF( tmp_assign_source_24 );
outline_0_var___doc__ = tmp_assign_source_24;
tmp_assign_source_25 = const_str_plain_RefreshTokenGrant;
assert( outline_0_var___qualname__ == NULL );
Py_INCREF( tmp_assign_source_25 );
outline_0_var___qualname__ = tmp_assign_source_25;
tmp_defaults_1 = const_tuple_none_true_tuple;
Py_INCREF( tmp_defaults_1 );
tmp_assign_source_26 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( tmp_defaults_1 );
assert( outline_0_var___init__ == NULL );
outline_0_var___init__ = tmp_assign_source_26;
tmp_assign_source_27 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( );
assert( outline_0_var_create_token_response == NULL );
outline_0_var_create_token_response = tmp_assign_source_27;
tmp_assign_source_28 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( );
assert( outline_0_var_validate_token_request == NULL );
outline_0_var_validate_token_request = tmp_assign_source_28;
// Tried code:
tmp_called_name_3 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_called_name_3 );
tmp_args_name_2 = PyTuple_New( 3 );
tmp_tuple_element_3 = const_str_plain_RefreshTokenGrant;
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_args_name_2, 0, tmp_tuple_element_3 );
tmp_tuple_element_3 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_tuple_element_3 );
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_args_name_2, 1, tmp_tuple_element_3 );
tmp_tuple_element_3 = locals_dict_1;
Py_INCREF( tmp_tuple_element_3 );
if ( outline_0_var___qualname__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___qualname__,
outline_0_var___qualname__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___qualname__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___qualname__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___module__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___module__,
outline_0_var___module__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___module__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___module__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___doc__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___doc__,
outline_0_var___doc__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___doc__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___doc__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___init__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___init__,
outline_0_var___init__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___init__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___init__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var_create_token_response != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain_create_token_response,
outline_0_var_create_token_response
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain_create_token_response
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain_create_token_response
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var_validate_token_request != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request,
outline_0_var_validate_token_request
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_args_name_2, 2, tmp_tuple_element_3 );
tmp_kw_name_2 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_kw_name_2 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 18;
tmp_assign_source_29 = CALL_FUNCTION( tmp_called_name_3, tmp_args_name_2, tmp_kw_name_2 );
Py_DECREF( tmp_args_name_2 );
if ( tmp_assign_source_29 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_4;
}
assert( outline_0_var___class__ == NULL );
outline_0_var___class__ = tmp_assign_source_29;
tmp_outline_return_value_1 = outline_0_var___class__;
CHECK_OBJECT( tmp_outline_return_value_1 );
Py_INCREF( tmp_outline_return_value_1 );
goto try_return_handler_4;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token );
return MOD_RETURN_VALUE( NULL );
// Return handler code:
try_return_handler_4:;
CHECK_OBJECT( (PyObject *)outline_0_var___class__ );
Py_DECREF( outline_0_var___class__ );
outline_0_var___class__ = NULL;
Py_XDECREF( outline_0_var___qualname__ );
outline_0_var___qualname__ = NULL;
Py_XDECREF( outline_0_var___module__ );
outline_0_var___module__ = NULL;
Py_XDECREF( outline_0_var___doc__ );
outline_0_var___doc__ = NULL;
Py_XDECREF( outline_0_var___init__ );
outline_0_var___init__ = NULL;
Py_XDECREF( outline_0_var_create_token_response );
outline_0_var_create_token_response = NULL;
Py_XDECREF( outline_0_var_validate_token_request );
outline_0_var_validate_token_request = NULL;
goto outline_result_1;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( outline_0_var___qualname__ );
outline_0_var___qualname__ = NULL;
Py_XDECREF( outline_0_var___module__ );
outline_0_var___module__ = NULL;
Py_XDECREF( outline_0_var___doc__ );
outline_0_var___doc__ = NULL;
Py_XDECREF( outline_0_var___init__ );
outline_0_var___init__ = NULL;
Py_XDECREF( outline_0_var_create_token_response );
outline_0_var_create_token_response = NULL;
Py_XDECREF( outline_0_var_validate_token_request );
outline_0_var_validate_token_request = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto outline_exception_1;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token );
return MOD_RETURN_VALUE( NULL );
outline_exception_1:;
exception_lineno = 18;
goto try_except_handler_3;
outline_result_1:;
tmp_assign_source_22 = tmp_outline_return_value_1;
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant, tmp_assign_source_22 );
goto try_end_3;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_4 = exception_type;
exception_keeper_value_4 = exception_value;
exception_keeper_tb_4 = exception_tb;
exception_keeper_lineno_4 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_class_creation_1__bases );
tmp_class_creation_1__bases = NULL;
Py_XDECREF( tmp_class_creation_1__class_decl_dict );
tmp_class_creation_1__class_decl_dict = NULL;
Py_XDECREF( tmp_class_creation_1__metaclass );
tmp_class_creation_1__metaclass = NULL;
Py_XDECREF( tmp_class_creation_1__prepared );
tmp_class_creation_1__prepared = NULL;
// Re-raise.
exception_type = exception_keeper_type_4;
exception_value = exception_keeper_value_4;
exception_tb = exception_keeper_tb_4;
exception_lineno = exception_keeper_lineno_4;
goto frame_exception_exit_1;
// End of try:
try_end_3:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_fecfc1a1477f82e7708776ac673a0656 );
#endif
popFrameStack();
assertFrameObject( frame_fecfc1a1477f82e7708776ac673a0656 );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_fecfc1a1477f82e7708776ac673a0656 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_fecfc1a1477f82e7708776ac673a0656, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_fecfc1a1477f82e7708776ac673a0656->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_fecfc1a1477f82e7708776ac673a0656, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
Py_XDECREF( tmp_class_creation_1__bases );
tmp_class_creation_1__bases = NULL;
Py_XDECREF( tmp_class_creation_1__class_decl_dict );
tmp_class_creation_1__class_decl_dict = NULL;
Py_XDECREF( tmp_class_creation_1__metaclass );
tmp_class_creation_1__metaclass = NULL;
Py_XDECREF( tmp_class_creation_1__prepared );
tmp_class_creation_1__prepared = NULL;
return MOD_RETURN_VALUE( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 33.912031 | 278 | 0.708938 | Pckool |
42fad074269bfefe00101ce8a49dd37741bfa172 | 7,992 | cxx | C++ | cmake-2.8.10.1/Source/cmOSXBundleGenerator.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | cmake-2.8.10.1/Source/cmOSXBundleGenerator.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | cmake-2.8.10.1/Source/cmOSXBundleGenerator.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2012 Nicolas Despres <nicolas.despres@gmail.com>
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmOSXBundleGenerator.h"
#include "cmMakefile.h"
#include "cmTarget.h"
#include "cmLocalGenerator.h"
#include <cassert>
void cmOSXBundleGenerator::PrepareTargetProperties(cmTarget* target)
{
if(target->IsCFBundleOnApple())
{
target->SetProperty("PREFIX", "");
target->SetProperty("SUFFIX", "");
}
}
//----------------------------------------------------------------------------
cmOSXBundleGenerator::
cmOSXBundleGenerator(cmTarget* target,
std::string targetNameOut,
const char* configName)
: Target(target)
, Makefile(target->GetMakefile())
, LocalGenerator(Makefile->GetLocalGenerator())
, TargetNameOut(targetNameOut)
, ConfigName(configName)
, MacContentDirectory()
, FrameworkVersion()
, MacContentFolders(0)
{
if (this->MustSkip())
return;
this->MacContentDirectory =
this->Target->GetMacContentDirectory(this->ConfigName,
/*implib*/ false,
/*includeMacOS*/ false);
if(this->Target->IsFrameworkOnApple())
this->FrameworkVersion = this->Target->GetFrameworkVersion();
}
//----------------------------------------------------------------------------
bool cmOSXBundleGenerator::MustSkip()
{
return !this->Target->HaveWellDefinedOutputFiles();
}
//----------------------------------------------------------------------------
void cmOSXBundleGenerator::CreateAppBundle(std::string& targetName,
std::string& outpath)
{
if (this->MustSkip())
return;
// Compute bundle directory names.
outpath = this->MacContentDirectory;
outpath += "MacOS";
cmSystemTools::MakeDirectory(outpath.c_str());
outpath += "/";
this->Makefile->AddCMakeOutputFile(outpath.c_str());
// Configure the Info.plist file. Note that it needs the executable name
// to be set.
std::string plist = this->MacContentDirectory + "Info.plist";
this->LocalGenerator->GenerateAppleInfoPList(this->Target,
targetName.c_str(),
plist.c_str());
this->Makefile->AddCMakeOutputFile(plist.c_str());
}
//----------------------------------------------------------------------------
void cmOSXBundleGenerator::CreateFramework(std::string const& targetName)
{
if (this->MustSkip())
return;
assert(this->MacContentFolders);
// Configure the Info.plist file into the Resources directory.
this->MacContentFolders->insert("Resources");
std::string plist = this->MacContentDirectory + "Resources/Info.plist";
this->LocalGenerator->GenerateFrameworkInfoPList(this->Target,
targetName.c_str(),
plist.c_str());
// TODO: Use the cmMakefileTargetGenerator::ExtraFiles vector to
// drive rules to create these files at build time.
std::string oldName;
std::string newName;
// Compute the location of the top-level foo.framework directory.
std::string top = this->Target->GetDirectory(this->ConfigName);
top += "/";
top += this->TargetNameOut;
top += ".framework/";
// Make foo.framework/Versions
std::string versions = top;
versions += "Versions";
cmSystemTools::MakeDirectory(versions.c_str());
// Make foo.framework/Versions/version
std::string version = versions;
version += "/";
version += this->FrameworkVersion;
cmSystemTools::MakeDirectory(version.c_str());
// Current -> version
oldName = this->FrameworkVersion;
newName = versions;
newName += "/Current";
cmSystemTools::RemoveFile(newName.c_str());
cmSystemTools::CreateSymlink(oldName.c_str(), newName.c_str());
this->Makefile->AddCMakeOutputFile(newName.c_str());
// foo -> Versions/Current/foo
oldName = "Versions/Current/";
oldName += this->TargetNameOut;
newName = top;
newName += this->TargetNameOut;
cmSystemTools::RemoveFile(newName.c_str());
cmSystemTools::CreateSymlink(oldName.c_str(), newName.c_str());
this->Makefile->AddCMakeOutputFile(newName.c_str());
// Resources -> Versions/Current/Resources
if(this->MacContentFolders->find("Resources") !=
this->MacContentFolders->end())
{
oldName = "Versions/Current/Resources";
newName = top;
newName += "Resources";
cmSystemTools::RemoveFile(newName.c_str());
cmSystemTools::CreateSymlink(oldName.c_str(), newName.c_str());
this->Makefile->AddCMakeOutputFile(newName.c_str());
}
// Headers -> Versions/Current/Headers
if(this->MacContentFolders->find("Headers") !=
this->MacContentFolders->end())
{
oldName = "Versions/Current/Headers";
newName = top;
newName += "Headers";
cmSystemTools::RemoveFile(newName.c_str());
cmSystemTools::CreateSymlink(oldName.c_str(), newName.c_str());
this->Makefile->AddCMakeOutputFile(newName.c_str());
}
// PrivateHeaders -> Versions/Current/PrivateHeaders
if(this->MacContentFolders->find("PrivateHeaders") !=
this->MacContentFolders->end())
{
oldName = "Versions/Current/PrivateHeaders";
newName = top;
newName += "PrivateHeaders";
cmSystemTools::RemoveFile(newName.c_str());
cmSystemTools::CreateSymlink(oldName.c_str(), newName.c_str());
this->Makefile->AddCMakeOutputFile(newName.c_str());
}
}
//----------------------------------------------------------------------------
void cmOSXBundleGenerator::CreateCFBundle(std::string& targetName,
std::string& outpath)
{
if (this->MustSkip())
return;
// Compute bundle directory names.
outpath = this->MacContentDirectory;
outpath += "MacOS";
cmSystemTools::MakeDirectory(outpath.c_str());
outpath += "/";
this->Makefile->AddCMakeOutputFile(outpath.c_str());
// Configure the Info.plist file. Note that it needs the executable name
// to be set.
std::string plist = this->MacContentDirectory;
plist += "Info.plist";
this->LocalGenerator->GenerateAppleInfoPList(this->Target,
targetName.c_str(),
plist.c_str());
this->Makefile->AddCMakeOutputFile(plist.c_str());
}
//----------------------------------------------------------------------------
void
cmOSXBundleGenerator::
GenerateMacOSXContentStatements(std::vector<cmSourceFile*> const& sources,
MacOSXContentGeneratorType* generator)
{
if (this->MustSkip())
return;
for(std::vector<cmSourceFile*>::const_iterator
si = sources.begin(); si != sources.end(); ++si)
{
cmTarget::SourceFileFlags tsFlags =
this->Target->GetTargetSourceFileFlags(*si);
if(tsFlags.Type != cmTarget::SourceFileTypeNormal)
{
(*generator)(**si, tsFlags.MacFolder);
}
}
}
//----------------------------------------------------------------------------
std::string
cmOSXBundleGenerator::InitMacOSXContentDirectory(const char* pkgloc)
{
// Construct the full path to the content subdirectory.
std::string macdir = this->MacContentDirectory;
macdir += pkgloc;
cmSystemTools::MakeDirectory(macdir.c_str());
// Record use of this content location. Only the first level
// directory is needed.
{
std::string loc = pkgloc;
loc = loc.substr(0, loc.find('/'));
this->MacContentFolders->insert(loc);
}
return macdir;
}
| 33.721519 | 78 | 0.603729 | vidkidz |
42fd626ce7e61f29accaa7671597789e8a94f46f | 7,529 | cpp | C++ | SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp | sygh-JP/FbxModelViewer | 690387451accd99f63e4385decc4cbbfea1c1603 | [
"MIT"
] | 12 | 2017-07-27T10:37:20.000Z | 2021-12-12T02:07:44.000Z | SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp | sygh-JP/FbxModelViewer | 690387451accd99f63e4385decc4cbbfea1c1603 | [
"MIT"
] | 1 | 2018-02-22T20:32:38.000Z | 2018-02-22T20:32:38.000Z | SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp | sygh-JP/FbxModelViewer | 690387451accd99f63e4385decc4cbbfea1c1603 | [
"MIT"
] | 4 | 2018-03-06T15:12:54.000Z | 2020-10-01T22:53:47.000Z | #include "stdafx.h"
#include "MyOGLDynamicFontRects.hpp"
namespace MyOGL
{
bool MyDynamicManyRectsBase::Create(uint32_t rectCount, uint32_t strideInBytes, const void* pInitialData)
{
_ASSERTE(m_vertexBuffer.get() == 0);
//_ASSERTE(pInitialData != nullptr); // OpenGL では D3D と違って頂点バッファ初期化用データに NULL も一応指定可能。ただしおそらく不定データになるはず。
_ASSERTE(rectCount > 0);
_ASSERTE(strideInBytes > 0);
const uint32_t vertexCount = rectCount * 4;
const uint32_t byteWidth = vertexCount * strideInBytes;
const void* pSrcData = pInitialData;
m_vertexBuffer = Factory::CreateOneBufferPtr();
_ASSERTE(m_vertexBuffer.get() != 0);
if (m_vertexBuffer.get() == 0)
{
return false;
}
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer.get());
// GL_STREAM_DRAW と GL_DYNAMIC_DRAW の違いが不明。
// 前者はフレームあたり1回程度の使い捨て用途、後者はフレームあたり2回以上書き換える用途に最適化されている?
// http://extns.cswiki.jp/index.php?OpenGL%2F%E3%83%90%E3%83%83%E3%83%95%E3%82%A1
// HACK: 1フレームで頂点バッファを何度も書き換える場合、都度 glFlush() や glFinish() を呼ばないといけない環境(ドライバー)も存在する。
// ある Android 実機では glFinish() なしで glBufferSubData() を1フレーム内で続けて呼び出すと、
// 意図した描画結果にならない(頂点バッファの内容が正しく更新されない)現象に遭遇した。
// なお、iPhone や Android などのモバイル環境では、
// 比較的余裕のある NVIDIA GeForce や AMD Radeon などの PC 向け GPU アーキテクチャ&ドライバーとは違って、
// パフォーマンス最優先のためにタイルベースの遅延レンダラー(Tile-Based Deferred Rendering, TBDR)が採用されているらしく、
// glTexSubImage2D() を1フレーム内で何度も呼び出すと性能が低下するらしい。
// http://blog.livedoor.jp/abars/archives/51879199.html
// フォント描画・スプライト描画に関しては、
// ID3DXSprite, ID3DX10Sprite や、XNA の SpriteBatch などのように、描画タスクをキューイングするバッチ処理を実装して、
// 頂点バッファの書き換え回数を減らすようにしたほうがよさげ。
// ID3DXSprite::Draw() は D3D9 テクスチャを、ID3DX10Sprite::DrawXXX() は D3D10 テクスチャの SRV をパラメータにとる。
// ID3DXFont::DrawText(), ID3DX10Font::DrawText() はスプライトのインターフェイスを受け取って効率化することも可能になっている。
// DirectX Tool Kit(DirectXTK, DXTK)には SpriteBatch クラスがオープンソース実装されているので、それを参考にする手もある。
// ただ、Direct3D 定数バッファ相当の OpenGL Uniform Block は通例頻繁にバッファ内容を書き換える用途で使用されるはずのため、
// ID3D11DeviceContext::UpdateSubresource() 相当機能が glBufferSubData() だとすれば、
// ES 3.0 対応モバイルでも glFinish() を呼ぶことなく glBufferSubData() だけできちんと更新してくれないと困るのだが……
// OpenGL 1.5 では D3D10/11 の Map(), Unmap() に似た glMapBuffer(), glUnmapBuffer() が導入されているが、
// モバイルでは glBufferSubData() 同様もしくはそれ以上に性能低下すると思われる。
// ちなみに glInvalidateBufferData(), glInvalidateBufferSubData() は何のために存在する?
glBufferData(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_DYNAMIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_STREAM_DRAW);
glBufferStorage(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_DYNAMIC_STORAGE_BIT);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// NVIDIA ドライバーを更新すると、
// glBufferData(), glBufferStorage() 呼び出し箇所などで、
// Source="OpenGL API", Type="Other", ID=131185, Severity=Low, Message="Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations."
// などの診断メッセージが出力されるようになる。
std::vector<TIndex> indexArray(rectCount * 6);
for (size_t i = 0; i < rectCount; ++i)
{
// CCW
indexArray[i * 6 + 0] = TIndex(0 + (i * 4));
indexArray[i * 6 + 1] = TIndex(2 + (i * 4));
indexArray[i * 6 + 2] = TIndex(1 + (i * 4));
indexArray[i * 6 + 3] = TIndex(1 + (i * 4));
indexArray[i * 6 + 4] = TIndex(2 + (i * 4));
indexArray[i * 6 + 5] = TIndex(3 + (i * 4));
}
m_indexArray.swap(indexArray);
m_rectCount = rectCount;
m_vertexBufferSizeInBytes = byteWidth;
return true;
}
bool MyDynamicManyRectsBase::ReplaceVertexData(const void* pSrcData)
{
_ASSERTE(m_vertexBuffer.get() != 0);
_ASSERTE(pSrcData != nullptr);
const uint32_t byteWidth = m_vertexBufferSizeInBytes;
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer.get());
// 確保済みのバッファの内容を書き換える場合、glBufferData() ではなく glBufferSubData() を使う。
glBufferSubData(GL_ARRAY_BUFFER, 0, byteWidth, pSrcData);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return true;
}
bool MyDynamicFontRects::UpdateVertexBufferByString(LPCWSTR pString,
MyMath::Vector2F posInPixels,
const MyMath::Vector4F& upperColor, const MyMath::Vector4F& lowerColor,
long fontHeight, bool usesFixedFeed,
uint32_t fontTexWidth, uint32_t fontTexHeight,
const MyMath::TCharCodeUVMap& codeUVMap)
{
_ASSERTE(pString != nullptr);
m_stringLength = 0;
float offsetX = 0;
TVertex* pVertexArray = &m_vertexArray[0]; // ローカル変数にキャッシュして高速化。
for (int i = 0; pString[i] != 0 && i < MaxCharacterCount; ++i, ++m_stringLength)
{
// HACK: このアルゴリズム(というか単一の wchar_t キー)だと、サロゲート ペアにはどうしても対応不可能。
const size_t charCode = static_cast<size_t>(pString[i]);
if (charCode < codeUVMap.size())
{
const auto codeUV = codeUVMap[charCode];
const float uvLeft = static_cast<float>(codeUV.X) / fontTexWidth;
const float uvTop = static_cast<float>(codeUV.Y) / fontTexHeight;
const float uvRight = static_cast<float>(codeUV.GetRight()) / fontTexWidth;
const float uvBottom = static_cast<float>(codeUV.GetBottom()) / fontTexHeight;
const float uvWidth = codeUV.Width;
const float uvHeight = codeUV.Height;
// LT, RT, LB, RB.(0, 1, 2 は左手系の定義順)
const size_t index0 = i * 4 + 0;
// 文字の水平方向送り(カーニングは考慮しないが、プロポーショナルの場合は文字幅)。
// スペースの文字送りも考慮する。
// HUD 系は常にモノスペースのほうがいいこともある。
// 非 ASCII はテクスチャ作成時にフォント メトリックから取得した文字幅にする。
// ヨーロッパ言語など、非 ASCII でもモノスペース時は半角幅のほうがいい文字もあるが、それは考慮しない。
// したがって、メソッドのフラグで等幅指定されたら、ASCII のみ半角幅とし、
// 非 ASCII はフォント メトリックから取得した文字幅を使うようにする。
const float feed = (usesFixedFeed && iswascii(pString[i])) ? (fontHeight / 2) : uvWidth;
pVertexArray[index0].Position.x = posInPixels.x + offsetX;
pVertexArray[index0].Position.y = posInPixels.y;
pVertexArray[index0].Position.z = 0;
//pVertexArray[index0].Position.w = 1;
pVertexArray[index0].Color = upperColor;
pVertexArray[index0].TexCoord.x = uvLeft;
pVertexArray[index0].TexCoord.y = uvTop;
const size_t index1 = i * 4 + 1;
pVertexArray[index1].Position.x = posInPixels.x + offsetX + uvWidth;
pVertexArray[index1].Position.y = posInPixels.y;
pVertexArray[index1].Position.z = 0;
//pVertexArray[index1].Position.w = 1;
pVertexArray[index1].Color = upperColor;
pVertexArray[index1].TexCoord.x = uvRight;
pVertexArray[index1].TexCoord.y = uvTop;
const size_t index2 = i * 4 + 2;
pVertexArray[index2].Position.x = posInPixels.x + offsetX;
pVertexArray[index2].Position.y = posInPixels.y + uvHeight;
pVertexArray[index2].Position.z = 0;
//pVertexArray[index2].Position.w = 1;
pVertexArray[index2].Color = lowerColor;
pVertexArray[index2].TexCoord.x = uvLeft;
pVertexArray[index2].TexCoord.y = uvBottom;
const size_t index3 = i * 4 + 3;
pVertexArray[index3].Position.x = posInPixels.x + offsetX + uvWidth;
pVertexArray[index3].Position.y = posInPixels.y + uvHeight;
pVertexArray[index3].Position.z = 0;
//pVertexArray[index3].Position.w = 1;
pVertexArray[index3].Color = lowerColor;
pVertexArray[index3].TexCoord.x = uvRight;
pVertexArray[index3].TexCoord.y = uvBottom;
// ボールド体の場合はもう少しオフセットしたほうがいいかも。
// フォントによっては、強制的に半角幅分送るだけ、というのは問題あり。
// 特にプロポーショナル フォントは英数字であっても文字幅が異なる。
// モノスペースであっても、半角幅分とはかぎらない。
offsetX += feed + 1;
}
}
if (m_stringLength > 0)
{
return this->ReplaceVertexData(&m_vertexArray[0]);
}
else
{
return true;
}
}
} // end of namespace
| 41.368132 | 240 | 0.703148 | sygh-JP |
42ffd885db326c66c1a72511a5313064b489a854 | 13,387 | cc | C++ | coral/dmabuf/model_pipelining_dmabuf_devboard_test.cc | cpcloud/libcoral | 8b21123c74d1f19c94b9d37aa16b26b80ef5e83b | [
"Apache-2.0"
] | null | null | null | coral/dmabuf/model_pipelining_dmabuf_devboard_test.cc | cpcloud/libcoral | 8b21123c74d1f19c94b9d37aa16b26b80ef5e83b | [
"Apache-2.0"
] | null | null | null | coral/dmabuf/model_pipelining_dmabuf_devboard_test.cc | cpcloud/libcoral | 8b21123c74d1f19c94b9d37aa16b26b80ef5e83b | [
"Apache-2.0"
] | null | null | null | // Tests DMA buffer support for model pipelining.
//
// It assumes the following test data inside `FLAGS_test_data_dir` folder
// - inception_v3_299_quant_edgetpu.tflite
// - pipeline/inception_v3_299_quant_segment_0_of_2_edgetpu.tflite
// - pipeline/inception_v3_299_quant_segment_1_of_2_edgetpu.tflite
#include <glib.h>
#include <gst/allocators/gstdmabuf.h>
#include <gst/gst.h>
#include <sys/mman.h>
#include <thread> // NOLINT
#include "absl/strings/str_cat.h"
#include "absl/strings/substitute.h"
#include "coral/pipeline/allocator.h"
#include "coral/pipeline/pipelined_model_runner.h"
#include "coral/pipeline/test_utils.h"
#include "coral/test_utils.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "tensorflow/lite/builtin_op_data.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tflite/public/edgetpu.h"
namespace coral {
namespace {
const int kMinFrames = 10;
// This file is part of the system image as part of OOBE.
const char *kVideoPath = "/usr/share/edgetpudemo/video_device.mp4";
const char *kPipeline =
"filesrc location=%s ! decodebin ! glfilterbin filter=glbox"
" ! video/x-raw,format=RGB,width=%d,height=%d"
" ! appsink name=appsink sync=false emit-signals=true";
const char *kModelBaseName = "inception_v3_299_quant";
class DmaBuffer : public Buffer {
public:
DmaBuffer(GstSample *sample, size_t requested_bytes)
: sample_(CHECK_NOTNULL(sample)), requested_bytes_(requested_bytes) {}
void *ptr() override { return nullptr; }
void *MapToHost() override {
if (!handle_) {
handle_ = mmap(nullptr, requested_bytes_, PROT_READ, MAP_PRIVATE, fd(),
/*offset=*/0);
if (handle_ == MAP_FAILED) {
handle_ = nullptr;
}
}
return handle_;
}
bool UnmapFromHost() override {
if (munmap(handle_, requested_bytes_) != 0) {
return false;
}
return true;
}
int fd() {
if (fd_ == -1) {
GstBuffer *buf = CHECK_NOTNULL(gst_sample_get_buffer(sample_));
GstMemory *mem = gst_buffer_peek_memory(buf, 0);
if (gst_is_dmabuf_memory(mem)) {
fd_ = gst_dmabuf_memory_get_fd(mem);
}
}
return fd_;
}
private:
friend class DmaAllocator;
GstSample *sample_ = nullptr;
size_t requested_bytes_ = 0;
int fd_ = -1;
void *handle_ = nullptr;
};
class DmaAllocator : public Allocator {
public:
DmaAllocator(GstElement *sink) : sink_(CHECK_NOTNULL(sink)) {}
Buffer *Alloc(size_t size_bytes) override {
GstSample *sample;
g_signal_emit_by_name(sink_, "pull-sample", &sample);
return new DmaBuffer(sample, size_bytes);
}
void Free(Buffer *buffer) override {
auto *sample = static_cast<DmaBuffer *>(buffer)->sample_;
if (sample) {
gst_sample_unref(sample);
}
delete buffer;
}
private:
GstElement *sink_ = nullptr;
};
// Monitors bus for error messages.
gboolean OnBusCall(GstBus *bus, GstMessage *msg, GMainLoop *loop) {
switch (GST_MESSAGE_TYPE(msg)) {
case GST_MESSAGE_EOS:
g_printerr("End of stream\n");
g_main_loop_quit(loop);
break;
case GST_MESSAGE_ERROR: {
GError *error;
gst_message_parse_error(msg, &error, NULL);
g_printerr("Error: %s\n", error->message);
g_error_free(error);
g_main_loop_quit(loop);
break;
}
default:
break;
}
return TRUE;
}
struct PipelinedModelState {
PipelinedModelState(GMainLoop *loop, PipelinedModelRunner *runner,
tflite::Interpreter *first_segment_interpreter) {
this->loop = loop;
this->runner = runner;
this->first_segment_interpreter = first_segment_interpreter;
this->seen_frames = 0;
}
~PipelinedModelState() { g_main_loop_unref(this->loop); }
GMainLoop *loop;
PipelinedModelRunner *runner;
// Needed to get input tensor types and input tensor size.
tflite::Interpreter *first_segment_interpreter;
int seen_frames;
};
// Pushes to PipelinedModelRunner whenever a new frame is available. It returns
// immediately after the push, and results are consumed in a separate thread.
GstFlowReturn PipelinedModelOnNewSample(GstElement *sink,
PipelinedModelState *state) {
GstFlowReturn ret = GST_FLOW_ERROR;
++state->seen_frames;
PipelineTensor input_buffer;
const TfLiteTensor *input_tensor =
state->first_segment_interpreter->input_tensor(0);
input_buffer.buffer =
state->runner->GetInputTensorAllocator()->Alloc(input_tensor->bytes);
input_buffer.type = input_tensor->type;
input_buffer.bytes = input_tensor->bytes;
state->runner->Push({input_buffer});
if (state->seen_frames >= kMinFrames) {
state->runner->Push({});
}
ret = state->seen_frames >= kMinFrames ? GST_FLOW_EOS : GST_FLOW_OK;
if (ret != GST_FLOW_OK) {
g_main_loop_quit(state->loop);
}
return ret;
}
struct RefModelState {
RefModelState(GMainLoop *loop, tflite::Interpreter *interpreter,
std::vector<std::vector<uint8_t>> *ref_result) {
this->loop = loop;
this->interpreter = interpreter;
this->ref_result = ref_result;
this->seen_frames = 0;
}
~RefModelState() { g_main_loop_unref(this->loop); }
GMainLoop *loop;
tflite::Interpreter *interpreter;
std::vector<std::vector<uint8_t>> *ref_result;
int seen_frames;
};
GstFlowReturn RefModelOnNewSample(GstElement *sink, RefModelState *state) {
GstFlowReturn ret = GST_FLOW_ERROR;
GstSample *sample;
g_signal_emit_by_name(sink, "pull-sample", &sample);
if (sample) {
++state->seen_frames;
GstBuffer *buf = gst_sample_get_buffer(sample);
GstMapInfo info;
if (gst_buffer_map(buf, &info, GST_MAP_READ) == TRUE) {
uint8_t *input_tensor =
state->interpreter->typed_input_tensor<uint8_t>(0);
std::memcpy(input_tensor, info.data, info.size);
CHECK_EQ(state->interpreter->Invoke(), kTfLiteOk);
CHECK_EQ(state->interpreter->outputs().size(), 1);
const auto *score_tensor = state->interpreter->output_tensor(0);
const auto *score = tflite::GetTensorData<uint8_t>(score_tensor);
state->ref_result->push_back(
std::vector<uint8_t>(score, score + score_tensor->bytes));
gst_buffer_unmap(buf, &info);
ret = state->seen_frames >= kMinFrames ? GST_FLOW_EOS : GST_FLOW_OK;
}
}
if (sample) {
gst_sample_unref(sample);
}
if (ret != GST_FLOW_OK) {
g_main_loop_quit(state->loop);
}
return ret;
}
// Analyzes kMinFrames frames using non-partitioned model and stores the result
// as reference.
void GetRefModelResult(const std::string &model_path,
std::vector<std::vector<uint8_t>> *ref_result) {
auto context =
CHECK_NOTNULL(edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(
edgetpu::DeviceType::kApexPci));
auto model =
CHECK_NOTNULL(tflite::FlatBufferModel::BuildFromFile(model_path.c_str()));
auto interpreter = CHECK_NOTNULL(CreateInterpreter(*model, context.get()));
const TfLiteTensor *input_tensor =
CHECK_NOTNULL(interpreter->input_tensor(0));
int tensor_width = input_tensor->dims->data[1];
int tensor_height = input_tensor->dims->data[2];
gst_init(nullptr, nullptr);
gchar *pipeline_desc =
g_strdup_printf(kPipeline, kVideoPath, tensor_width, tensor_height);
g_print("GStreamer pipeline:\n%s\n", pipeline_desc);
GstElement *pipeline =
CHECK_NOTNULL(gst_parse_launch(pipeline_desc, nullptr));
g_free(pipeline_desc);
GstElement *sink = gst_bin_get_by_name(GST_BIN(pipeline), "appsink");
RefModelState state(g_main_loop_new(NULL, FALSE), interpreter.get(),
ref_result);
g_signal_connect(sink, "new-sample", G_CALLBACK(RefModelOnNewSample), &state);
gst_object_unref(sink);
GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
gst_bus_add_watch(bus, reinterpret_cast<GstBusFunc>(OnBusCall), state.loop);
gst_object_unref(bus);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
g_main_loop_run(state.loop);
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
}
class ModelPipeliningDmaBufDevboardTest : public ::testing::Test {
protected:
static void SetUpTestSuite() {
const auto model_path =
TestDataPath(absl::StrCat(kModelBaseName, "_edgetpu.tflite"));
ref_result_ = new std::vector<std::vector<uint8_t>>();
ref_result_->reserve(kMinFrames);
GetRefModelResult(model_path, ref_result_);
}
void CheckPipelinedModelInferenceResult(
std::vector<edgetpu::EdgeTpuContext *> contexts) {
std::vector<std::string> model_segment_paths(num_segments);
for (int i = 0; i < num_segments; ++i) {
model_segment_paths[i] = TestDataPath(
absl::Substitute("pipeline/$0_segment_$1_of_$2_edgetpu.tflite",
kModelBaseName, i, num_segments));
}
std::vector<std::unique_ptr<tflite::Interpreter>> managed_interpreters(
num_segments);
std::vector<tflite::Interpreter *> interpreters(num_segments);
std::vector<std::unique_ptr<tflite::FlatBufferModel>> models(num_segments);
for (int i = 0; i < num_segments; ++i) {
models[i] = CHECK_NOTNULL(tflite::FlatBufferModel::BuildFromFile(
model_segment_paths[i].c_str()));
managed_interpreters[i] =
CHECK_NOTNULL(CreateInterpreter(*(models[i]), contexts[i]));
interpreters[i] = managed_interpreters[i].get();
}
const TfLiteTensor *input_tensor = interpreters[0]->input_tensor(0);
ASSERT_EQ(input_tensor->type, kTfLiteUInt8);
const auto &output_indices = interpreters[num_segments - 1]->outputs();
for (size_t i = 0; i < output_indices.size(); ++i) {
const auto *out_tensor = CHECK_NOTNULL(
interpreters[num_segments - 1]->tensor(output_indices[i]));
ASSERT_EQ(out_tensor->type, kTfLiteUInt8);
}
int tensor_width = input_tensor->dims->data[1];
int tensor_height = input_tensor->dims->data[2];
ASSERT_EQ(input_tensor->dims->data[3], 3); // channels, 3 for RGB
gst_init(nullptr, nullptr);
gchar *pipeline_desc =
g_strdup_printf(kPipeline, kVideoPath, tensor_width, tensor_height);
g_print("GStreamer pipeline:\n%s\n", pipeline_desc);
GstElement *pipeline =
CHECK_NOTNULL(gst_parse_launch(pipeline_desc, nullptr));
g_free(pipeline_desc);
GstElement *sink =
CHECK_NOTNULL(gst_bin_get_by_name(GST_BIN(pipeline), "appsink"));
std::unique_ptr<Allocator> dma_allocator(new DmaAllocator(sink));
std::unique_ptr<PipelinedModelRunner> runner(
new PipelinedModelRunner(interpreters, dma_allocator.get()));
PipelinedModelState state(g_main_loop_new(NULL, FALSE), runner.get(),
interpreters[0]);
g_signal_connect(sink, "new-sample", G_CALLBACK(PipelinedModelOnNewSample),
&state);
gst_object_unref(sink);
GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
gst_bus_add_watch(bus, reinterpret_cast<GstBusFunc>(OnBusCall), state.loop);
gst_object_unref(bus);
auto check_result = [&runner, this]() {
std::vector<PipelineTensor> output_tensors;
int counter = 0;
while (runner->Pop(&output_tensors)) {
ASSERT_EQ(output_tensors.size(), 1);
const auto &expected = (*ref_result_)[counter];
const auto *actual =
static_cast<uint8_t *>(output_tensors[0].buffer->ptr());
ASSERT_EQ(output_tensors[0].bytes, expected.size());
for (int i = 0; i < expected.size(); ++i) {
EXPECT_EQ(actual[i], expected[i]);
}
runner->GetOutputTensorAllocator()->Free(output_tensors[0].buffer);
output_tensors.clear();
counter++;
}
EXPECT_EQ(counter, ref_result_->size());
};
auto consumer = std::thread(check_result);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
g_main_loop_run(state.loop);
consumer.join();
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
}
static std::vector<std::vector<uint8_t>> *ref_result_;
const int num_segments = 2;
};
std::vector<std::vector<uint8_t>>
*ModelPipeliningDmaBufDevboardTest::ref_result_ = nullptr;
TEST_F(ModelPipeliningDmaBufDevboardTest, DmaBufInputSupported) {
auto pci_context =
CHECK_NOTNULL(edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(
edgetpu::DeviceType::kApexPci));
auto usb_context =
CHECK_NOTNULL(edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(
edgetpu::DeviceType::kApexUsb));
// PCI Edge TPU supports DMA buffer as input starting from Mendel Eagle.
CheckPipelinedModelInferenceResult({pci_context.get(), usb_context.get()});
}
TEST_F(ModelPipeliningDmaBufDevboardTest, DmaBufInputNotSupported) {
auto pci_context =
CHECK_NOTNULL(edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(
edgetpu::DeviceType::kApexPci));
auto usb_context =
CHECK_NOTNULL(edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(
edgetpu::DeviceType::kApexUsb));
// USB Edge TPU does not support DMA buffer as input.
CheckPipelinedModelInferenceResult({usb_context.get(), pci_context.get()});
}
} // namespace
} // namespace coral
| 33.136139 | 80 | 0.696273 | cpcloud |
42ffde66eb9f7bcaa2cbc82100fa765f1eba80b6 | 333 | hh | C++ | libalcc/copa/random.hh | comnetsAD/ALCC | fc9c627de8c381987fc775ce0872339fceb43ddf | [
"MIT"
] | 6 | 2021-05-19T16:58:15.000Z | 2022-03-10T03:51:20.000Z | libalcc/copa/random.hh | comnetsAD/ALCC | fc9c627de8c381987fc775ce0872339fceb43ddf | [
"MIT"
] | null | null | null | libalcc/copa/random.hh | comnetsAD/ALCC | fc9c627de8c381987fc775ce0872339fceb43ddf | [
"MIT"
] | 4 | 2021-05-24T11:19:18.000Z | 2022-03-08T17:58:24.000Z | #ifndef RANDOM_HH
#define RANDOM_HH
#include <boost/random/mersenne_twister.hpp>
#include <random>
typedef boost::random::mt19937 PRNG;
extern PRNG & global_PRNG();
class RandGen {
std::default_random_engine generator;
public:
RandGen();
double uniform(double a, double b);
double exponential(double lambda);
};
#endif
| 14.478261 | 44 | 0.747748 | comnetsAD |
6e0233838b7f37894d460f2bfe5a8566d05f8eba | 1,189 | hh | C++ | include/Attributes/StandardAttribute.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 6 | 2016-09-28T18:26:42.000Z | 2021-04-10T13:19:05.000Z | include/Attributes/StandardAttribute.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 1 | 2021-02-09T00:24:04.000Z | 2021-02-27T22:08:05.000Z | include/Attributes/StandardAttribute.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 5 | 2017-09-14T09:48:17.000Z | 2021-07-19T07:58:34.000Z | /*
* Copyright 2021 Aaron Bamberger
* Licensed under BSD 2-clause license
* See LICENSE file at root of source tree,
* or https://opensource.org/licenses/BSD-2-Clause
*/
#ifndef _STANDARD_ATTRIBUTE_H
#define _STANDARD_ATTRIBUTE_H
#include "Attributes/Attribute.hh"
#include "Util/ValueWithLocation.hh"
#include <string>
class StandardAttribute : public Attribute {
public:
enum class StandardAttributeType {
STANDARD_ATTRIBUTE_INVALID,
STANDARD_ATTRIBUTE_PART,
STANDARD_ATTRIBUTE_FILE_FUNCTION,
STANDARD_ATTRIBUTE_FILE_POLARITY,
STANDARD_ATTRIBUTE_SAME_COORDINATES,
STANDARD_ATTRIBUTE_CREATION_DATE,
STANDARD_ATTRIBUTE_GENERATION_SOFTWARE,
STANDARD_ATTRIBUTE_PROJECT_ID,
STANDARD_ATTRIBUTE_MD5,
STANDARD_ATTRIBUTE_APER_FUNCTION,
STANDARD_ATTRIBUTE_DRILL_TOLERANCE,
STANDARD_ATTRIBUTE_FLASH_TEXT,
STANDARD_ATTRIBUTE_NET,
STANDARD_ATTRIBUTE_PIN_NUMBER,
STANDARD_ATTRIBUTE_PIN_FUNCTION,
STANDARD_ATTRIBUTE_COMPONENT
};
StandardAttribute(ValueWithLocation<std::string> name, StandardAttributeType type);
virtual ~StandardAttribute();
StandardAttributeType get_type();
private:
StandardAttributeType m_type;
};
#endif // _STANDARD_ATTRIBUTE_H
| 25.297872 | 84 | 0.827586 | aaronbamberger |
6e07ecf0b5b6d597eb132a6ed3f2aede8627d1c6 | 9,709 | cpp | C++ | src/mainwindow.cpp | AshBringer47/Graph | 0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95 | [
"MIT"
] | 2 | 2015-03-07T12:31:29.000Z | 2017-08-31T03:15:21.000Z | src/mainwindow.cpp | AshBringer47/Graph | 0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95 | [
"MIT"
] | null | null | null | src/mainwindow.cpp | AshBringer47/Graph | 0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95 | [
"MIT"
] | 6 | 2016-10-17T02:04:29.000Z | 2019-10-13T21:12:39.000Z | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "algorithm/getallvertexlistinordervorker.h"
#include "view/settings.h"
#include <QFileDialog>
#include <QUrl>
#include <QMessageBox>
#include "util/rand.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
_scene = new GraphScene(this);
_controlsWidget = new Controls(this);
_matrixViewWindow = new MatrixView(this);
_settingWindow = new Settings(this);
ui->graphView->setScene(_scene);
ui->mainToolBar->addWidget(_controlsWidget);
connect(_controlsWidget, &Controls::newNode,
_scene, &GraphScene::newNode);
connect(_controlsWidget, &Controls::clearScene,
_scene, &GraphScene::clearScene);
connect(ui->action_openSettings, &QAction::triggered,
_settingWindow, &QWidget::show);
connect(GraphicVertex::selectSignalEmitterInstance(), &graphItemSelectSignalEmitter::vertexSelected_,
_controlsWidget, &Controls::vertexSelected);
connect(GraphicVertex::selectSignalEmitterInstance(), &graphItemSelectSignalEmitter::vertexMoved,
_controlsWidget, &Controls::selectedVertexMoved);
connect(ui->action_forTest, &QAction::triggered,
_scene->graph(), &Graph::forTest);
connect(ui->graphView, &GraphView::removeSelectedVertex,
_scene, &GraphScene::removeSelectedVertex);
connect(ui->graphView, &GraphView::addIsolatedVertex,
_scene, &GraphScene::addIsolatedVertex);
}
MainWindow::~MainWindow()
{
delete ui;
}
QString *MainWindow::getTextGraphFromFile()
{
QString str = QFileDialog::getOpenFileName(this, tr("Open graph"), tr(""), tr("txt graph data (*.txt)"));
if(str.isEmpty()) {
return nullptr;
}
QFile file(str);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return nullptr;
}
QTextStream fileStream(&file);
QString *tmp = new QString(fileStream.readAll());
file.close();
return tmp;
}
void MainWindow::on_action_addVericesFromFile_triggered()
{
QScopedPointer<QString> textGraph(getTextGraphFromFile());
if(textGraph.isNull()) {
return;
}
if(textGraph->at(0) == 'w' || textGraph->at(0) == 'n') {
_scene->addNodesFromString(*textGraph, textGraph->at(0) == 'w');
} else {
QMessageBox::warning(this, tr("Попередження"), tr("Помилка читання типу графа"));
}
}
void MainWindow::on_action_showHangingVertex_triggered()
{
auto vertices = _scene->graph()->hangingVertex();
_matrixViewWindow->showVertexList(vertices, tr("Висячі вершини"));
delete vertices;
}
void MainWindow::on_action_showIsolatedVertex_triggered()
{
auto vertices = _scene->graph()->isolatedVertex();
_matrixViewWindow->showVertexList(vertices, tr("Ізольовані вершини"));
delete vertices;
}
void MainWindow::on_action_showIncidenceMatrix_triggered()
{
auto matrix = _scene->graph()->incidenceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця інцидентності"));
delete matrix;
}
void MainWindow::on_action_showAdjacencyMatrix_triggered()
{
auto matrix = _scene->graph()->adjacencyMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця суміжності"));
delete matrix;
}
void MainWindow::on_action_showDistanceMatrix_triggered()
{
auto matrix = _scene->graph()->distanceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця відстаней"));
delete matrix;
}
void MainWindow::on_action_showReachabilityMatrix_triggered()
{
auto matrix = _scene->graph()->reachabilityMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця досяжності"));
delete matrix;
}
void MainWindow::on_action_checkCycles_triggered()
{
graphCycles *cycles = _scene->graph()->checkCycles();
_matrixViewWindow->showManyVertexList(cycles->cyclesVertexId, tr("Деякі цикли з графу"));
delete cycles;
}
void MainWindow::on_action_breadthSearch_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
getVertexSearchOrderWorker w;
_scene->graph()->breadthSearch(vertexId, &w);
_scene->graph()->highlightVertex(w.allItem().toList(), 600);
}
void MainWindow::on_action_depthSearch_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
getVertexSearchOrderWorker w;
_scene->graph()->depthSearch(vertexId, &w);
_scene->graph()->highlightVertex(w.allItem().toList(), 600);
}
void MainWindow::on_action_checkConnectivity_triggered()
{
auto connectType = _scene->graph()->connectivity();
_matrixViewWindow->showGraphConnectivity(connectType, tr("Зв’язність графу"));
}
void MainWindow::on_action_showWeightedDistanceMatrix_triggered()
{
auto matrix = _scene->graph()->weightedDistanceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця відстаней (зваж.)"));
delete matrix;
}
void MainWindow::on_action_DijkstraMinPaths_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
auto v = _scene->graph()->minPathsDijkstra(vertexId);
_matrixViewWindow->showPathToAll(v, tr("Шлях"));
}
void MainWindow::on_action_BellmanFord_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
auto v = _scene->graph()->minPathsBellmanFord(vertexId);
_matrixViewWindow->showPathToAll(v, tr("Шлях"));
}
void MainWindow::on_action_isPlanarity_triggered()
{
if(_scene->graph()->isPlanarity()) {
_matrixViewWindow->showSimpleString("Граф планарний", "Планарність графу");
} else {
_matrixViewWindow->showSimpleString("Граф не планарний", "Планарність графу");
}
}
void MainWindow::on_action_coloring_triggered()
{
QMap<int, QColor> colorTable;
colorTable.insert(0, Qt::red);
colorTable.insert(1, Qt::blue);
colorTable.insert(2, Qt::black);
colorTable.insert(3, Qt::cyan);
colorTable.insert(4, Qt::magenta);
colorTable.insert(5, Qt::darkRed);
colorTable.insert(6, Qt::darkGreen);
colorTable.insert(7, Qt::darkBlue);
colorTable.insert(7, Qt::darkCyan);
colorTable.insert(8, Qt::darkMagenta);
QMap<int, int> resultColors = _scene->graph()->coloring();
for(int key : resultColors.keys()) {
Vertex *v = _scene->graph()->getVertex(key);
if(v == nullptr) {
continue;
}
QPen newPen = v->graphicsVertex()->pen();
if(!colorTable.contains(resultColors[key])) {
colorTable.insert(resultColors[key], QColor(Rand::intNumber(0, 255), Rand::intNumber(0, 255), Rand::intNumber(0, 255)));
}
newPen.setColor(colorTable[resultColors[key]]);
v->graphicsVertex()->setPen(newPen);
}
// TODO: restore color
}
void MainWindow::on_action_clearScene_triggered()
{
_scene->clearScene();
}
void MainWindow::on_action_FordFulkerson_triggered()
{
int startVertexId = _scene->selectVertex();
if(startVertexId == -1) {
return;
}
int endVertexId = _scene->selectVertex();
if(endVertexId == -1) {
return;
}
flow maxFlow = _scene->graph()->maxFlowFordFulkerson(startVertexId, endVertexId);
if(maxFlow.value != INF) {
_matrixViewWindow->showSimpleString("Максималний потік між вершиною "
+ QString::number(maxFlow.beginVertexId)
+ " та вершиною "
+ QString::number(maxFlow.endVertexId)
+ " дорівнює "
+ QString::number(maxFlow.value),
"Максимальний потік");
} else {
_matrixViewWindow->showSimpleString("Максималний потік між вершиною "
+ QString::number(maxFlow.beginVertexId)
+ " та вершиною "
+ QString::number(maxFlow.endVertexId)
+ " дорівнює нескінченності",
"Максимальний потік");
}
}
void MainWindow::on_action_topologicalSorting_triggered()
{
QList<int> topologicalSorting = _scene->graph()->topologicalSorting();
QString sorting;
if(!topologicalSorting.isEmpty()) {
sorting.reserve(topologicalSorting.size() * 4);
for(int v : topologicalSorting) {
sorting.append(QString::number(v));
sorting.append(" - ");
}
sorting.resize(sorting.size() - 3);
} else {
sorting = tr("Топологічне сортування, для даного графу, неможливе");
}
_matrixViewWindow->showSimpleString(sorting, tr("Топологічне сортування"));
}
void MainWindow::on_action_showVertexDegree_triggered()
{
auto degree = _scene->graph()->vertexDegree();
_matrixViewWindow->showVertexDegree(degree, tr("Степені6 вершин графу"));
}
void MainWindow::on_action_saveGraph_triggered()
{
QString str = QFileDialog::getSaveFileName(this, tr("Open graph"), tr(""), tr("txt graph data (*.txt)"));
if(str.isEmpty()) {
return;
}
QFile file(str);
if(file.open(QIODevice::WriteOnly | QIODevice::Text) ) {
QTextStream outStream(&file);
outStream << _scene->graph()->toTextGraph();
}
file.close();
}
void MainWindow::on_action_inverseGraph_triggered()
{
_scene->graph()->inverseGraph();
}
| 30.152174 | 132 | 0.639304 | AshBringer47 |
6e08be03ac82cd7eb5635d5a38622565495d536b | 424 | cpp | C++ | test/ac-library/segtree.min.test.cpp | sash2104/library | ecb52543e4f8a66300ffd8794ea9c13bc74bdb19 | [
"Unlicense"
] | null | null | null | test/ac-library/segtree.min.test.cpp | sash2104/library | ecb52543e4f8a66300ffd8794ea9c13bc74bdb19 | [
"Unlicense"
] | 10 | 2020-01-27T15:57:45.000Z | 2021-12-20T03:26:26.000Z | test/ac-library/segtree.min.test.cpp | sash2104/library | ecb52543e4f8a66300ffd8794ea9c13bc74bdb19 | [
"Unlicense"
] | null | null | null | #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A"
#include <iostream>
#include "../../atcoder/segtree/min.hpp"
using namespace std;
// @title セグメント木、min (ac-library)
int main() {
int n, q; cin >> n >> q;
segtree::min::type<int> seg(n);
for (int i = 0; i < q; ++i) {
int c, x, y; cin >> c >> x >> y;
if (c == 0) seg.set(x, y);
else cout << seg.prod(x, y+1) << endl;
}
}
| 24.941176 | 82 | 0.570755 | sash2104 |
6e09fa2515f524b3a4b661b90b8391205cc9dd67 | 983 | cpp | C++ | source/entity/Drain.cpp | Tomash667/carpg | 7e89d83f51cb55a89baf509915a9a9f8c642825f | [
"MIT"
] | 19 | 2015-05-30T12:14:07.000Z | 2021-05-26T19:17:21.000Z | source/entity/Drain.cpp | Tomash667/carpg | 7e89d83f51cb55a89baf509915a9a9f8c642825f | [
"MIT"
] | 402 | 2016-02-26T08:39:21.000Z | 2021-07-06T16:47:16.000Z | source/entity/Drain.cpp | Tomash667/carpg | 7e89d83f51cb55a89baf509915a9a9f8c642825f | [
"MIT"
] | 21 | 2015-07-28T14:11:39.000Z | 2020-12-11T07:54:09.000Z | #include "Pch.h"
#include "Drain.h"
#include "Unit.h"
#include <ParticleSystem.h>
//=================================================================================================
bool Drain::Update(float dt)
{
t += dt;
if(pe->manual_delete == 2)
{
delete pe;
return true;
}
if(Unit* unit = target)
{
Vec3 center = unit->GetCenter();
for(ParticleEmitter::Particle& p : pe->particles)
p.pos = Vec3::Lerp(p.pos, center, t / 1.5f);
return false;
}
else
{
pe->time = 0.3f;
pe->manual_delete = 0;
return true;
}
}
//=================================================================================================
void Drain::Save(GameWriter& f)
{
f << target;
f << pe->id;
f << t;
}
//=================================================================================================
void Drain::Load(GameReader& f)
{
if(LOAD_VERSION < V_0_13)
f.Skip<int>(); // old from
f >> target;
pe = ParticleEmitter::GetById(f.Read<int>());
f >> t;
}
| 18.903846 | 99 | 0.417091 | Tomash667 |
6e0a177518fa95590055e0ff0956db84506214e0 | 26,704 | cpp | C++ | Src/Assets/Mitsuba/MitsubaLoader.cpp | dennis-lynch/GPU-Raytracer | 93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e | [
"MIT"
] | null | null | null | Src/Assets/Mitsuba/MitsubaLoader.cpp | dennis-lynch/GPU-Raytracer | 93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e | [
"MIT"
] | null | null | null | Src/Assets/Mitsuba/MitsubaLoader.cpp | dennis-lynch/GPU-Raytracer | 93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e | [
"MIT"
] | null | null | null | #include "MitsubaLoader.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Core/Array.h"
#include "Core/HashMap.h"
#include "Core/Format.h"
#include "Core/Parser.h"
#include "Core/StringView.h"
#include "Assets/BVHLoader.h"
#include "Assets/OBJLoader.h"
#include "Assets/PLYLoader.h"
#include "Renderer/Scene.h"
#include "Renderer/MeshData.h"
#include "Util/Util.h"
#include "Util/Geometry.h"
#include "XMLParser.h"
#include "MitshairLoader.h"
#include "SerializedLoader.h"
struct ShapeGroup {
MeshDataHandle mesh_data_handle;
MaterialHandle material_handle;
};
using ShapeGroupMap = HashMap<String, ShapeGroup>;
using MaterialMap = HashMap<String, MaterialHandle>;
using TextureMap = HashMap<String, TextureHandle>;
static TextureHandle parse_texture(const XMLNode * node, TextureMap & texture_map, StringView path, Scene & scene, Vector3 * rgb) {
StringView type = node->get_attribute_value("type");
if (type == "scale") {
if (const XMLNode * scale = node->get_child_by_name("scale")) {
if (scale->tag == "float") {
*rgb *= scale->get_attribute_value<float>("value");
} else if (scale->tag == "rgb") {
*rgb *= scale->get_attribute_value<Vector3>("value");
} else {
WARNING(scale->location, "Invalid scale tag <{}>!\n", scale->tag);
}
}
node = node->get_child_by_tag("texture");
type = node->get_attribute_value("type");
}
if (type == "bitmap") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, scene.allocator);
String texture_name = String(Util::remove_directory(filename_abs.view()), scene.allocator);
TextureHandle texture_handle = scene.asset_manager.add_texture(std::move(filename_abs), std::move(texture_name));
if (const XMLAttribute * id = node->get_attribute("id")) {
texture_map.insert(id->value, texture_handle);
}
return texture_handle;
} else {
WARNING(node->location, "Only bitmap textures are supported!\n");
}
return TextureHandle { INVALID };
}
static void parse_rgb_or_texture(const XMLNode * node, const char * name, TextureMap & texture_map, StringView path, Scene & scene, Vector3 * rgb, TextureHandle * texture_handle) {
const XMLNode * colour = node->get_child_by_name(name);
if (colour) {
if (colour->tag == "rgb") {
*rgb = colour->get_attribute_optional("value", Vector3(1.0f));
} else if (colour->tag == "srgb") {
*rgb = colour->get_attribute_optional("value", Vector3(1.0f));
rgb->x = Math::gamma_to_linear(rgb->x);
rgb->y = Math::gamma_to_linear(rgb->y);
rgb->z = Math::gamma_to_linear(rgb->z);
} else if (colour->tag == "texture") {
*texture_handle = parse_texture(colour, texture_map, path, scene, rgb);
const XMLNode * scale = colour->get_child_by_name("scale");
if (scale) {
*rgb = scale->get_attribute_optional("value", Vector3(1.0f));
}
} else if (colour->tag == "ref") {
StringView texture_name = colour->get_attribute_value<StringView>("id");
TextureHandle * ref_handle = texture_map.try_get(texture_name);
if (ref_handle) {
*texture_handle = *ref_handle;
} else {
WARNING(colour->location, "Invalid texture ref '{}'!\n", texture_name);
}
}
} else {
*rgb = Vector3(1.0f);
}
}
static Matrix4 parse_transform_matrix(const XMLNode * node) {
Matrix4 world = { };
const XMLNode * transform = node->get_child_by_tag("transform");
if (!transform) {
return world;
}
for (size_t i = 0; i < transform->children.size(); i++) {
const XMLNode & transformation = transform->children[i];
if (transformation.tag == "matrix") {
world = transformation.get_attribute_value<Matrix4>("value") * world;
} else if (transformation.tag == "lookat") {
Vector3 origin = transformation.get_attribute_optional("origin", Vector3(0.0f, 0.0f, 0.0f));
Vector3 target = transformation.get_attribute_optional("target", Vector3(0.0f, 0.0f, -1.0f));
Vector3 up = transformation.get_attribute_optional("up", Vector3(0.0f, 1.0f, 0.0f));
world = Matrix4::create_translation(origin) * Matrix4::create_rotation(Quaternion::look_rotation(target - origin, up)) * world;
} else if (transformation.tag == "scale") {
const XMLAttribute * scale = transformation.get_attribute("value");
if (scale) {
world = Matrix4::create_scale(scale->get_value<float>()) * world;
} else {
float x = transformation.get_attribute_optional("x", 1.0f);
float y = transformation.get_attribute_optional("y", 1.0f);
float z = transformation.get_attribute_optional("z", 1.0f);
world = Matrix4::create_scale(x, y, z) * world;
}
} else if (transformation.tag == "rotate") {
float x = transformation.get_attribute_optional("x", 0.0f);
float y = transformation.get_attribute_optional("y", 0.0f);
float z = transformation.get_attribute_optional("z", 0.0f);
if (x == 0.0f && y == 0.0f && z == 0.0f) {
WARNING(transformation.location, "WARNING: Rotation without axis specified!\n");
} else {
float angle = transformation.get_attribute_optional("angle", 0.0f);
world = Matrix4::create_rotation(Quaternion::axis_angle(Vector3(x, y, z), Math::deg_to_rad(angle))) * world;
}
} else if (transformation.tag == "translate") {
world = Matrix4::create_translation(Vector3(
transformation.get_attribute_optional("x", 0.0f),
transformation.get_attribute_optional("y", 0.0f),
transformation.get_attribute_optional("z", 0.0f)
)) * world;
} else {
WARNING(transformation.location, "Node <{}> is not a valid transformation!\n", transformation.tag);
}
}
return world;
}
static void parse_transform(const XMLNode * node, Vector3 * position, Quaternion * rotation, float * scale, const Vector3 & forward = Vector3(0.0f, 0.0f, 1.0f)) {
Matrix4 world = parse_transform_matrix(node);
Matrix4::decompose(world, position, rotation, scale, forward);
}
static MaterialHandle parse_material(const XMLNode * node, Scene & scene, const MaterialMap & material_map, TextureMap & texture_map, StringView path) {
Material material = { };
const XMLNode * bsdf;
if (node->tag != "bsdf") {
// Check if there is an emitter defined
const XMLNode * emitter = node->get_child_by_tag("emitter");
if (emitter) {
material.type = Material::Type::LIGHT;
material.name = "emitter";
material.emission = emitter->get_child_value<Vector3>("radiance");
return scene.asset_manager.add_material(std::move(material));
}
// Check if an existing Material is referenced
const XMLNode * ref = node->get_child_by_tag("ref");
if (ref) {
StringView material_name = ref->get_attribute_value<StringView>("id");
if (MaterialHandle * material_id = material_map.try_get(material_name)) {
return *material_id;
} else {
WARNING(ref->location, "Invalid material Ref '{}'!\n", material_name);
return MaterialHandle::get_default();
}
}
// Otherwise, parse BSDF
bsdf = node->get_child_by_tag("bsdf");
if (bsdf == nullptr) {
WARNING(node->location, "Unable to parse BSDF!\n");
return MaterialHandle::get_default();
}
} else {
bsdf = node;
}
const XMLAttribute * name = bsdf->get_attribute("id");
const XMLNode * inner_bsdf = bsdf;
StringView inner_bsdf_type = inner_bsdf->get_attribute_value<StringView>("type");
// Keep peeling back nested BSDFs, we only care about the innermost one
while (
inner_bsdf_type == "twosided" ||
inner_bsdf_type == "mask" ||
inner_bsdf_type == "bumpmap" ||
inner_bsdf_type == "coating"
) {
const XMLNode * inner_bsdf_child = inner_bsdf->get_child_by_tag("bsdf");
if (inner_bsdf_child) {
inner_bsdf = inner_bsdf_child;
} else {
const XMLNode * ref = inner_bsdf->get_child_by_tag("ref");
if (ref) {
StringView id = ref->get_attribute_value<StringView>("id");
if (MaterialHandle * material_handle = material_map.try_get(id)) {
return *material_handle;
} else {
WARNING(ref->location, "Invalid material Ref '{}'!\n", id);
return MaterialHandle::get_default();
}
} else {
return MaterialHandle::get_default();
}
}
inner_bsdf_type = inner_bsdf->get_attribute_value<StringView>("type");
if (name == nullptr) {
name = inner_bsdf->get_attribute("id");
}
}
if (name) {
material.name = String(name->value, scene.allocator);
} else {
material.name = "Material";
}
if (inner_bsdf_type == "diffuse") {
material.type = Material::Type::DIFFUSE;
parse_rgb_or_texture(inner_bsdf, "reflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
} else if (inner_bsdf_type == "conductor" || inner_bsdf_type == "roughconductor") {
material.type = Material::Type::CONDUCTOR;
if (inner_bsdf_type == "conductor") {
material.linear_roughness = 0.0f;
} else {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
}
const XMLNode * material_str = inner_bsdf->get_child_by_name("material");
if (material_str && material_str->get_attribute_value<StringView>("value") == "none") {
material.eta = Vector3(0.0f);
material.k = Vector3(1.0f);
} else {
material.eta = inner_bsdf->get_child_value_optional("eta", Vector3(1.33f));
material.k = inner_bsdf->get_child_value_optional("k", Vector3(1.0f));
}
} else if (inner_bsdf_type == "plastic" || inner_bsdf_type == "roughplastic" || inner_bsdf_type == "roughdiffuse") {
material.type = Material::Type::PLASTIC;
parse_rgb_or_texture(inner_bsdf, "diffuseReflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
if (inner_bsdf_type == "plastic") {
material.linear_roughness = 0.0f;
} else {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
}
} else if (inner_bsdf_type == "phong") {
material.type = Material::Type::PLASTIC;
parse_rgb_or_texture(inner_bsdf, "diffuseReflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
float exponent = inner_bsdf->get_child_value_optional("exponent", 1.0f);
material.linear_roughness = powf(0.5f * exponent + 1.0f, 0.25f);
} else if (inner_bsdf_type == "thindielectric" || inner_bsdf_type == "dielectric" || inner_bsdf_type == "roughdielectric") {
float int_ior = 0.0f;
float ext_ior = 0.0f;
auto lookup_known_ior = [](StringView name, float * ior) {
// Based on: https://www.mitsuba-renderer.org/releases/0.5.0/documentation.pdf (page 58)
struct IOR {
const char * name;
float ior;
};
static IOR known_iors[] = {
{ "vacuum", 1.0f },
{ "helium", 1.00004f },
{ "hydrogen", 1.00013f },
{ "air", 1.00028f },
{ "carbon dioxide", 1.00045f },
{ "water", 1.3330f },
{ "acetone", 1.36f },
{ "ethanol", 1.361f },
{ "carbon tetrachloride", 1.461f },
{ "glycerol", 1.4729f },
{ "benzene", 1.501f },
{ "silicone oil", 1.52045f },
{ "bromine", 1.661f },
{ "water ice", 1.31f },
{ "fused quartz", 1.458f },
{ "pyrex", 1.470f },
{ "acrylic glass", 1.49f },
{ "polypropylene", 1.49f },
{ "bk7", 1.5046f },
{ "sodium chloride", 1.544f },
{ "amber", 1.55f },
{ "pet", 1.575f },
{ "diamond", 2.419f }
};
for (int i = 0; i < Util::array_count(known_iors); i++) {
if (name == known_iors[i].name) {
*ior = known_iors[i].ior;
return true;
}
}
return false;
};
const XMLNode * child_int_ior = inner_bsdf->get_child_by_name("intIOR");
if (child_int_ior && child_int_ior->tag == "string") {
StringView int_ior_name = child_int_ior->get_attribute_value("value");
if (!lookup_known_ior(int_ior_name, &int_ior)) {
ERROR(child_int_ior->location, "Index of refraction not known for '{}'\n", int_ior_name);
}
} else {
int_ior = inner_bsdf->get_child_value_optional("intIOR", 1.33f);
}
const XMLNode * child_ext_ior = inner_bsdf->get_child_by_name("extIOR");
if (child_ext_ior && child_ext_ior->tag == "string") {
StringView ext_ior_name = child_ext_ior->get_attribute_value("value");
if (!lookup_known_ior(ext_ior_name, &ext_ior)) {
ERROR(child_ext_ior->location, "Index of refraction not known for '{}'\n", ext_ior_name);
}
} else {
ext_ior = inner_bsdf->get_child_value_optional("extIOR", 1.0f);
}
material.type = Material::Type::DIELECTRIC;
material.index_of_refraction = ext_ior == 0.0f ? int_ior : int_ior / ext_ior;
if (inner_bsdf_type == "roughdielectric") {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
} else {
material.linear_roughness = 0.0f;
}
} else if (inner_bsdf_type == "difftrans") {
material.type = Material::Type::DIFFUSE;
parse_rgb_or_texture(inner_bsdf, "transmittance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
} else {
WARNING(inner_bsdf->location, "WARNING: BSDF type '{}' not supported!\n", inner_bsdf_type);
return MaterialHandle::get_default();
}
return scene.asset_manager.add_material(std::move(material));
}
static MediumHandle parse_medium(const XMLNode * node, Scene & scene) {
const XMLNode * xml_medium = node->get_child_by_tag("medium");
if (!xml_medium) {
return MediumHandle { INVALID };
}
StringView medium_type = xml_medium->get_attribute_value("type");
if (medium_type == "homogeneous") {
Medium medium = { };
if (const XMLAttribute * name = xml_medium->get_attribute("name")) {
medium.name = String(name->value, scene.allocator);
}
const XMLNode * xml_sigma_a = xml_medium->get_child_by_name("sigmaA");
const XMLNode * xml_sigma_s = xml_medium->get_child_by_name("sigmaS");
const XMLNode * xml_sigma_t = xml_medium->get_child_by_name("sigmaT");
const XMLNode * xml_albedo = xml_medium->get_child_by_name("albedo"); // Single scatter albedo
Vector3 sigma_a = { };
Vector3 sigma_s = { };
if (!((xml_sigma_a && xml_sigma_s) ^ (xml_sigma_t && xml_albedo))) {
WARNING(xml_medium->location, "WARNING: Incorrect configuration of Medium properties\nPlease provide EITHER sigmaA and sigmaS OR sigmaT and albedo\n");
} else if (xml_sigma_a && xml_sigma_s) {
sigma_a = xml_sigma_a->get_attribute_value<Vector3>("value");
sigma_s = xml_sigma_s->get_attribute_value<Vector3>("value");
} else {
Vector3 sigma_t = xml_sigma_t->get_attribute_value<Vector3>("value");
Vector3 albedo = xml_albedo ->get_attribute_value<Vector3>("value");
sigma_s = albedo * sigma_t;
sigma_a = sigma_t - sigma_s;
}
float scale = xml_medium->get_child_value_optional("scale", 1.0f);
medium.set_A_and_d(scale * sigma_a, scale * sigma_s);
if (const XMLNode * phase = xml_medium->get_child_by_tag("phase")) {
StringView phase_type = phase->get_attribute_value("type");
if (phase_type == "isotropic") {
medium.g = 0.0f;
} else if (phase_type == "hg") {
medium.g = phase->get_child_value_optional("g", 0.0f);
} else {
WARNING(xml_medium->location, "WARNING: Phase function type '{}' not supported!\n", phase_type);
}
}
return scene.asset_manager.add_medium(medium);
} else {
WARNING(xml_medium->location, "WARNING: Medium type '{}' not supported!\n", medium_type);
}
return MediumHandle { INVALID };
}
static MeshDataHandle parse_shape(const XMLNode * node, Allocator * allocator, Scene & scene, StringView path, String * name) {
StringView type = node->get_attribute_value<StringView>("type");
if (type == "obj" || type == "ply") {
String filename = Util::combine_stringviews(path, node->get_child_value<StringView>("filename"), scene.allocator);
MeshDataHandle mesh_data_handle;
if (type == "obj") {
mesh_data_handle = scene.asset_manager.add_mesh_data(filename, OBJLoader::load);
} else {
mesh_data_handle = scene.asset_manager.add_mesh_data(filename, PLYLoader::load);
}
*name = String(Util::remove_directory(filename.view()), scene.allocator);
return mesh_data_handle;
} else if (type == "rectangle" || type == "cube" || type == "disk" || type == "cylinder" || type == "sphere") {
Matrix4 transform = parse_transform_matrix(node);
Array<Triangle> triangles;
if (type == "rectangle") {
triangles = Geometry::rectangle(transform);
} else if (type == "cube") {
triangles = Geometry::cube(transform);
} else if (type == "disk") {
triangles = Geometry::disk(transform);
} else if (type == "cylinder") {
Vector3 p0 = node->get_child_value_optional("p0", Vector3(0.0f, 0.0f, 0.0f));
Vector3 p1 = node->get_child_value_optional("p1", Vector3(0.0f, 0.0f, 1.0f));
float radius = node->get_child_value_optional("radius", 1.0f);
triangles = Geometry::cylinder(transform, p0, p1, radius);
} else if (type == "sphere") {
float radius = node->get_child_value_optional("radius", 1.0f);
Vector3 center = Vector3(0.0f);
const XMLNode * xml_center = node->get_child_by_name("center");
if (xml_center) {
center = Vector3(
xml_center->get_attribute_optional("x", 0.0f),
xml_center->get_attribute_optional("y", 0.0f),
xml_center->get_attribute_optional("z", 0.0f)
);
}
transform = transform * Matrix4::create_translation(center) * Matrix4::create_scale(radius);
triangles = Geometry::sphere(transform);
} else {
ASSERT_UNREACHABLE();
}
*name = String(type, scene.allocator);
return scene.asset_manager.add_mesh_data(std::move(triangles));
} else if (type == "serialized") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel);
int shape_index = node->get_child_value_optional("shapeIndex", 0);
*name = Format(scene.allocator).format("{}_{}"_sv, filename_rel, shape_index);
String bvh_filename = Format().format("{}.shape_{}.bvh"_sv, filename_abs, shape_index);
auto fallback_loader = [filename_abs = std::move(filename_abs), location = node->location, shape_index](const String & filename, Allocator * allocator) {
return SerializedLoader::load(filename_abs, allocator, location, shape_index);
};
return scene.asset_manager.add_mesh_data(bvh_filename, bvh_filename, fallback_loader);
} else if (type == "hair") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, scene.allocator);
*name = String(filename_rel, scene.allocator);
float radius = node->get_child_value_optional("radius", 0.0025f);
auto fallback_loader = [location = node->location, radius](const String & filename, Allocator * allocator) {
return MitshairLoader::load(filename, allocator, location, radius);
};
return scene.asset_manager.add_mesh_data(filename_abs, fallback_loader);
} else {
WARNING(node->location, "WARNING: Shape type '{}' not supported!\n", type);
return MeshDataHandle { INVALID };
}
}
static void walk_xml_tree(const XMLNode * node, Allocator * allocator, Scene & scene, ShapeGroupMap & shape_group_map, MaterialMap & material_map, TextureMap & texture_map, StringView path) {
if (node->tag == "bsdf") {
MaterialHandle material_handle = parse_material(node, scene, material_map, texture_map, path);
const Material & material = scene.asset_manager.get_material(material_handle);
material_map.insert(material.name, material_handle);
} else if (node->tag == "texture") {
Vector3 scale = 1.0f;
parse_texture(node, texture_map, path, scene, &scale);
} else if (node->tag == "shape") {
StringView type = node->get_attribute_value<StringView>("type");
if (type == "shapegroup") {
if (node->children.size() > 0) {
const XMLNode * shape = node->get_child_by_tag("shape");
if (!shape) {
ERROR(node->location, "Shapegroup needs a <shape> child!\n");
}
String name = { };
MeshDataHandle mesh_data_handle = parse_shape(shape, allocator, scene, path, &name);
MaterialHandle material_handle = parse_material(shape, scene, material_map, texture_map, path);
StringView id = node->get_attribute_value<StringView>("id");
shape_group_map[id] = { mesh_data_handle, material_handle };
}
} else if (type == "instance") {
const XMLNode * ref = node->get_child_by_tag("ref");
if (!ref) {
WARNING(node->location, "Instance without ref!\n");
return;
}
StringView id = ref->get_attribute_value<StringView>("id");
const ShapeGroup * shape_group = shape_group_map.try_get(id);
if (shape_group && shape_group->mesh_data_handle.handle != INVALID) {
Mesh & mesh = scene.add_mesh(id, shape_group->mesh_data_handle, shape_group->material_handle);
parse_transform(node, &mesh.position, &mesh.rotation, &mesh.scale);
}
} else {
String name = { };
MeshDataHandle mesh_data_handle = parse_shape(node, allocator, scene, path, &name);
MaterialHandle material_handle = parse_material(node, scene, material_map, texture_map, path);
MediumHandle medium_handle = parse_medium(node, scene);
if (material_handle.handle != INVALID) {
Material & material = scene.asset_manager.get_material(material_handle);
if (material.medium_handle.handle != INVALID && material.medium_handle.handle != medium_handle.handle) {
// This Material is already used with a different Medium
// Make a copy of the Material and add it as a new Material to the Scene
Material material_copy = material;
material_copy.medium_handle = medium_handle;
material_handle = scene.asset_manager.add_material(std::move(material_copy));
} else {
material.medium_handle = medium_handle;
}
}
if (mesh_data_handle.handle != INVALID) {
Mesh & mesh = scene.add_mesh(std::move(name), mesh_data_handle, material_handle);
// Do not apply transform to primitive shapes, since they have the transform baked into their vertices
bool type_is_primitive = type == "rectangle" || type == "cube" || type == "disk" || type == "cylinder" || type == "sphere";
if (!type_is_primitive) {
parse_transform(node, &mesh.position, &mesh.rotation, &mesh.scale);
}
}
}
} else if (node->tag == "sensor") {
StringView camera_type = node->get_attribute_value<StringView>("type");
if (camera_type == "perspective" || camera_type == "perspective_rdist" || camera_type == "thinlens") {
if (const XMLNode * fov = node->get_child_by_name("fov")) {
scene.camera.set_fov(Math::deg_to_rad(fov->get_attribute_value<float>("value")));
}
if (camera_type == "perspective") {
scene.camera.aperture_radius = 0.0f;
} else {
scene.camera.aperture_radius = node->get_child_value_optional("apertureRadius", 0.05f);
scene.camera.focal_distance = node->get_child_value_optional("focusDistance", 10.0f);
}
parse_transform(node, &scene.camera.position, &scene.camera.rotation, nullptr, Vector3(0.0f, 0.0f, -1.0f));
} else {
WARNING(node->location, "WARNING: Camera type '{}' not supported!\n", camera_type);
}
if (const XMLNode * film = node->get_child_by_tag("film")) {
cpu_config.initial_width = film->get_child_value_optional("width", cpu_config.initial_width);
cpu_config.initial_height = film->get_child_value_optional("height", cpu_config.initial_height);
scene.camera.resize(cpu_config.initial_width, cpu_config.initial_height);
}
} else if (node->tag == "integrator") {
gpu_config.num_bounces = node->get_child_value_optional("maxDepth", gpu_config.num_bounces);
} else if (node->tag == "emitter") {
StringView emitter_type = node->get_attribute_value<StringView>("type");
if (emitter_type == "area") {
WARNING(node->location, "Area emitter defined without geometry!\n");
} else if (emitter_type == "envmap") {
StringView filename_rel = node->get_child_value<StringView>("filename");
StringView extension = Util::get_file_extension(filename_rel);
if (extension.is_empty()) {
WARNING(node->location, "Environment Map '{}' has no file extension!\n", filename_rel);
} else if (extension != "hdr") {
WARNING(node->location, "Environment Map '{}' has unsupported file extension. Only HDR Environment Maps are supported!\n", filename_rel);
} else {
cpu_config.sky_filename = Util::combine_stringviews(path, filename_rel, scene.allocator);
}
} else if (emitter_type == "point") {
// Make small area light
constexpr float RADIUS = 0.0001f;
Matrix4 transform = parse_transform_matrix(node) * Matrix4::create_scale(RADIUS);
Array<Triangle> triangles = Geometry::sphere(transform, 0);
MeshDataHandle mesh_data_handle = scene.asset_manager.add_mesh_data(std::move(triangles));
Material material = { };
material.type = Material::Type::LIGHT;
material.emission = node->get_child_value_optional<Vector3>("intensity", Vector3(1.0f));
MaterialHandle material_handle = scene.asset_manager.add_material(std::move(material));
scene.add_mesh("PointLight", mesh_data_handle, material_handle);
} else {
WARNING(node->location, "Emitter type '{}' is not supported!\n", emitter_type);
}
} else if (node->tag == "include") {
StringView filename_rel = node->get_attribute_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, allocator);
MitsubaLoader::load(filename_abs, allocator, scene);
} else for (int i = 0; i < node->children.size(); i++) {
walk_xml_tree(&node->children[i], allocator, scene, shape_group_map, material_map, texture_map, path);
}
}
void MitsubaLoader::load(const String & filename, Allocator * allocator, Scene & scene) {
XMLParser xml_parser(filename, allocator);
XMLNode root = xml_parser.parse_root();
const XMLNode * scene_node = root.get_child_by_tag("scene");
if (!scene_node) {
ERROR(root.location, "File does not contain a <scene> tag!\n");
}
{
StringView version = scene_node->get_attribute_value<StringView>("version");
Parser version_parser(version);
int major = version_parser.parse_int(); version_parser.expect('.');
int minor = version_parser.parse_int(); version_parser.expect('.');
int patch = version_parser.parse_int();
int version_number = major * 100 + minor * 10 + patch;
if (version_number >= 200) {
ERROR(scene_node->location, "Mitsuba 2 files are not supported!\n");
}
}
ShapeGroupMap shape_group_map(allocator);
MaterialMap material_map (allocator);
TextureMap texture_map (allocator);
walk_xml_tree(scene_node, allocator, scene, shape_group_map, material_map, texture_map, Util::get_directory(filename.view()));
}
| 38.645441 | 191 | 0.688586 | dennis-lynch |
6e15f02e9829b9cf7c214485ba63634a9445fd68 | 45,024 | hpp | C++ | Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp | Samuel-Harden/SimWorldsBoids | ae560181aa77bde75adc4ab2687952d919b4e988 | [
"MIT"
] | null | null | null | Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp | Samuel-Harden/SimWorldsBoids | ae560181aa77bde75adc4ab2687952d919b4e988 | [
"MIT"
] | null | null | null | Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp | Samuel-Harden/SimWorldsBoids | ae560181aa77bde75adc4ab2687952d919b4e988 | [
"MIT"
] | null | null | null | // Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSONPATH_FILTER_HPP
#define JSONCONS_JSONPATH_FILTER_HPP
#include <string>
#include <sstream>
#include <vector>
#include <istream>
#include <cstdlib>
#include <memory>
#include <regex>
#include "jsoncons/json.hpp"
#include "jsonpath_error_category.hpp"
namespace jsoncons { namespace jsonpath {
template <class Json>
class jsonpath_evaluator;
enum class filter_states
{
start,
cr,
lf,
expect_right_round_bracket,
expect_oper_or_right_round_bracket,
expect_path_or_value,
expect_regex,
regex,
single_quoted_text,
double_quoted_text,
unquoted_text,
path,
value,
oper
};
enum class token_types
{
left_paren,
right_paren,
term,
eq,
ne,
regex,
ampamp,
pipepipe,
lt,
gt,
lte,
gte,
plus,
minus,
exclaim,
done
};
template <class Json>
class term
{
public:
typedef typename Json::string_type string_type;
typedef typename Json::char_type char_type;
virtual ~term() {}
virtual void initialize(const Json&)
{
}
virtual bool accept_single_node() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json evaluate_single_node() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool exclaim() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool eq(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool eq(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ne(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ne(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool regex(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool regex2(const string_type&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ampamp(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ampamp(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool pipepipe(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool pipepipe(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool lt(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool lt(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool gt(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool gt(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json minus(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json minus(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json unary_minus() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json plus(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json plus(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
};
template <class Json>
class token
{
token_types type_;
std::shared_ptr<term<Json>> term_ptr_;
public:
token(token_types type)
: type_(type)
{
}
token(token_types type, std::shared_ptr<term<Json>> term_ptr)
: type_(type), term_ptr_(term_ptr)
{
}
token(const token& t)
: type_(t.type_), term_ptr_(t.term_ptr_)
{
}
token_types type() const
{
return type_;
}
std::shared_ptr<term<Json>> term_ptr()
{
return term_ptr_;
}
void initialize(const Json& context_node)
{
if (term_ptr_.get() != nullptr)
{
term_ptr_->initialize(context_node);
}
}
};
template <class Json>
class token_stream
{
std::vector<token<Json>>& tokens_;
size_t index_;
public:
token_stream(std::vector<token<Json>>& tokens)
: tokens_(tokens), index_(0)
{
}
token<Json> get()
{
static token<Json> done = token<Json>(token_types::done);
return index_ < tokens_.size() ? tokens_[index_++] : done;
}
void putback()
{
--index_;
}
};
template <class Json>
bool ampamp(const Json& lhs, const Json& rhs)
{
return lhs.as_bool() && rhs.as_bool();
}
template <class Json>
bool pipepipe(const Json& lhs, const Json& rhs)
{
return lhs.as_bool() || rhs.as_bool();
}
template <class Json>
bool lt(const Json& lhs, const Json& rhs)
{
bool result = false;
if (lhs. template is<unsigned long long>() && rhs. template is<unsigned long long>())
{
result = lhs. template as<unsigned long long>() < rhs. template as<unsigned long long>();
}
else if (lhs. template is<long long>() && rhs. template is<long long>())
{
result = lhs. template as<long long>() < rhs. template as<long long>();
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = lhs.as_double() < rhs.as_double();
}
else if (lhs.is_string() && rhs.is_string())
{
result = lhs.as_string() < rhs.as_string();
}
return result;
}
template <class Json>
bool gt(const Json& lhs, const Json& rhs)
{
return lt(rhs,lhs);
}
template <class Json>
Json plus(const Json& lhs, const Json& rhs)
{
Json result = Json(jsoncons::null_type());
if (lhs.is_integer() && rhs.is_integer())
{
result = Json(((lhs.as_integer() + rhs.as_integer())));
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = Json((lhs.as_double() + rhs.as_double()));
}
else if (lhs.is_uinteger() && rhs.is_uinteger())
{
result = Json((lhs.as_uinteger() + rhs.as_uinteger()));
}
return result;
}
template <class Json>
Json unary_minus(const Json& lhs)
{
Json result = Json::null();
if (lhs.is_integer())
{
result = -lhs.as_integer();
}
else if (lhs.is_double())
{
result = -lhs.as_double();
}
return result;
}
template <class Json>
Json minus(const Json& lhs, const Json& rhs)
{
Json result = Json::null();
if (lhs.is_integer() && rhs.is_integer())
{
result = ((lhs.as_integer() - rhs.as_integer()));
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = (lhs.as_double() - rhs.as_double());
}
else if (lhs.is_uinteger() && rhs.is_uinteger() && lt(rhs,lhs))
{
result = (lhs.as_uinteger() - rhs.as_uinteger());
}
return result;
}
template <class Json>
class value_term : public term<Json>
{
Json value_;
public:
template <class T>
value_term(const T& value)
: value_(value)
{
}
bool accept_single_node() const override
{
return value_.as_bool();
}
Json evaluate_single_node() const override
{
return value_;
}
bool exclaim() const override
{
return !value_.as_bool();
}
bool eq(const term<Json>& rhs) const override
{
return rhs.eq(value_);
}
bool eq(const Json& rhs) const override
{
return value_ == rhs;
}
bool ne(const term<Json>& rhs) const override
{
return rhs.ne(value_);
}
bool ne(const Json& rhs) const override
{
return value_ != rhs;
}
bool regex(const term<Json>& rhs) const override
{
return rhs.regex2(value_.as_string());
}
bool ampamp(const term<Json>& rhs) const override
{
return rhs.ampamp(value_);
}
bool ampamp(const Json& rhs) const override
{
return jsoncons::jsonpath::ampamp(value_,rhs);
}
bool pipepipe(const term<Json>& rhs) const override
{
return rhs.pipepipe(value_);
}
bool pipepipe(const Json& rhs) const override
{
return jsoncons::jsonpath::pipepipe(value_,rhs);
}
bool lt(const term<Json>& rhs) const override
{
return rhs.gt(value_);
}
bool lt(const Json& rhs) const override
{
return jsoncons::jsonpath::lt(value_,rhs);
}
bool gt(const term<Json>& rhs) const override
{
return rhs.lt(value_);
}
bool gt(const Json& rhs) const override
{
return jsoncons::jsonpath::gt(value_,rhs);
}
Json minus(const term<Json>& rhs) const override
{
return jsoncons::jsonpath::plus(rhs.unary_minus(),value_);
}
Json minus(const Json& rhs) const override
{
return jsoncons::jsonpath::minus(value_,rhs);
}
Json unary_minus() const override
{
return jsoncons::jsonpath::unary_minus(value_);
}
Json plus(const term<Json>& rhs) const override
{
return rhs.plus(value_);
}
Json plus(const Json& rhs) const override
{
return jsoncons::jsonpath::plus(value_,rhs);
}
};
template <class Json>
class regex_term : public term<Json>
{
typedef typename Json::char_type char_type;
typedef typename Json::string_type string_type;
string_type pattern_;
std::regex::flag_type flags_;
public:
regex_term(const string_type& pattern, std::regex::flag_type flags)
: pattern_(pattern), flags_(flags)
{
}
bool regex2(const string_type& subject) const override
{
std::basic_regex<char_type> pattern(pattern_,
flags_);
return std::regex_match(subject, pattern);
}
};
template <class Json>
class path_term : public term<Json>
{
typedef typename Json::string_type string_type;
string_type path_;
Json nodes_;
public:
path_term(const string_type& path)
: path_(path)
{
}
void initialize(const Json& context_node) override
{
jsonpath_evaluator<Json> evaluator;
evaluator.evaluate(context_node,path_);
nodes_ = evaluator.get_values();
}
bool accept_single_node() const override
{
return nodes_.size() != 0;
}
Json evaluate_single_node() const override
{
return nodes_.size() == 1 ? nodes_[0] : nodes_;
}
bool exclaim() const override
{
return nodes_.size() == 0;
}
bool eq(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.eq(nodes_[i]);
}
}
return result;
}
bool eq(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = nodes_[i] == rhs;
}
}
return result;
}
bool ne(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.ne(nodes_[i]);
}
}
return result;
}
bool ne(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = nodes_[i] != rhs;
}
}
return result;
}
bool regex(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.regex2(nodes_[i].as_string());
}
}
return result;
}
bool ampamp(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.ampamp(nodes_[i]);
}
}
return result;
}
bool ampamp(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::ampamp(nodes_[i],rhs);
}
}
return result;
}
bool pipepipe(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.pipepipe(nodes_[i]);
}
}
return result;
}
bool pipepipe(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::pipepipe(nodes_[i],rhs);
}
}
return result;
}
bool lt(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::lt(nodes_[i],rhs);
}
}
return result;
}
bool lt(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.gt(nodes_[i]);
}
}
return result;
}
bool gt(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::gt(nodes_[i],rhs);
}
}
return result;
}
bool gt(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.lt(nodes_[i]);
}
}
return result;
}
Json minus(const Json& rhs) const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::minus(nodes_[0],rhs) : Json(jsoncons::null_type());
}
Json minus(const term<Json>& rhs) const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::plus(rhs.unary_minus(),nodes_[0]) : Json(jsoncons::null_type());
}
Json unary_minus() const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::unary_minus(nodes_[0]) : Json::null();
}
Json plus(const Json& rhs) const override
{
static auto a_null = Json(jsoncons::null_type());
return nodes_.size() == 1 ? jsoncons::jsonpath::plus(nodes_[0],rhs) : a_null;
}
Json plus(const term<Json>& rhs) const override
{
static auto a_null = Json(jsoncons::null_type());
return nodes_.size() == 1 ? rhs.plus(nodes_[0]) : a_null;
}
};
template <class Json>
class jsonpath_filter_parser
{
typedef typename Json::string_type string_type;
typedef typename Json::char_type char_type;
size_t& line_;
size_t& column_;
filter_states state_;
string_type buffer_;
std::vector<token<Json>> tokens_;
int depth_;
const char_type* begin_input_;
const char_type* end_input_;
const char_type*& p_;
filter_states pre_line_break_state_;
public:
jsonpath_filter_parser(const char_type** expr, size_t* line,size_t* column)
: line_(*line), column_(*column), depth_(0), p_(*expr)
{
}
bool exists(const Json& context_node)
{
for (auto it=tokens_.begin(); it != tokens_.end(); ++it)
{
it->initialize(context_node);
}
bool result = false;
token_stream<Json> ts(tokens_);
auto e = expression(ts);
result = e->accept_single_node();
return result;
}
Json eval(const Json& context_node)
{
try
{
for (auto it=tokens_.begin(); it != tokens_.end(); ++it)
{
it->initialize(context_node);
}
token_stream<Json> ts(tokens_);
auto e = expression(ts);
Json result = e->evaluate_single_node();
return result;
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
}
std::shared_ptr<term<Json>> primary(token_stream<Json>& ts)
{
auto t = ts.get();
switch (t.type())
{
case token_types::left_paren:
{
auto expr = expression(ts);
t = ts.get();
if (t.type() != token_types::right_paren)
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_right_brace,line_,column_);
}
return expr;
}
case token_types::term:
return t.term_ptr();
case token_types::exclaim:
{
Json val = Json(primary(ts)->exclaim());
auto expr = std::make_shared<value_term<Json>>(val);
return expr;
}
case token_types::minus:
{
Json val = primary(ts)->unary_minus();
auto expr = std::make_shared<value_term<Json>>(val);
return expr;
}
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_primary,line_,column_);
}
}
std::shared_ptr<term<Json>> expression(token_stream<Json>& ts)
{
auto left = make_term(ts);
auto t = ts.get();
while (true)
{
switch (t.type())
{
case token_types::plus:
{
Json val = left->plus(*(make_term(ts)));
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::minus:
{
Json val = left->minus(*(make_term(ts)));
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
default:
ts.putback();
return left;
}
}
return left;
}
std::shared_ptr<term<Json>> make_term(token_stream<Json>& ts)
{
auto left = primary(ts);
auto t = ts.get();
while (true)
{
switch (t.type())
{
case token_types::eq:
{
bool e = left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::ne:
{
bool e = left->ne(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::regex:
{
bool e = left->regex(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::ampamp:
{
bool e = left->ampamp(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::pipepipe:
{
bool e = left->pipepipe(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::lt:
{
bool e = left->lt(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::gt:
{
bool e = left->gt(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::lte:
{
bool e = left->lt(*(primary(ts))) || left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::gte:
{
bool e = left->gt(*(primary(ts))) || left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
default:
ts.putback();
return left;
}
}
}
void parse(const char_type* expr, size_t length)
{
parse(expr,expr+length);
}
void parse(const char_type* expr, const char_type* end_expr)
{
p_ = expr;
end_input_ = end_expr;
depth_ = 0;
tokens_.clear();
state_ = filter_states::start;
bool done = false;
while (!done && p_ < end_input_)
{
switch (state_)
{
case filter_states::cr:
++line_;
column_ = 1;
switch (*p_)
{
case '\n':
state_ = pre_line_break_state_;
++p_;
++column_;
break;
default:
state_ = pre_line_break_state_;
break;
}
break;
case filter_states::lf:
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case filter_states::start:
switch (*p_)
{
case '\r':
case '\n':
pre_line_break_state_ = state_;
state_ = filter_states::lf;
break;
case '(':
state_ = filter_states::expect_path_or_value;
++depth_;
tokens_.push_back(token<Json>(token_types::left_paren));
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
}
break;
}
++p_;
++column_;
break;
case filter_states::oper:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '!':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::ne));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::exclaim));
}
break;
case '&':
if (p_+1 < end_input_ && *(p_+1) == '&')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::ampamp));
}
break;
case '|':
if (p_+1 < end_input_ && *(p_+1) == '|')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::pipepipe));
}
break;
case '=':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::eq));
}
else if (p_+1 < end_input_ && *(p_+1) == '~')
{
++p_;
++column_;
state_ = filter_states::expect_regex;
tokens_.push_back(token<Json>(token_types::regex));
}
break;
case '>':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::gte));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::gt));
}
break;
case '<':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::lte));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::lt));
}
break;
case '+':
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::plus));
break;
case '-':
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::minus));
break;
case ' ':case '\t':
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
}
++p_;
++column_;
break;
case filter_states::unquoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::oper;
}
break;
case ')':
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
state_ = filter_states::start;
done = true;
}
else
{
state_ = filter_states::expect_path_or_value;
}
++p_;
++column_;
break;
case ' ':case '\t':
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
++p_;
++column_;
break;
default:
buffer_.push_back(*p_);
++p_;
++column_;
break;
}
}
break;
case filter_states::single_quoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '\\':
buffer_.push_back(*p_);
if (p_+1 < end_input_)
{
++p_;
++column_;
buffer_.push_back(*p_);
}
break;
case '\'':
buffer_.push_back('\"');
//if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
case filter_states::double_quoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '\\':
buffer_.push_back(*p_);
if (p_+1 < end_input_)
{
++p_;
++column_;
buffer_.push_back(*p_);
}
break;
case '\"':
buffer_.push_back(*p_);
//if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
case filter_states::expect_path_or_value:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
state_ = filter_states::oper;
// don't increment
break;
case '@':
buffer_.push_back(*p_);
state_ = filter_states::path;
++p_;
++column_;
break;
case ' ':case '\t':
++p_;
++column_;
break;
case '\'':
buffer_.push_back('\"');
state_ = filter_states::single_quoted_text;
++p_;
++column_;
break;
case '\"':
buffer_.push_back(*p_);
state_ = filter_states::double_quoted_text;
++p_;
++column_;
break;
case '(':
++depth_;
tokens_.push_back(token<Json>(token_types::left_paren));
++p_;
++column_;
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
++p_;
++column_;
break;
default:
// don't increment
state_ = filter_states::unquoted_text;
break;
};
break;
case filter_states::expect_oper_or_right_round_bracket:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case ' ':case '\t':
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
state_ = filter_states::oper;
// don't increment p
}
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
};
break;
case filter_states::expect_right_round_bracket:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case ' ':case '\t':
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
else
{
state_ = filter_states::expect_oper_or_right_round_bracket;
}
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
};
++p_;
++column_;
break;
case filter_states::path:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
if (buffer_.length() > 0)
{
tokens_.push_back(token<Json>(token_types::term,std::make_shared<path_term<Json>>(buffer_)));
buffer_.clear();
}
state_ = filter_states::oper;
// don't increment
}
break;
case ')':
if (buffer_.length() > 0)
{
tokens_.push_back(token<Json>(token_types::term,std::make_shared<path_term<Json>>(buffer_)));
tokens_.push_back(token<Json>(token_types::right_paren));
buffer_.clear();
}
if (--depth_ == 0)
{
state_ = filter_states::start;
done = true;
}
else
{
state_ = filter_states::expect_path_or_value;
}
++p_;
++column_;
break;
default:
buffer_.push_back(*p_);
++p_;
++column_;
break;
};
break;
case filter_states::expect_regex:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '/':
state_ = filter_states::regex;
break;
case ' ':case '\t':
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_slash,line_,column_);
break;
};
++p_;
++column_;
break;
case filter_states::regex:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '/':
//if (buffer_.length() > 0)
{
std::regex::flag_type flags = std::regex_constants::ECMAScript;
if (p_+1 < end_input_ && *(p_+1) == 'i')
{
++p_;
++column_;
flags |= std::regex_constants::icase;
}
tokens_.push_back(token<Json>(token_types::term,std::make_shared<regex_term<Json>>(buffer_,flags)));
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
default:
++p_;
++column_;
break;
}
}
if (depth_ != 0)
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unbalanced_paren,line_,column_);
}
}
};
}}
#endif | 30.076152 | 128 | 0.427172 | Samuel-Harden |
6e15f4a68a455b18d41e30fc01dab5c134fd3a9d | 216 | cpp | C++ | src/rynx/tech/reflection.cpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | 11 | 2019-08-19T08:44:14.000Z | 2020-09-22T20:04:46.000Z | src/rynx/tech/reflection.cpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null | src/rynx/tech/reflection.cpp | Apodus/rynx | 3e1babc2f2957702ba2b09d78be3a959f2f4ea18 | [
"MIT"
] | null | null | null |
#include <rynx/tech/reflection.hpp>
namespace rynx::reflection::internal {
registration_object* global_linked_list_initializer_head = nullptr;
registration_object* global_linked_list_initializer_tail = nullptr;
} | 30.857143 | 68 | 0.837963 | Apodus |
6e1636d1ea96946231d627d9212c2f85697003b9 | 584 | cpp | C++ | Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
unordered_map<int , int>one;
unordered_multimap<int,int>two;
int num ;
cin >> num;
int temp ;
for(int i= 0 ; i < num ; i++)
{
cin >> temp ;
one.insert(make_pair(temp ,i));
two.insert(make_pair(temp, i));
}
int q;
cin >> q;
long long comp1 = 0;
long long comp2 = 0;
while(q--)
{
cin >> temp ;
comp1 += ((one.find(temp)->second) +1 );
comp2 += (num - (two.find(temp)->second) );
}
cout << comp1 << " " << comp2 << endl;
return 0;
}
| 18.25 | 50 | 0.506849 | LawranceMichaelite |
6e17bd8e1c5370f6e1ee72f02636683003917f63 | 339 | hpp | C++ | cxx/line/line_c2.hpp | EQt/treelas | 24a5cebf101180822198806c0a4131b0efb7a36d | [
"MIT"
] | 3 | 2020-06-18T13:31:26.000Z | 2021-04-05T17:42:56.000Z | cxx/line/line_c2.hpp | EQt/treelas | 24a5cebf101180822198806c0a4131b0efb7a36d | [
"MIT"
] | null | null | null | cxx/line/line_c2.hpp | EQt/treelas | 24a5cebf101180822198806c0a4131b0efb7a36d | [
"MIT"
] | null | null | null | /* Compared to cline.hpp, save more memory */
#pragma once
template <typename float_ = double>
void
dp_line_c2(const int n,
const float_ *y,
const float_ lam,
float_ *beta);
extern template
void
dp_line_c2(const int n,
const double *y,
const double lam,
double *beta);
| 17.842105 | 45 | 0.59587 | EQt |
6e1922c98d47293a8a4193f5994b49955608852c | 10,256 | cpp | C++ | test/rix/core/helpers/src/Textures.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 217 | 2015-01-06T09:26:53.000Z | 2022-03-23T14:03:18.000Z | test/rix/core/helpers/src/Textures.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 10 | 2015-01-25T12:42:05.000Z | 2017-11-28T16:10:16.000Z | test/rix/core/helpers/src/Textures.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 44 | 2015-01-13T01:19:41.000Z | 2022-02-21T21:35:08.000Z | // Copyright NVIDIA Corporation 2012
// 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 NVIDIA CORPORATION 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 ``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 <dp/math/math.h>
#include <dp/math/Matmnt.h>
#include <test/rix/core/helpers/SimplexNoise1234.h>
#include <test/rix/core/helpers/Textures.h>
namespace dp
{
namespace rix
{
using namespace std;
using namespace math;
namespace util
{
TextureObjectDataSharedPtr TextureObjectData::create()
{
return( std::shared_ptr<TextureObjectData>( new TextureObjectData() ) );
}
TextureObjectData::TextureObjectData()
{
}
TextureObjectData::~TextureObjectData()
{
}
TextureObjectDataSharedPtr createTextureColored( const Vec2ui& size, const Vec4f& color )
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
unsigned int length = size[0] * size[1];
texture->m_data.resize(length);
for(unsigned int i = 0; i < length; i++)
{
texture->m_data[i] = color;
}
return texture;
}
TextureObjectDataSharedPtr createTextureCheckered(const Vec2ui& size, const Vec2ui& tileCount, const Vec4f& oddColor, const Vec4f& evenColor)
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < size[1]; iy++)
{
unsigned iycheck = tileCount[1] * iy / size[1];
for(unsigned int ix = 0; ix < size[0]; ix++)
{
unsigned ixcheck = tileCount[0] * ix / size[0];
texture->m_data[ iy * size[1] + ix ] = (iycheck^ixcheck)&1 ? oddColor : evenColor;
}
}
return texture;
}
TextureObjectDataSharedPtr createTextureGradient(const Vec2ui& size, const Vec4f& bottomColor, const Vec4f& topLeftColor, const Vec4f& topRightColor)
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < size[1]; iy++)
{
float weight0 = (float)iy / (size[1] - 1);
float sumWeight12 = 1.0f - weight0;
for(unsigned int ix = 0; ix < size[0]; ix++)
{
float weight1 = sumWeight12 * ix / (size[0] - 1);
float weight2 = sumWeight12 - weight1;
Vec4f color = weight0 * bottomColor + weight1 * topLeftColor + weight2 * topRightColor;
texture->m_data[ iy * size[1] + ix ] = color;
}
}
return texture;
}
TextureObjectDataSharedPtr convertHeightMapToNormalMap( const TextureObjectDataSharedPtr& heightMap
, float factor ) //Maximum apparent bump depth
{
TextureObjectDataSharedPtr normalMap = TextureObjectData::create();
unsigned int texWidth = heightMap->m_size[0];
unsigned int texHeight = heightMap->m_size[1];
normalMap->m_size = heightMap->m_size;
normalMap->m_data.resize(texWidth * texHeight);
//Texel lengths in texture space
Vec2f incr( 2.0f / texWidth, 2.0f / texHeight );
//Loop through all texels and get our tangents and binormals by taking the central differences
for(unsigned int iy = 0; iy < texHeight; iy++)
{
for(unsigned int ix = 0; ix < texWidth; ix++)
{
unsigned int curTexel = iy * texWidth + ix;
unsigned int nextTexelX = ix < texWidth - 1 ? curTexel + 1 : iy * texWidth;
unsigned int prevTexelX = ix > 0 ? curTexel - 1 : iy * texWidth + texWidth - 1;
unsigned int nextTexelY = iy < texHeight - 1 ? curTexel + texWidth : ix;
unsigned int prevTexelY = iy > 0 ? curTexel - texWidth : curTexel + (texHeight - 1) * texWidth;
Vec3f tangent( incr[0]
, 0.0f
, (heightMap->m_data[nextTexelX][0] - heightMap->m_data[prevTexelX][0]) * factor );
Vec3f binormal( 0.0f
, incr[1]
, (heightMap->m_data[nextTexelY][0] - heightMap->m_data[prevTexelY][0]) * factor );
Vec3f normal = tangent ^ binormal;
normalize(normal);
//clamp the normal to [0, 1]
normalMap->m_data[curTexel] = Vec4f(0.5f, 0.5f, 0.5f, 0.0f) + 0.5f * Vec4f(normal, 0.0f);
}
}
return normalMap;
}
TextureObjectDataSharedPtr createNoiseTexture( const math::Vec2ui& size, float frequencyX, float frequencyY )
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
unsigned int texWidth = size[0];
unsigned int texHeight = size[1];
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < texHeight; iy++)
{
for(unsigned int ix = 0; ix < texWidth; ix++)
{
unsigned int curTexel = iy * texWidth + ix;
float intensity = 0.5f * ( dp::rix::util::SimplexNoise1234::noise( frequencyX * iy / texHeight - 1.0f, frequencyY * ix / texWidth - 1.0f ) + 1.0f );
texture->m_data[curTexel][0] = intensity;
texture->m_data[curTexel][1] = intensity;
texture->m_data[curTexel][2] = intensity;
texture->m_data[curTexel][3] = 1.0f;
}
}
return texture;
}
TextureObjectDataSharedPtr createPyramidNormalMap( const math::Vec2ui& size
, const math::Vec2ui& pyramidTiles
, float pyramidHeight ) //Depth of a pyramid in texel space
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
unsigned int texWidth = size[0];
unsigned int texHeight = size[1];
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
//Texel lengths in texture space
Vec2f incr( 1.0f / texWidth, 1.0f / texHeight );
//Dimensions of one pyramid
unsigned int pyramidIX = texWidth / pyramidTiles[0];
unsigned int pyramidIY = texHeight / pyramidTiles[1];
//Calculate all four occurring normals of the pyramid ahead of time
Vec4f wNormalLeft = Vec4f( -pyramidHeight, 0.0f, 0.5f * incr[0] * pyramidIX, 0.0f);
Vec4f wNormalRight = Vec4f( pyramidHeight, 0.0f, 0.5f * incr[0] * pyramidIX, 0.0f);
Vec4f wNormalTop = Vec4f( 0.0f, pyramidHeight, 0.5f * incr[1] * pyramidIY, 0.0f);
Vec4f wNormalBottom = Vec4f( 0.0f, -pyramidHeight, 0.5f * incr[1] * pyramidIY, 0.0f);
//Normalize our normals
wNormalLeft.normalize();
wNormalRight.normalize();
wNormalTop.normalize();
wNormalBottom.normalize();
//Clamp our normals to [0, 1]
wNormalLeft = 0.5f*wNormalLeft + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalRight = 0.5f*wNormalRight + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalTop = 0.5f*wNormalTop + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalBottom = 0.5f*wNormalBottom + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
for(unsigned int iy = 0; iy < texHeight; iy++)
{
//Get our vertical texel position relative to the center of the current pyramid tile
int iyrel = iy % pyramidIY - pyramidIY / 2;
for(unsigned int ix = 0; ix < texWidth; ix++)
{
//Get our horizontal texel position relative to the center of the current pyramid tile
int ixrel = ix % pyramidIX - pyramidIX / 2;
unsigned int curTexel = iy * texWidth + ix;
//Assign the appropriate normal according to what face of the pyramid we're on
if( iyrel > abs(ixrel) )
{
texture->m_data[curTexel] = wNormalTop;
}
else if( iyrel > ixrel )
{
texture->m_data[curTexel] = wNormalLeft;
}
else if( iyrel > -ixrel )
{
texture->m_data[curTexel] = wNormalRight;
}
else
{
texture->m_data[curTexel] = wNormalBottom;
}
}
}
return texture;
}
} // namespace generator
} // namespace util
} // namespace dp
| 40.698413 | 161 | 0.579076 | asuessenbach |
6e199ad362897f328f27659eb07ed40b8370fd8b | 3,835 | cpp | C++ | src/IntDivision.cpp | xf97/SolidityCheck | a859f4b65c7eea945ef7b9702c85cf3ff42f50f7 | [
"MIT"
] | 19 | 2019-11-26T21:59:41.000Z | 2022-01-23T16:32:24.000Z | src/IntDivision.cpp | xf97/SolidityCheck | a859f4b65c7eea945ef7b9702c85cf3ff42f50f7 | [
"MIT"
] | 1 | 2020-09-24T15:31:47.000Z | 2020-09-25T02:29:15.000Z | src/IntDivision.cpp | xf97/SolidityCheck | a859f4b65c7eea945ef7b9702c85cf3ff42f50f7 | [
"MIT"
] | 4 | 2020-01-05T12:18:47.000Z | 2021-12-29T15:34:04.000Z | //
// Created by xiaofeng on 2019/11/29.
//
//This program is used to judge integer division.
//source file
/*
author=__xiaofeng__
*/
//using head files
#include <iostream>
#include "IntDivision.h"
bool IntDivision::IsDivision(const string & _str)
{
if (_str.find(ID_DIV) < _str.size())
return true;
return false;
}
void IntDivision::GetIndex(const string& _str,vector<int>& _index)
{
_index.clear();
int index = 0;
while (_str.find(ID_DIV, index) < _str.size()) {
index = _str.find(ID_DIV, index);
_index.push_back(index);
index++;
}
}
void IntDivision::GetLeft(string & _str, int _index,const string& _sta)
{
int _i = _index;
_i--;
_str.clear();
while (isblank(_sta[_i]) && _i>=0)
_i--;
while (_i >= 0 && isdigit(_sta[_i])) {
_str.push_back(_sta[_i]);
_i--;
}
reverse(_str.begin(), _str.end());
}
void IntDivision::GetRight(string & _str, int _index, const string & _sta)
{
_str.clear();
_index++;
while (isblank(_sta[_index]) && _index >= 0)
_index++;
while (isdigit(_sta[_index]) && _index>=0)
{
_str.push_back(_sta[_index]);
_index++;
}
}
bool IntDivision::IsInt(const string & _str)
{
if (_str.empty())
return false;
for (auto i = _str.begin(); i != _str.end(); i++) {
if (!isdigit((*i)))
return false;
}
return true;
}
IntDivision::IntDivision(const string _report_name, const vector<string> _content)
{
report_name = _report_name;
content = _content;
IDName = "Integer Division";
OtherOperation = "All integer division results in Solidity are rounded down.\nBug level: warning";
}
IntDivision::~IntDivision()
{
report_name.clear();
content.clear();
IDName.clear();
OtherOperation.clear();
row_number.clear();
}
string IntDivision::MakeReport(const vector<int>& _row_number)
{
if (_row_number.size() == 0) {
return "No integer division.\n\n";
}
string _report = "";
_report += "[Bug 9]\n";
_report += "bug name: ";
_report += IDName;
_report += '\n';
_report += "number of bugs: ";
_report += to_string(_row_number.size());
_report += '\n';
_report += "row number: ";
for (auto i = _row_number.begin(); i != _row_number.end(); i++) {
_report += to_string((*i));
_report += " ";
}
_report += '\n';
if (OtherOperation.size() != 0) {
_report += "additional description: ";
_report += OtherOperation;
_report += '\n';
}
return _report;
}
int IntDivision::GetNumber()
{
return row_number.size();
}
vector<int> IntDivision::GetRowNumber()
{
return row_number;
}
void IntDivision::Detection()
{
string left = "";
string right = "";
vector<int> index;
for (int i = 0; i < content.size(); i++) {
if (IsDivision(content[i])) {
GetIndex(content[i],index);
for (auto j = index.begin(); j != index.end(); j++) {
GetLeft(left, (*j),content[i]);
GetRight(right, (*j),content[i]);
if (IsInt(left) && IsInt(right)) {
row_number.push_back((i + 1));
}
}
}
}
}
void IntDivision::Re_Detection()
{
regex reg{ID_RE_DIV};
for (int i = 0; i < content.size(); i++) {
if (content[i].find('/') < content.size()) {
smatch s;
if (regex_search(content[i], s, reg)) {
row_number.push_back(i + 1);
}
else
continue;
}
else
continue;
}
}
| 23.384146 | 103 | 0.524902 | xf97 |
6e1b7f60e33117a46bdf4be9916fc50f8acd238f | 16,099 | cc | C++ | components/global_media_controls/public/media_session_item_producer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/global_media_controls/public/media_session_item_producer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/global_media_controls/public/media_session_item_producer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 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 "components/global_media_controls/public/media_session_item_producer.h"
#include "base/containers/contains.h"
#include "base/metrics/histogram_functions.h"
#include "components/global_media_controls/public/media_item_manager.h"
#include "components/global_media_controls/public/media_item_ui.h"
#include "components/global_media_controls/public/media_session_item_producer_observer.h"
#include "media/base/media_switches.h"
namespace global_media_controls {
namespace {
constexpr int kAutoDismissTimerInMinutesDefault = 60; // minutes
constexpr const char kAutoDismissTimerInMinutesParamName[] = "timer_in_minutes";
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class MediaNotificationClickSource {
kMedia = 0,
kPresentation,
kMediaFling,
kMaxValue = kMediaFling
};
// Returns the time value to be used for the auto-dismissing of the
// notifications after they are inactive.
// If the feature (auto-dismiss) is disabled, the returned value will be
// TimeDelta::Max() which is the largest int64 possible.
base::TimeDelta GetAutoDismissTimerValue() {
if (!base::FeatureList::IsEnabled(media::kGlobalMediaControlsAutoDismiss))
return base::TimeDelta::Max();
return base::Minutes(base::GetFieldTrialParamByFeatureAsInt(
media::kGlobalMediaControlsAutoDismiss,
kAutoDismissTimerInMinutesParamName, kAutoDismissTimerInMinutesDefault));
}
} // namespace
MediaSessionItemProducer::Session::Session(
MediaSessionItemProducer* owner,
const std::string& id,
std::unique_ptr<MediaSessionNotificationItem> item,
mojo::Remote<media_session::mojom::MediaController> controller)
: owner_(owner), id_(id), item_(std::move(item)) {
DCHECK(owner_);
DCHECK(item_);
SetController(std::move(controller));
}
MediaSessionItemProducer::Session::~Session() {
// If we've been marked inactive, then we've already recorded inactivity as
// the dismiss reason.
if (is_marked_inactive_)
return;
RecordDismissReason(dismiss_reason_.value_or(
GlobalMediaControlsDismissReason::kMediaSessionStopped));
}
void MediaSessionItemProducer::Session::MediaSessionInfoChanged(
media_session::mojom::MediaSessionInfoPtr session_info) {
is_playing_ =
session_info && session_info->playback_state ==
media_session::mojom::MediaPlaybackState::kPlaying;
// If we've started playing, we don't want the inactive timer to be running.
if (is_playing_) {
if (inactive_timer_.IsRunning() || is_marked_inactive_) {
MarkActiveIfNecessary();
RecordInteractionDelayAfterPause();
inactive_timer_.Stop();
}
return;
}
// If the timer is already running, we don't need to do anything.
if (inactive_timer_.IsRunning())
return;
last_interaction_time_ = base::TimeTicks::Now();
StartInactiveTimer();
}
void MediaSessionItemProducer::Session::MediaSessionActionsChanged(
const std::vector<media_session::mojom::MediaSessionAction>& actions) {
bool is_audio_device_switching_supported =
base::ranges::find(
actions,
media_session::mojom::MediaSessionAction::kSwitchAudioDevice) !=
actions.end();
if (is_audio_device_switching_supported !=
is_audio_device_switching_supported_) {
is_audio_device_switching_supported_ = is_audio_device_switching_supported;
is_audio_device_switching_supported_callback_list_.Notify(
is_audio_device_switching_supported_);
}
}
void MediaSessionItemProducer::Session::MediaSessionPositionChanged(
const absl::optional<media_session::MediaPosition>& position) {
OnSessionInteractedWith();
}
void MediaSessionItemProducer::Session::OnRequestIdReleased() {
// The request ID is released when the tab is closed.
set_dismiss_reason(GlobalMediaControlsDismissReason::kTabClosed);
}
void MediaSessionItemProducer::Session::SetController(
mojo::Remote<media_session::mojom::MediaController> controller) {
if (controller.is_bound()) {
observer_receiver_.reset();
controller->AddObserver(observer_receiver_.BindNewPipeAndPassRemote());
controller_ = std::move(controller);
}
}
void MediaSessionItemProducer::Session::set_dismiss_reason(
GlobalMediaControlsDismissReason reason) {
DCHECK(!dismiss_reason_.has_value());
dismiss_reason_ = reason;
}
void MediaSessionItemProducer::Session::OnSessionInteractedWith() {
// If we're not currently tracking inactive time, then no action is needed.
if (!inactive_timer_.IsRunning() && !is_marked_inactive_)
return;
MarkActiveIfNecessary();
RecordInteractionDelayAfterPause();
last_interaction_time_ = base::TimeTicks::Now();
// Otherwise, reset the timer.
inactive_timer_.Stop();
StartInactiveTimer();
}
bool MediaSessionItemProducer::Session::IsPlaying() const {
return is_playing_;
}
void MediaSessionItemProducer::Session::SetAudioSinkId(const std::string& id) {
controller_->SetAudioSinkId(id);
}
base::CallbackListSubscription MediaSessionItemProducer::Session::
RegisterIsAudioDeviceSwitchingSupportedCallback(
base::RepeatingCallback<void(bool)> callback) {
callback.Run(is_audio_device_switching_supported_);
return is_audio_device_switching_supported_callback_list_.Add(
std::move(callback));
}
// static
void MediaSessionItemProducer::Session::RecordDismissReason(
GlobalMediaControlsDismissReason reason) {
base::UmaHistogramEnumeration("Media.GlobalMediaControls.DismissReason",
reason);
}
void MediaSessionItemProducer::Session::StartInactiveTimer() {
DCHECK(!inactive_timer_.IsRunning());
// Using |base::Unretained()| here is okay since |this| owns
// |inactive_timer_|.
// If the feature is disabled, the timer will run forever, in order for the
// rest of the code to continue running as expected.
inactive_timer_.Start(
FROM_HERE, GetAutoDismissTimerValue(),
base::BindOnce(&MediaSessionItemProducer::Session::OnInactiveTimerFired,
base::Unretained(this)));
}
void MediaSessionItemProducer::Session::OnInactiveTimerFired() {
// If the session has been paused and inactive for long enough, then mark it
// as inactive.
is_marked_inactive_ = true;
RecordDismissReason(GlobalMediaControlsDismissReason::kInactiveTimeout);
owner_->OnSessionBecameInactive(id_);
}
void MediaSessionItemProducer::Session::RecordInteractionDelayAfterPause() {
base::TimeDelta time_since_last_interaction =
base::TimeTicks::Now() - last_interaction_time_;
base::UmaHistogramCustomTimes(
"Media.GlobalMediaControls.InteractionDelayAfterPause",
time_since_last_interaction, base::Minutes(1), base::Days(1), 100);
}
void MediaSessionItemProducer::Session::MarkActiveIfNecessary() {
if (!is_marked_inactive_)
return;
is_marked_inactive_ = false;
owner_->OnSessionBecameActive(id_);
}
MediaSessionItemProducer::MediaSessionItemProducer(
mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote,
mojo::Remote<media_session::mojom::MediaControllerManager>
controller_manager_remote,
MediaItemManager* item_manager,
absl::optional<base::UnguessableToken> source_id)
: audio_focus_remote_(std::move(audio_focus_remote)),
controller_manager_remote_(std::move(controller_manager_remote)),
item_manager_(item_manager),
item_ui_observer_set_(this) {
if (source_id.has_value()) {
audio_focus_remote_->AddSourceObserver(
*source_id, audio_focus_observer_receiver_.BindNewPipeAndPassRemote());
audio_focus_remote_->GetSourceFocusRequests(
*source_id,
base::BindOnce(&MediaSessionItemProducer::OnReceivedAudioFocusRequests,
weak_ptr_factory_.GetWeakPtr()));
} else {
audio_focus_remote_->AddObserver(
audio_focus_observer_receiver_.BindNewPipeAndPassRemote());
audio_focus_remote_->GetFocusRequests(
base::BindOnce(&MediaSessionItemProducer::OnReceivedAudioFocusRequests,
weak_ptr_factory_.GetWeakPtr()));
}
}
MediaSessionItemProducer::~MediaSessionItemProducer() = default;
base::WeakPtr<media_message_center::MediaNotificationItem>
MediaSessionItemProducer::GetMediaItem(const std::string& id) {
auto it = sessions_.find(id);
return it == sessions_.end() ? nullptr : it->second.item()->GetWeakPtr();
}
std::set<std::string> MediaSessionItemProducer::GetActiveControllableItemIds() {
return active_controllable_session_ids_;
}
bool MediaSessionItemProducer::HasFrozenItems() {
return !frozen_session_ids_.empty();
}
void MediaSessionItemProducer::OnFocusGained(
media_session::mojom::AudioFocusRequestStatePtr session) {
const std::string id = session->request_id->ToString();
// If we have an existing unfrozen item then this is a duplicate call and
// we should ignore it.
auto it = sessions_.find(id);
if (it != sessions_.end() && !it->second.item()->frozen())
return;
mojo::Remote<media_session::mojom::MediaController> item_controller;
mojo::Remote<media_session::mojom::MediaController> session_controller;
controller_manager_remote_->CreateMediaControllerForSession(
item_controller.BindNewPipeAndPassReceiver(), *session->request_id);
controller_manager_remote_->CreateMediaControllerForSession(
session_controller.BindNewPipeAndPassReceiver(), *session->request_id);
if (it != sessions_.end()) {
// If the notification was previously frozen then we should reset the
// controller because the mojo pipe would have been reset.
it->second.SetController(std::move(session_controller));
it->second.item()->SetController(std::move(item_controller),
std::move(session->session_info));
} else {
sessions_.emplace(
std::piecewise_construct, std::forward_as_tuple(id),
std::forward_as_tuple(
this, id,
std::make_unique<MediaSessionNotificationItem>(
this, id, session->source_name.value_or(std::string()),
std::move(item_controller), std::move(session->session_info)),
std::move(session_controller)));
for (auto& observer : observers_)
observer.OnMediaSessionItemCreated(id);
}
}
void MediaSessionItemProducer::OnFocusLost(
media_session::mojom::AudioFocusRequestStatePtr session) {
const std::string id = session->request_id->ToString();
auto it = sessions_.find(id);
if (it == sessions_.end())
return;
// If we're not currently showing this item, then we can just remove it.
if (!base::Contains(active_controllable_session_ids_, id) &&
!base::Contains(frozen_session_ids_, id)) {
RemoveItem(id);
return;
}
// Otherwise, freeze it in case it regains focus quickly.
it->second.item()->Freeze(base::BindOnce(
&MediaSessionItemProducer::OnItemUnfrozen, base::Unretained(this), id));
active_controllable_session_ids_.erase(id);
frozen_session_ids_.insert(id);
item_manager_->OnItemsChanged();
}
void MediaSessionItemProducer::OnRequestIdReleased(
const base::UnguessableToken& request_id) {
const std::string id = request_id.ToString();
auto it = sessions_.find(id);
if (it == sessions_.end())
return;
// When the tab is closed, just remove the item instead of freezing it.
it->second.OnRequestIdReleased();
RemoveItem(id);
}
void MediaSessionItemProducer::OnMediaItemUIClicked(const std::string& id) {
auto it = sessions_.find(id);
if (it == sessions_.end())
return;
it->second.OnSessionInteractedWith();
base::UmaHistogramEnumeration("Media.Notification.Click",
MediaNotificationClickSource::kMedia);
it->second.item()->Raise();
}
void MediaSessionItemProducer::OnMediaItemUIDismissed(const std::string& id) {
Session* session = GetSession(id);
if (!session) {
return;
}
session->set_dismiss_reason(
GlobalMediaControlsDismissReason::kUserDismissedNotification);
session->item()->Dismiss();
}
void MediaSessionItemProducer::AddObserver(
MediaSessionItemProducerObserver* observer) {
observers_.AddObserver(observer);
}
void MediaSessionItemProducer::RemoveObserver(
MediaSessionItemProducerObserver* observer) {
observers_.RemoveObserver(observer);
}
void MediaSessionItemProducer::OnItemShown(const std::string& id,
MediaItemUI* item_ui) {
if (item_ui)
item_ui_observer_set_.Observe(id, item_ui);
}
bool MediaSessionItemProducer::IsItemActivelyPlaying(const std::string& id) {
const auto it = sessions_.find(id);
return it == sessions_.end() ? false : it->second.IsPlaying();
}
void MediaSessionItemProducer::HideItem(const std::string& id) {
active_controllable_session_ids_.erase(id);
frozen_session_ids_.erase(id);
item_manager_->HideItem(id);
}
void MediaSessionItemProducer::RemoveItem(const std::string& id) {
active_controllable_session_ids_.erase(id);
frozen_session_ids_.erase(id);
inactive_session_ids_.erase(id);
for (auto& observer : observers_)
observer.OnMediaSessionItemDestroyed(id);
item_manager_->HideItem(id);
sessions_.erase(id);
}
void MediaSessionItemProducer::ActivateItem(const std::string& id) {
DCHECK(HasSession(id));
if (base::Contains(inactive_session_ids_, id))
return;
active_controllable_session_ids_.insert(id);
item_manager_->ShowItem(id);
}
bool MediaSessionItemProducer::HasSession(const std::string& id) const {
return base::Contains(sessions_, id);
}
void MediaSessionItemProducer::LogMediaSessionActionButtonPressed(
const std::string& id,
media_session::mojom::MediaSessionAction action) {
for (auto& observer : observers_)
observer.OnMediaSessionActionButtonPressed(id, action);
}
void MediaSessionItemProducer::SetAudioSinkId(const std::string& id,
const std::string& sink_id) {
auto it = sessions_.find(id);
DCHECK(it != sessions_.end());
it->second.SetAudioSinkId(sink_id);
}
base::CallbackListSubscription
MediaSessionItemProducer::RegisterIsAudioOutputDeviceSwitchingSupportedCallback(
const std::string& id,
base::RepeatingCallback<void(bool)> callback) {
auto it = sessions_.find(id);
DCHECK(it != sessions_.end());
return it->second.RegisterIsAudioDeviceSwitchingSupportedCallback(
std::move(callback));
}
MediaSessionItemProducer::Session* MediaSessionItemProducer::GetSession(
const std::string& id) {
auto it = sessions_.find(id);
return it == sessions_.end() ? nullptr : &it->second;
}
void MediaSessionItemProducer::OnSessionBecameActive(const std::string& id) {
DCHECK(base::Contains(inactive_session_ids_, id));
auto it = sessions_.find(id);
DCHECK(it != sessions_.end());
inactive_session_ids_.erase(id);
if (it->second.item()->frozen()) {
frozen_session_ids_.insert(id);
} else {
active_controllable_session_ids_.insert(id);
}
item_manager_->ShowItem(id);
}
void MediaSessionItemProducer::OnSessionBecameInactive(const std::string& id) {
// If this session is already marked inactive, then there's nothing to do.
if (base::Contains(inactive_session_ids_, id))
return;
inactive_session_ids_.insert(id);
// Mark hidden on our end.
HideItem(id);
// Let the service know that the item is hidden.
item_manager_->HideItem(id);
}
void MediaSessionItemProducer::HideMediaDialog() {
item_manager_->HideDialog();
}
void MediaSessionItemProducer::OnReceivedAudioFocusRequests(
std::vector<media_session::mojom::AudioFocusRequestStatePtr> sessions) {
for (auto& session : sessions)
OnFocusGained(std::move(session));
}
void MediaSessionItemProducer::OnItemUnfrozen(const std::string& id) {
frozen_session_ids_.erase(id);
active_controllable_session_ids_.insert(id);
item_manager_->OnItemsChanged();
}
} // namespace global_media_controls
| 33.400415 | 89 | 0.744208 | zealoussnow |
6e1bfe314c1a6b3c6c098d2846ab7c1476252146 | 236 | hpp | C++ | wfc/logger.hpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | 1 | 2018-10-18T10:15:53.000Z | 2018-10-18T10:15:53.000Z | wfc/logger.hpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | 7 | 2019-12-04T23:36:03.000Z | 2021-04-21T12:37:07.000Z | wfc/logger.hpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | null | null | null | //
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2015
//
// Copyright: See COPYING file that comes with this distribution
//
#pragma once
#include <wfc/logger/logger.hpp>
namespace wfc
{
using ::wlog::only_for_log;
}
| 15.733333 | 64 | 0.707627 | mambaru |
6e1e22d26093e587114dd69b7c5c796891fac952 | 3,352 | cpp | C++ | hangman.cpp | AfaanBilal/hangman | f1b50e48039a26f25d2046dd8f209b3117e58c35 | [
"MIT"
] | 1 | 2020-01-04T19:38:26.000Z | 2020-01-04T19:38:26.000Z | hangman.cpp | AfaanBilal/hangman | f1b50e48039a26f25d2046dd8f209b3117e58c35 | [
"MIT"
] | null | null | null | hangman.cpp | AfaanBilal/hangman | f1b50e48039a26f25d2046dd8f209b3117e58c35 | [
"MIT"
] | null | null | null | /*
Hangman
(c) Afaan Bilal
Play hangman!
*/
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <fstream>
using namespace std;
const int numWords = 50;
string wordlist[numWords];
string input;
size_t f;
int sel = 0;
int maxTries = 10;
int tries = 0;
void cls();
void display();
bool checkIfWon();
int main()
{
ifstream file("hangman.txt");
if(file.is_open())
{
for(int i = 0; i < numWords; ++i)
{
file >> wordlist[i];
}
}
srand(time(NULL));
sel = rand() % numWords;
char c = ' ';
display();
cout << endl << "\tEnter an alphabet: ";
c = _getch();
while (c != '.')
{
c = toupper(c);
f = input.find(c);
if (f == string::npos)
{
input.push_back(c);
if (wordlist[sel].find(c) == string::npos)
{
tries++;
if (tries >= maxTries)
{
display();
cout << endl << "\t\tSorry! You have lost!" << endl << endl;
cout << "\t\tThe word was " << wordlist[sel] << endl << endl;
break;
}
}
display();
if (checkIfWon())
{
cout << endl << "\t\tCongratulations! You have won!" << endl << endl;
break;
}
}
else
{
cout << endl << "\tAlphabet already entered." << endl;
}
cout << endl << "\tEnter an alphabet: ";
c = _getch();
}
}
void cls()
{
system("@cls || clear");
}
void drawHangman()
{
cout << endl;
switch (tries)
{
case 10:
cout << "\t\t YOU KILLED ME!" << endl;
cout << "\t\t\t _________ " << endl;
case 9: cout << "\t\t\t | |" << endl;
case 8: cout << "\t\t\t --- |" << endl;
case 7: cout << "\t\t\t | | |" << endl;
case 6: cout << "\t\t\t --- |" << endl;
case 5: cout << "\t\t\t ----|---- |" << endl;
case 4: cout << "\t\t\t | |" << endl;
case 3: cout << "\t\t\t | |" << endl;
case 2: cout << "\t\t\t --- |" << endl;
case 1: cout << "\t\t\t / \\ |" << endl;
cout << "\t\t\t |" << endl;
cout << "\t\t\t____________|" << endl;
}
cout << endl << endl;
}
void display()
{
cls();
cout << endl << "\t\t\t" << "HANGMAN" << endl << endl;
cout << "\thttps://github.com/AfaanBilal/hangman" << endl << endl;
drawHangman();
cout << "\tPress '.' to exit." << endl;
cout << "\tTries left: " << (maxTries - tries) << endl << endl;
cout << "\t\t ";
for (int i = 0; i < wordlist[sel].length(); i++)
{
f = input.find(wordlist[sel][i]);
if (f == string::npos)
cout << "_" << " ";
else
cout << wordlist[sel][i] << " ";
}
cout << endl;
}
bool checkIfWon()
{
for (int i = 0; i < wordlist[sel].length(); i++)
{
if (input.find(wordlist[sel][i]) == string::npos)
return false;
}
return true;
}
| 22.346667 | 85 | 0.406026 | AfaanBilal |
6e24d37d9c5ac8ee13ad5e9a1b113c7fd9b0eedb | 8,285 | hxx | C++ | libbuild2/script/parser.hxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 422 | 2018-05-30T12:00:00.000Z | 2022-03-29T07:29:56.000Z | libbuild2/script/parser.hxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 183 | 2018-07-02T20:38:30.000Z | 2022-03-31T09:54:35.000Z | libbuild2/script/parser.hxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 14 | 2019-01-09T12:34:02.000Z | 2021-03-16T09:10:53.000Z | // file : libbuild2/script/parser.hxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#ifndef LIBBUILD2_SCRIPT_PARSER_HXX
#define LIBBUILD2_SCRIPT_PARSER_HXX
#include <libbuild2/types.hxx>
#include <libbuild2/forward.hxx>
#include <libbuild2/utility.hxx>
#include <libbuild2/parser.hxx>
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/script/token.hxx>
#include <libbuild2/script/lexer.hxx> // redirect_aliases
#include <libbuild2/script/script.hxx>
namespace build2
{
namespace script
{
class lexer;
struct lexer_mode;
class parser: protected build2::parser
{
public:
parser (context& c, bool relex): build2::parser (c), relex_ (relex) {}
// Helpers.
//
// Parse attribute string and perform attribute-guided assignment.
// Issue diagnostics and throw failed in case of an error.
//
void
apply_value_attributes (const variable*, // Optional.
value& lhs,
value&& rhs,
const string& attributes,
token_type assign_kind,
const path_name&); // For diagnostics.
using build2::parser::apply_value_attributes;
// Commonly used parsing functions. Issue diagnostics and throw failed
// in case of an error.
//
// Usually (but not always) parse functions receive the token/type
// from which it should start consuming and in return the token/type
// should contain the first token that has not been consumed.
//
// Functions that are called parse_*() rather than pre_parse_*() can be
// used for both stages.
//
protected:
value
parse_variable_line (token&, token_type&);
// Ordered sequence of here-document redirects that we can expect to
// see after the command line.
//
struct here_redirect
{
size_t expr; // Index in command_expr.
size_t pipe; // Index in command_pipe.
int fd; // Redirect fd (0 - in, 1 - out, 2 - err).
};
struct here_doc
{
// Redirects that share here_doc. Most of the time we will have no
// more than 2 (2 - for the roundtrip cases). Doesn't refer overridden
// redirects and thus can be empty.
//
small_vector<here_redirect, 2> redirects;
string end;
bool literal; // Literal (single-quote).
string modifiers;
// Regex introducer ('\0' if not a regex, so can be used as bool).
//
char regex;
// Regex global flags. Meaningful if regex != '\0'.
//
string regex_flags;
};
using here_docs = vector<here_doc>;
pair<command_expr, here_docs>
parse_command_expr (token&, token_type&, const redirect_aliases&);
command_exit
parse_command_exit (token&, token_type&);
void
parse_here_documents (token&, token_type&,
pair<command_expr, here_docs>&);
struct parsed_doc
{
union
{
string str; // Here-document literal.
regex_lines regex; // Here-document regex.
};
bool re; // True if regex.
uint64_t end_line; // Here-document end marker location.
uint64_t end_column;
parsed_doc (string, uint64_t line, uint64_t column);
parsed_doc (regex_lines&&, uint64_t line, uint64_t column);
parsed_doc (parsed_doc&&); // Note: move constuctible-only type.
~parsed_doc ();
};
parsed_doc
parse_here_document (token&, token_type&,
const string&,
const string& mode,
char re_intro); // '\0' if not a regex.
// Start pre-parsing a script line returning its type, detected based on
// the first two tokens. Use the specified lexer mode to peek the second
// token.
//
line_type
pre_parse_line_start (token&, token_type&, lexer_mode);
// Parse the env pseudo-builtin arguments up to the program name. Return
// the program execution timeout, CWD, the list of the variables that
// should be unset ("name") and/or set ("name=value") in the command
// environment, and the token/type that starts the program name. Note
// that the variable unsets come first, if present.
//
struct parsed_env
{
optional<duration> timeout;
optional<dir_path> cwd;
environment_vars variables;
};
parsed_env
parse_env_builtin (token&, token_type&);
// Execute.
//
protected:
// Return false if the execution of the script should be terminated with
// the success status (e.g., as a result of encountering the exit
// builtin). For unsuccessful termination the failed exception is thrown.
//
using exec_set_function = void (const variable&,
token&, token_type&,
const location&);
using exec_cmd_function = void (token&, token_type&,
size_t li,
bool single,
const location&);
using exec_if_function = bool (token&, token_type&,
size_t li,
const location&);
// If a parser implementation doesn't pre-enter variables into a pool
// during the pre-parsing phase, then they are entered during the
// execution phase and so the variable pool must be provided. Note that
// in this case the variable pool insertions are not MT-safe.
//
bool
exec_lines (lines::const_iterator b, lines::const_iterator e,
const function<exec_set_function>&,
const function<exec_cmd_function>&,
const function<exec_if_function>&,
size_t& li,
variable_pool* = nullptr);
// Customization hooks.
//
protected:
// Parse the command's leading name chunk. The argument first is true if
// this is the first command in the line. The argument env is true if
// the command is executed via the env pseudo-builtin.
//
// During the execution phase try to parse and translate the leading
// names into the process path and return nullopt if choose not to do
// so, leaving it to the parser to handle. Also return in the last
// two arguments uninterpreted names, if any.
//
// The default implementation always returns nullopt. The derived parser
// can provide an override that can, for example, handle process path
// values, executable targets, etc.
//
// Note that normally it makes sense to leave simple unpaired names for
// the parser to handle, unless there is a good reason not to (e.g.,
// it's a special builtin or some such). Such names may contain
// something that requires re-lexing, for example `foo|bar`, which won't
// be easy to translate but which are handled by the parser.
//
// During the pre-parsing phase the returned process path and names
// (that must still be parsed) are discarded. The main purpose of the
// call is to allow implementations to perform static script analysis,
// recognize and execute certain directives, or some such.
//
virtual optional<process_path>
parse_program (token&, token_type&,
bool first, bool env,
names&, parse_names_result&);
// Set lexer pointers for both the current and the base classes.
//
protected:
void
set_lexer (lexer*);
// Number of quoted tokens since last reset. Note that this includes the
// peeked token, if any.
//
protected:
size_t
quoted () const;
void
reset_quoted (token& current);
size_t replay_quoted_;
protected:
bool relex_;
lexer* lexer_ = nullptr;
};
}
}
#endif // LIBBUILD2_SCRIPT_PARSER_HXX
| 34.665272 | 79 | 0.595413 | build2 |
6e25735d9d1090bac9cc52f7c1ee1d1619a595ac | 834 | hpp | C++ | src/FeatureExtraction.hpp | Trojahn/BackShotCoSS | cf0b996720612ab4bb1b579701f50e8cdd14f2c3 | [
"MIT"
] | 1 | 2021-04-01T23:00:10.000Z | 2021-04-01T23:00:10.000Z | src/FeatureExtraction.hpp | Trojahn/BackShotCoSS | cf0b996720612ab4bb1b579701f50e8cdd14f2c3 | [
"MIT"
] | null | null | null | src/FeatureExtraction.hpp | Trojahn/BackShotCoSS | cf0b996720612ab4bb1b579701f50e8cdd14f2c3 | [
"MIT"
] | 2 | 2016-08-27T17:29:27.000Z | 2018-11-05T02:10:45.000Z | #ifndef FEATUREEXTRACTION_H
#define FEATUREEXTRACTION_H
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <iomanip>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cmath>
#include <thread>
#include <mutex>
#include "Utils.hpp"
#include "Shot.hpp"
#include "Parameters.hpp"
using namespace std;
class FeatureExtraction {
private:
void processOpticalFlow(vector<Mat> frames, pair<int,double> &opticalFlow);
vector<pair<int,int>> keyframes;
vector<pair<int,int>> shots;
string videoPath;
public:
FeatureExtraction(vector< pair<int,int> > keyframes, vector<pair<int,int>> shots, string videoPath);
vector<Shot> extractFeatures(bool enableOpticalFlow);
};
#endif | 21.947368 | 102 | 0.747002 | Trojahn |
6e294a0debd6730c77212cc53db0ebf86335b103 | 2,178 | hpp | C++ | src/include/randest/ks_test.hpp | renegat96/randest | 29449ff61398526cc1b88a1f003ed8fddef14693 | [
"MIT"
] | null | null | null | src/include/randest/ks_test.hpp | renegat96/randest | 29449ff61398526cc1b88a1f003ed8fddef14693 | [
"MIT"
] | null | null | null | src/include/randest/ks_test.hpp | renegat96/randest | 29449ff61398526cc1b88a1f003ed8fddef14693 | [
"MIT"
] | null | null | null | /*
* Kolmogorov-Smirnov goodness-of-fit test.
* H_0 the data follow a specified distribution
* H_a the data do not follow the specified distribution
* D = max (F(Y_i) -
* */
#pragma once
#include <functional>
#include <randest/test.hpp>
#include <randest/data_provider.hpp>
#include <randest/data_sort.hpp>
namespace randest {
template<typename OutputT = long double>
struct NormalDistribution {
long double operator()(const OutputT &x) {
return static_cast<long double>(x);
}
};
template<typename OutputT = long double,
typename Compare = std::less<OutputT>,
typename CDF = std::function<long double(OutputT)>>
class ks_test : public test {
private:
bool ran;
randest::data_provider<OutputT> *data;
long double ks_statistic;
/*
ks_test();
*/
ks_test();
CDF cdf;
public:
/*
ks_test(data_provider<OutputT> *data, CDF cdf = NormalDistribution<OutputT>());
void run();
long double getPerformance();
*/
ks_test(data_provider<OutputT> *data, CDF cdf = NormalDistribution<OutputT>()) {
this->data = data;
this->ks_statistic = 0;
this->cdf = cdf;
}
void run() {
::randest::data_sort<OutputT> sorted = data_sort<OutputT, Compare>(data);
ks_statistic = 0;
size_t size = sorted.size();
for (size_t i = 0; i < size; ++i) {
long double fx = static_cast<long double>(sorted.count_smaller(sorted[i])) / sorted.size();
long double observation = cdf(sorted[i]);
long double candidate = fabsl(observation - fx);
//ks_statistic = std::max(ks_statistic, candidate);
if (ks_statistic < candidate) {
ks_statistic = candidate;
}
}
ran = true;
}
long double getPerformance() {
if (!this->ran) throw "trying to get the result from a test that has not been ran";
return ks_statistic;
}
};
}
| 27.923077 | 107 | 0.556933 | renegat96 |
6e2c5d22fbd5e41daabc748c5eb43e2e1c6679a6 | 2,310 | cpp | C++ | backends/graphs/graphs.cpp | srivani/p4c | 6891448af6834c0798350f4b2a7c54ad3532148e | [
"Apache-2.0"
] | 487 | 2016-12-22T03:33:27.000Z | 2022-03-29T06:36:45.000Z | backends/graphs/graphs.cpp | srivani/p4c | 6891448af6834c0798350f4b2a7c54ad3532148e | [
"Apache-2.0"
] | 2,114 | 2016-12-18T11:36:27.000Z | 2022-03-31T22:33:23.000Z | backends/graphs/graphs.cpp | srivani/p4c | 6891448af6834c0798350f4b2a7c54ad3532148e | [
"Apache-2.0"
] | 456 | 2016-12-20T14:01:11.000Z | 2022-03-30T19:26:05.000Z | /*
Copyright 2013-present Barefoot Networks, Inc.
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/log.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/gc.h"
#include "lib/crash.h"
#include "lib/nullstream.h"
#include "graphs.h"
namespace graphs {
Graphs::vertex_t Graphs::add_vertex(const cstring &name, VertexType type) {
auto v = boost::add_vertex(*g);
boost::put(&Vertex::name, *g, v, name);
boost::put(&Vertex::type, *g, v, type);
return g->local_to_global(v);
}
void Graphs::add_edge(const vertex_t &from, const vertex_t &to, const cstring &name) {
auto ep = boost::add_edge(from, to, g->root());
boost::put(boost::edge_name, g->root(), ep.first, name);
}
boost::optional<Graphs::vertex_t> Graphs::merge_other_statements_into_vertex() {
if (statementsStack.empty()) return boost::none;
std::stringstream sstream;
if (statementsStack.size() == 1) {
statementsStack[0]->dbprint(sstream);
} else if (statementsStack.size() == 2) {
statementsStack[0]->dbprint(sstream);
sstream << "\n";
statementsStack[1]->dbprint(sstream);
} else {
statementsStack[0]->dbprint(sstream);
sstream << "\n...\n";
statementsStack.back()->dbprint(sstream);
}
auto v = add_vertex(cstring(sstream), VertexType::STATEMENTS);
for (auto parent : parents)
add_edge(parent.first, v, parent.second->label());
parents = {{v, new EdgeUnconditional()}};
statementsStack.clear();
return v;
}
Graphs::vertex_t Graphs::add_and_connect_vertex(const cstring &name, VertexType type) {
merge_other_statements_into_vertex();
auto v = add_vertex(name, type);
for (auto parent : parents)
add_edge(parent.first, v, parent.second->label());
return v;
}
} // namespace graphs
| 32.535211 | 87 | 0.687446 | srivani |
6e2f2e6c8b99fd0d6cfc507932509b3fe556e549 | 11,606 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8TextDecoder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8TextDecoder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8TextDecoder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8TextDecoder.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "bindings/v8/custom/V8ArrayBufferViewCustom.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/UseCounter.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(TextDecoder* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8TextDecoder::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::TextDecoder* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8TextDecoder::wrapperTypeInfo = { gin::kEmbedderBlink, V8TextDecoder::domTemplate, V8TextDecoder::derefObject, 0, 0, 0, V8TextDecoder::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, GarbageCollectedObject };
namespace TextDecoderV8Internal {
template <typename T> void V8_USE(T) { }
static void encodingAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
TextDecoder* impl = V8TextDecoder::toNative(holder);
v8SetReturnValueString(info, impl->encoding(), info.GetIsolate());
}
static void encodingAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TextDecoderV8Internal::encodingAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void fatalAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
TextDecoder* impl = V8TextDecoder::toNative(holder);
v8SetReturnValueBool(info, impl->fatal());
}
static void fatalAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TextDecoderV8Internal::fatalAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void ignoreBOMAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
TextDecoder* impl = V8TextDecoder::toNative(holder);
v8SetReturnValueBool(info, impl->ignoreBOM());
}
static void ignoreBOMAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TextDecoderV8Internal::ignoreBOMAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void decodeMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "decode", "TextDecoder", info.Holder(), info.GetIsolate());
TextDecoder* impl = V8TextDecoder::toNative(info.Holder());
ArrayBufferView* input;
Dictionary options;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (UNLIKELY(info.Length() <= 0)) {
String result = impl->decode(exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueString(info, result, info.GetIsolate());
return;
}
TONATIVE_VOID_INTERNAL(input, info[0]->IsArrayBufferView() ? V8ArrayBufferView::toNative(v8::Handle<v8::ArrayBufferView>::Cast(info[0])) : 0);
TONATIVE_VOID_INTERNAL(options, Dictionary(info[1], info.GetIsolate()));
if (!options.isUndefinedOrNull() && !options.isObject()) {
exceptionState.throwTypeError("parameter 2 ('options') is not an object.");
exceptionState.throwIfNeeded();
return;
}
}
String result = impl->decode(input, options, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueString(info, result, info.GetIsolate());
}
static void decodeMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
UseCounter::count(callingExecutionContext(info.GetIsolate()), UseCounter::TextDecoderDecode);
TextDecoderV8Internal::decodeMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TextDecoder", info.Holder(), isolate);
V8StringResource<> label;
Dictionary options;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TOSTRING_VOID_INTERNAL(label, argumentOrNull(info, 0));
TONATIVE_VOID_INTERNAL(options, Dictionary(info[1], info.GetIsolate()));
if (!options.isUndefinedOrNull() && !options.isObject()) {
exceptionState.throwTypeError("parameter 2 ('options') is not an object.");
exceptionState.throwIfNeeded();
return;
}
}
RawPtr<TextDecoder> impl = TextDecoder::create(label, options, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8::Handle<v8::Object> wrapper = info.Holder();
V8DOMWrapper::associateObjectWithWrapper<V8TextDecoder>(impl.release(), &V8TextDecoder::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
v8SetReturnValue(info, wrapper);
}
} // namespace TextDecoderV8Internal
static const V8DOMConfiguration::AttributeConfiguration V8TextDecoderAttributes[] = {
{"encoding", TextDecoderV8Internal::encodingAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"fatal", TextDecoderV8Internal::fatalAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"ignoreBOM", TextDecoderV8Internal::ignoreBOMAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static const V8DOMConfiguration::MethodConfiguration V8TextDecoderMethods[] = {
{"decode", TextDecoderV8Internal::decodeMethodCallback, 0, 0},
};
void V8TextDecoder::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "DOMConstructor");
UseCounter::count(callingExecutionContext(info.GetIsolate()), UseCounter::TextDecoderConstructor);
if (!info.IsConstructCall()) {
throwTypeError(ExceptionMessages::constructorNotCallableAsFunction("TextDecoder"), info.GetIsolate());
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
TextDecoderV8Internal::constructor(info);
}
static void configureV8TextDecoderTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
if (!RuntimeEnabledFeatures::encodingAPIEnabled())
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "", v8::Local<v8::FunctionTemplate>(), V8TextDecoder::internalFieldCount, 0, 0, 0, 0, 0, 0, isolate);
else
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "TextDecoder", v8::Local<v8::FunctionTemplate>(), V8TextDecoder::internalFieldCount,
V8TextDecoderAttributes, WTF_ARRAY_LENGTH(V8TextDecoderAttributes),
0, 0,
V8TextDecoderMethods, WTF_ARRAY_LENGTH(V8TextDecoderMethods),
isolate);
functionTemplate->SetCallHandler(V8TextDecoder::constructorCallback);
functionTemplate->SetLength(0);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8TextDecoder::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8TextDecoderTemplate);
}
bool V8TextDecoder::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8TextDecoder::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TextDecoder* V8TextDecoder::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
v8::Handle<v8::Object> wrap(TextDecoder* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8TextDecoder>(impl, isolate));
return V8TextDecoder::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8TextDecoder::createWrapper(RawPtr<TextDecoder> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8TextDecoder>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8TextDecoder>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
return wrapper;
}
void V8TextDecoder::derefObject(void* object)
{
}
template<>
v8::Handle<v8::Value> toV8NoInline(TextDecoder* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 43.30597 | 247 | 0.740048 | jingcao80 |
6e305f319f9aba9b5e4c1ccdb60f56d5fe3f74bc | 1,392 | cpp | C++ | Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Maximum Product of Word Lengths
====================================
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
Constraints:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] consists only of lowercase English letters.
*/
class Solution
{
public:
int maxProduct(vector<string> &words)
{
vector<int> masks;
for (auto &i : words)
{
int mask = 0;
for (auto &e : i)
// agr phele se bit set hai toh mt krdo vapas, galat hojayega
if (!(mask & (1 << (e - 'a'))))
mask += (1 << (e - 'a'));
masks.push_back(mask);
cout << mask << " ";
}
int ans = 0;
for (int i = 0; i < words.size(); ++i)
{
for (int j = i + 1; j < words.size(); ++j)
{
if ((masks[i] & masks[j]) == 0)
{
ans = max(ans, (int)(words[i].size() * words[j].size()));
}
}
}
return ans;
}
}; | 23.2 | 176 | 0.538793 | Akshad7829 |
6e308dcf04b947a9dbb89bf9c797b0dd47bc7be6 | 533 | hpp | C++ | src/translate_c.hpp | frmdstryr/zig | f3a9ec33453928830cf555f694c4c18c65a077a1 | [
"MIT"
] | null | null | null | src/translate_c.hpp | frmdstryr/zig | f3a9ec33453928830cf555f694c4c18c65a077a1 | [
"MIT"
] | null | null | null | src/translate_c.hpp | frmdstryr/zig | f3a9ec33453928830cf555f694c4c18c65a077a1 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of zig, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#ifndef ZIG_PARSEC_HPP
#define ZIG_PARSEC_HPP
#include "all_types.hpp"
enum TranslateMode {
TranslateModeImport,
TranslateModeTranslate,
};
Error parse_h_file(CodeGen *codegen, AstNode **out_root_node,
Stage2ErrorMsg **errors_ptr, size_t *errors_len,
const char **args_begin, const char **args_end,
TranslateMode mode, const char *resources_path);
#endif
| 21.32 | 61 | 0.718574 | frmdstryr |
6e3332bdbbaea73327935cfff16a970022137edb | 14,336 | hpp | C++ | include/generator/module_generator.hpp | pc2/FBLAS | c9655623897711758fcff98c741f556872ad3882 | [
"BSD-3-Clause"
] | null | null | null | include/generator/module_generator.hpp | pc2/FBLAS | c9655623897711758fcff98c741f556872ad3882 | [
"BSD-3-Clause"
] | null | null | null | include/generator/module_generator.hpp | pc2/FBLAS | c9655623897711758fcff98c741f556872ad3882 | [
"BSD-3-Clause"
] | null | null | null | /**
FBLAS: BLAS implementation for Intel FPGA
Copyright (c) 2019 ETH-Zurich. All rights reserved.
See LICENSE for license information.
Modules generator: modules code generator
*/
#ifndef MODULES_GENERATOR_HPP
#define MODULES_GENERATOR_HPP
#include <vector>
#include <map>
#include <functional>
#include <fstream>
#include <regex>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include "generator_routine.hpp"
#include "generator_helper.hpp"
#include "generator_commons.hpp"
/**
* @brief The FBlasGenerator class implements the FBlas code generator.
* Given a set of (parsed) routines it will generate the source code suitable for compilation
*/
class ModuleGenerator {
public:
ModuleGenerator()
{
fillGenerationFunctions();
}
void GenerateCode(const std::vector<GeneratorRoutine> &routines, const std::vector<GeneratorHelper> &helpers,std::string output_dir)
{
if(routines.size()==0)
{
std::cout << RED "No routines to generate" RESET <<std::endl;
return;
}
//dobbiamo avere un insieme di channel descriptors
for(int i=0; i< routines.size();i++)
{
std::cout << "Generating: "<<routines[i].getUserName()<<std::endl;
//For each routine the generated code will looks like:
//1) Defines (names, precision, channels, width, ...)
//2) Main computational kernel
//3) Helper kernels (read/write from /to memory)
if(generation_functions_.find(routines[i].getBlasName())!=generation_functions_.end())
generation_functions_[routines[i].getBlasName()](routines[i],i,output_dir);
else
std::cout << "Generation function not present " << routines[i].getBlasName()<<std::endl;
}
for(int i=0;i<helpers.size();i++)
{
std::cout << "Generating: "<<helpers[i].getUserName()<<std::endl;
if(generation_helpers_.find(helpers[i].getType())!=generation_helpers_.end())
generation_helpers_[helpers[i].getType()](helpers[i],i,output_dir);
else
std::cout << "Helper generation function not present " << helpers[i].getType()<<std::endl;
}
}
private:
//Level 1
static void Level1Dot(const GeneratorRoutine &r, unsigned int id, std::string output_folder);
static void Level1Axpy(const GeneratorRoutine &r, unsigned int id, std::string output_folder);
//Level2
static void Level2Gemv(const GeneratorRoutine &r, unsigned int id, std::string output_folder);
static void Level2Ger(const GeneratorRoutine &r, unsigned int id, std::string output_folder);
//Helpers
static void ReadVectorX(const GeneratorHelper &h, unsigned int id, std::string output_folder);
static void ReadVectorY(const GeneratorHelper &h, unsigned int id, std::string output_folder);
static void WriteScalar(const GeneratorHelper &h, unsigned int id, std::string output_folder);
static void WriteVector(const GeneratorHelper &h, unsigned int id, std::string output_folder);
static void ReadMatrix(const GeneratorHelper &h, unsigned int id, std::string output_folder);
static void WriteMatrix(const GeneratorHelper &h, unsigned int id, std::string output_folder);
//Generation functions
void fillGenerationFunctions()
{
// parsing_functions_.insert(std::make_pair("sdot",BlasParser::Level1Sdot));
generation_functions_["axpy"]=ModuleGenerator::Level1Axpy;
generation_functions_["dot"]=ModuleGenerator::Level1Dot;
//level 2
generation_functions_["gemv"]=ModuleGenerator::Level2Gemv;
generation_functions_["ger"]=ModuleGenerator::Level2Ger;
//helpers
generation_helpers_["read vector x"]=ModuleGenerator::ReadVectorX;
generation_helpers_["read vector"]=ModuleGenerator::ReadVectorX; //alias for simplicity
generation_helpers_["read vector y"]=ModuleGenerator::ReadVectorY;
generation_helpers_["write vector"]=ModuleGenerator::WriteVector;
generation_helpers_["write scalar"]=ModuleGenerator::WriteScalar;
generation_helpers_["read matrix"]=ModuleGenerator::ReadMatrix;
generation_helpers_["write matrix"]=ModuleGenerator::WriteMatrix;
}
/**
* @brief addCommons starts to fill up the generating file and the routine genereated json item
* with characteristics that are common to all the routines (name, user_name, precision, width)
* @param blas_name
* @param r
* @param fout
*/
static void addCommons(const GeneratorRoutine &r,std::ofstream &fout)
{
if(r.isDoublePrecision())
fout << k_double_precision_define_ <<std::endl;
//width: how to setup this information depends on the type of routine
if(!r.has2DComputationalTile())
{
fout << k_width_define_;
unsigned int width=(r.getWidth()!=0)?r.getWidth():k_default_width_;
fout << width <<std::endl;
}
else
{
unsigned int width_x=(r.getWidthX()!=0)?r.getWidthX():k_default_2d_width_;
unsigned int width_y=(r.getWidthY()!=0)?r.getWidthY():k_default_2d_width_;
//Remember width_x are the computational tile cols, while width_y is the number of rows
fout << k_ctile_rows_define_;
fout << width_y <<std::endl;
fout << k_ctile_cols_define_;
fout << width_x <<std::endl;
}
}
/**
* @brief addTileN add the informations about the Tile Size referring to N
*
*/
static void addTileN(const GeneratorRoutine &r, std::ofstream &fout)
{
fout << k_tile_n_size_define_;
//use default tile size if tile size was not defined by the user
//or a multiple of the width if the default size is not a multiple
unsigned int size= (r.getTileNsize()!=0)? r.getTileNsize() : k_default_tiling_;
if(r.getWidth() != 0 && (size%r.getWidth() != 0 || size<r.getWidth()))
{
size = r.getWidth() * 4 ;
std::cout << "Tile N size for routine " << r.getUserName() << " was not a multiple of the widthor was smaller than width. Set at: "<<size<<std::endl;
}
fout << size <<std::endl;
}
/**
* @brief addTileM add the informations about the Tile Size referring to M
* to both the generating kernel and routine json definition
*/
static void addTileM(const GeneratorRoutine &r, std::ofstream &fout)
{
fout << k_tile_m_size_define_;
unsigned int size= (r.getTileMsize()!=0)? r.getTileMsize() : k_default_tiling_;
if(r.getWidth() != 0 && (size%r.getWidth() != 0 || size<r.getWidth()))
{
size = r.getWidth() * 4 ;
std::cout << "Tile M size for routine " << r.getUserName() << " was not a multiple of the width. Set at: "<<size<<std::endl;
}
fout << size <<std::endl;
}
/**
* @brief addDefineAndItem add a given define and a given item, both of them with a given string as value
*/
static void addDefineAndItem(std::string define_name, std::string value, std::ofstream &fout)
{
fout << define_name<<value<<std::endl;
}
/**
* @brief addDefineChannelInVectorX add the define for input channel vector X
*/
static void addDefineChannelInVectorX(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_x_define_ << channel_name<<std::endl;
}
/**
* @brief addDefineChannelInVectorY add the define for input channel vector Y to the generating opencl kernel
*/
static void addDefineChannelInVectorY(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_y_define_ << channel_name<<std::endl;
}
/**
* @brief addDefineChannelOutVector add define for channel out vector
*/
static void addDefineChannelOutVector(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_vector_out_define_ << channel_name<<std::endl;
}
/**
* @brief addDefineChannelOutScalar add define for channel out scalar
*/
static void addDefineChannelOutScalar(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_scalar_out_define_ << channel_name<<std::endl;
}
static void addDefineChannelOutMatrix(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_matrix_out_define_ << channel_name<<std::endl;
}
static void addDefineChannelInMatrixA(std::string channel_name, std::ofstream &fout)
{
fout << k_channel_matrix_A_define_ << channel_name<<std::endl;
}
/**
* @brief CopyHeader copies the header of the file till the placeholder is found. For modules
* we maintain the first block of comments since it contains useful information
* @param fin
* @param fout
* @return true if the placeholder have been found, false otherwise
*/
static bool CopyHeader(std::ifstream &fin, std::ofstream &fout)
{
const std::string kPlaceholder_start="//FBLAS_PARAMETERS_START";
const std::string kPlaceholder_end="//FBLAS_PARAMETERS_END";
bool first_comment_block_skipped=true;
std::string line;
fout << k_generated_file_header_<<std::endl;
while(std::getline(fin,line))
{
if(!first_comment_block_skipped)
{
if(line.find("/*")!=std::string::npos)
{
//skip till the comment is finished
while(std::getline(fin,line) && line.find("*/")== std::string::npos);
first_comment_block_skipped=true;
continue;
}
}
if(line.find(kPlaceholder_start)!= std::string::npos)
{
//skip the following lines up to placeholder end
while(std::getline(fin,line) && line.find(kPlaceholder_end)== std::string::npos);
if(fin.eof()) //error we reached the end of file
{
std::cerr<< "Placeholders not found " <<std::endl;
return false;
}
else
return true;
}
else
{
fout << line <<std::endl;
}
}
//if we reached this point, placeholder haven't been found
return false;
}
/**
* @brief CopyTillEndReplacing copies the content of fin from the current position. Properly replaces module signature
* @param fin
* @param fout
* @param isKernel
* @param name
*/
static void CopyTillEndReplacing(std::ifstream &fin, std::ofstream &fout, bool isKernel, std::string pattern, std::string name)
{
std::string line;
while(std::getline(fin,line))
{
if(line.find("__kernel")!=std::string::npos)
{
if(!isKernel)
line=std::regex_replace(line,std::regex("__kernel "),std::string(""));
line=std::regex_replace(line,std::regex(pattern),name);
}
fout << line<<std::endl;
}
fin.close();
}
/**
* @brief CopyTillEnd copy the content of fin form the current position to end into fout.
* Fin is closed
* @param fin
* @param fout
*/
static void CopyTillEnd(std::ifstream &fin, std::ofstream &fout)
{
std::string line;
while(std::getline(fin,line))
{
fout << line<<std::endl;
}
fin.close();
}
static void CopyTillEnd(std::string file,std::ofstream &fout)
{
std::ifstream fin(file);
if(!fin.is_open()){
std::cerr << "Error in opening skeleton file for "<< file <<std::endl;
return;
}
CopyTillEnd(fin,fout);
}
std::map<std::string, std::function<void(const GeneratorRoutine &r, unsigned int id, std::string)> > generation_functions_;
std::map<std::string, std::function<void(const GeneratorHelper &h, unsigned int id, std::string)> > generation_helpers_;
//definition of helper files
static const std::map<std::string, std::string> k_helper_files_;
static const std::string k_skeleton_folder_; //the root directory containing all the skeletons
static const std::string k_generated_file_header_; //indicate that this file has been automatically generated
//Macros defines
//computation parameters and channel names defines (macro)
static const std::string k_double_precision_define_;
static const std::string k_width_define_;
static const std::string k_ctile_rows_define_;
static const std::string k_ctile_cols_define_;
static const std::string k_tile_n_size_define_;
static const std::string k_tile_m_size_define_;
static const std::string k_mtile_size_define_;
static const std::string k_kernel_name_define_ ;
static const std::string k_channel_x_define_;
static const std::string k_channel_y_define_;
static const std::string k_channel_x_trans_define_;
static const std::string k_channel_y_trans_define_;
static const std::string k_channel_x_trsv_define_;
static const std::string k_channel_matrix_A_define_;
static const std::string k_channel_matrix_A2_define_;
static const std::string k_channel_matrix_B_define_;
static const std::string k_channel_matrix_B2_define_;
static const std::string k_channel_scalar_out_define_;
static const std::string k_channel_vector_out_define_;
static const std::string k_channel_vector_out_x_define_;
static const std::string k_channel_vector_out_y_define_;
static const std::string k_channel_matrix_out_define_;
static const std::string k_commons_define_;
static const std::string k_stratix_10_platform_define_;
static const std::string k_arria_10_platform_define_;
static const std::string k_incx_define_;
static const std::string k_incy_define_;
static const std::string k_incw_define_;
static const std::string k_channel_enable_define_;
};
#endif // MODULES_GENERATOR_HPP
| 37.925926 | 161 | 0.643276 | pc2 |
6e339411f19deeeb69e2f45a4f82f7ee1bc85668 | 850 | cpp | C++ | JAL/PAT/Advanced/1099.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | JAL/PAT/Advanced/1099.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | JAL/PAT/Advanced/1099.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2020-04-20T11:16:53.000Z | 2021-01-02T15:58:35.000Z | #include<bits/stdc++.h>
using namespace std;
vector<pair<int, int>>v;
vector<int>preorder, a;
map<int, int>M;
int n;
void dfs(int root){
if(root == -1)return;
dfs(v[root].first);
preorder.push_back(root);
dfs(v[root].second);
}
int main(){
cin >> n;
v.resize(n);
for(int i = 0; i < n; i++){
cin >> v[i].first >> v[i].second;
}
a.resize(n);
for(auto &i: a){
cin >> i;
}
sort(a.begin(), a.end());
dfs(0);
assert(preorder.size() == n);
for(int i = 0; i < n; i++){
M[preorder[i]] = a[i];
}
queue<int>Q;
Q.push(0);
vector<int>res;
while(Q.size()){
int head = Q.front();
res.push_back(M[head]);
Q.pop();
if(v[head].first != -1)
Q.push(v[head].first);
if(v[head].second != -1)
Q.push(v[head].second);
}
for(int i = 0; i < res.size(); i++){
if(i)cout << " " << res[i];
else cout << res[i];
}
cout << endl;
} | 17.708333 | 37 | 0.544706 | webturing |
6e36a0342a3c3168b494244b86008946b851782f | 4,329 | cpp | C++ | src/GC/Circuit.cpp | GPikra/python-smpc-wrapper-importer | 43a8945e63f7c8996da699dae0a9f9240084214f | [
"BSD-2-Clause"
] | 3 | 2019-08-10T10:03:15.000Z | 2020-05-20T03:53:40.000Z | src/GC/Circuit.cpp | GPikra/python-smpc-wrapper-importer | 43a8945e63f7c8996da699dae0a9f9240084214f | [
"BSD-2-Clause"
] | 6 | 2019-06-10T13:20:34.000Z | 2019-07-10T17:28:52.000Z | src/GC/Circuit.cpp | athenarc/SCALE-MAMBA | 18fa886d820bec7e441448357b8f09e2be0e7c9e | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
Copyright (c) 2018, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
All rights reserved
*/
#include "Circuit.h"
istream &operator>>(istream &s, Circuit &C)
{
unsigned int nG, te;
s >> nG >> C.nWires;
C.num_AND= 0;
C.GateT.resize(nG);
C.GateI.resize(nG, vector<unsigned int>(2));
C.GateO.resize(nG);
s >> te;
C.numI.resize(te);
for (unsigned int i= 0; i < C.numI.size(); i++)
{
s >> C.numI[i];
}
s >> te;
C.numO.resize(te);
for (unsigned int i= 0; i < C.numO.size(); i++)
{
s >> C.numO[i];
}
unsigned int in, out;
string ss;
for (unsigned int i= 0; i < nG; i++)
{
s >> in >> out;
if (in > 2 || out > 1)
{
throw circuit_error();
}
for (unsigned int j= 0; j < in; j++)
{
s >> C.GateI[i][j];
}
s >> C.GateO[i];
s >> ss;
if (ss.compare("AND") == 0)
{
C.GateT[i]= AND;
C.num_AND++;
}
else if (ss.compare("XOR") == 0)
{
C.GateT[i]= XOR;
}
else if (ss.compare("INV") == 0)
{
C.GateT[i]= INV;
}
else
{
throw circuit_error();
}
if (C.GateT[i] == INV && in == 2)
{
throw circuit_error();
}
if (C.GateT[i] != INV && in == 1)
{
throw circuit_error();
}
}
// Define map between AND gates and the actual gates
C.map.resize(C.num_AND);
C.imap.resize(nG);
// Set stupid default value for imap, to be caught in access function
for (unsigned int i= 0; i < nG; i++)
{
C.imap[i]= 2 * nG;
}
unsigned int cnt= 0;
for (unsigned int i= 0; i < nG; i++)
{
if (C.GateT[i] == AND)
{
C.map[cnt]= i;
C.imap[i]= cnt;
cnt++;
}
}
return s;
}
ostream &operator<<(ostream &s, const Circuit &C)
{
s << C.GateT.size() << " " << C.nWires << endl;
s << C.numI.size() << " ";
for (unsigned int i= 0; i < C.numI.size(); i++)
{
s << C.numI[i] << " ";
}
s << endl;
s << C.numO.size() << " ";
for (unsigned int i= 0; i < C.numO.size(); i++)
{
s << C.numO[i] << " ";
}
s << endl
<< endl;
for (unsigned int i= 0; i < C.GateT.size(); i++)
{
if (C.GateT[i] == INV)
{
s << "1 1 " << C.GateI[i][0] << " " << C.GateO[i] << " INV\n";
}
else
{
s << "2 1 " << C.GateI[i][0] << " " << C.GateI[i][1] << " ";
s << C.GateO[i] << " ";
if (C.GateT[i] == AND)
{
s << "AND\n";
}
else
{
s << "XOR\n";
}
}
}
s << endl;
return s;
}
void Circuit::evaluate(const vector<vector<int>> &inputs,
vector<vector<int>> &outputs) const
{
vector<int> W(nWires);
for (unsigned int i= 0; i < nWires; i++)
{
W[i]= -1;
}
// Load inputs
unsigned int cnt= 0;
for (unsigned int i= 0; i < numI.size(); i++)
{
for (unsigned int j= 0; j < numI[i]; j++)
{
W[cnt]= inputs[i][j];
cnt++;
}
}
// Evaluate the circuit
for (unsigned int i= 0; i < GateT.size(); i++)
{ // First check if ordering is broken
if (W[GateI[i][0]] < 0)
{
throw circuit_error();
}
if (GateT[i] != INV && W[GateI[i][1]] < 0)
{
throw circuit_error();
}
// Now evaluate the gate
if (GateT[i] == AND)
{
W[GateO[i]]= W[GateI[i][0]] & W[GateI[i][1]];
}
else if (GateT[i] == XOR)
{
W[GateO[i]]= W[GateI[i][0]] ^ W[GateI[i][1]];
}
else
{
W[GateO[i]]= 1 - W[GateI[i][0]];
}
}
// Now produce the output
outputs.resize(numO.size());
cnt= nWires;
for (unsigned int i= 0; i < numO.size(); i++)
{
cnt-= numO[i];
}
for (unsigned int i= 0; i < numO.size(); i++)
{
outputs[i].resize(numO[i]);
for (unsigned int j= 0; j < numO[i]; j++)
{
outputs[i][j]= W[cnt];
cnt++;
}
}
}
| 21.325123 | 110 | 0.429891 | GPikra |
6e38645a4bf8350cb46779807f81f4526a749086 | 15,415 | cpp | C++ | src/core/tunnel/TunnelPool.cpp | moneromooo-monero/kovri | 7532037cd590617c27474112080e4bbc52faf586 | [
"BSD-3-Clause"
] | 2 | 2017-10-13T09:22:20.000Z | 2018-02-13T16:32:02.000Z | src/core/tunnel/TunnelPool.cpp | Menutra/kovri | 7532037cd590617c27474112080e4bbc52faf586 | [
"BSD-3-Clause"
] | null | null | null | src/core/tunnel/TunnelPool.cpp | Menutra/kovri | 7532037cd590617c27474112080e4bbc52faf586 | [
"BSD-3-Clause"
] | 2 | 2017-10-15T08:21:55.000Z | 2018-11-29T08:40:06.000Z | /**
* Copyright (c) 2013-2016, The Kovri I2P Router Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Parts of the project are originally copyright (c) 2013-2015 The PurpleI2P Project
*/
#include "TunnelPool.h"
#include <algorithm>
#include <vector>
#include "Garlic.h"
#include "NetworkDatabase.h"
#include "Tunnel.h"
#include "crypto/Rand.h"
#include "transport/Transports.h"
#include "util/I2PEndian.h"
#include "util/Timestamp.h"
#include "util/Log.h"
namespace i2p {
namespace tunnel {
TunnelPool::TunnelPool(
i2p::garlic::GarlicDestination* localDestination,
int numInboundHops,
int numOutboundHops,
int numInboundTunnels,
int numOutboundTunnels)
: m_LocalDestination(localDestination),
m_NumInboundHops(numInboundHops),
m_NumOutboundHops(numOutboundHops),
m_NumInboundTunnels(numInboundTunnels),
m_NumOutboundTunnels(numOutboundTunnels),
m_IsActive(true) {}
TunnelPool::~TunnelPool() {
DetachTunnels();
}
void TunnelPool::SetExplicitPeers(
std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers) {
m_ExplicitPeers = explicitPeers;
if (m_ExplicitPeers) {
int size = m_ExplicitPeers->size();
if (m_NumInboundHops > size) {
m_NumInboundHops = size;
LogPrint(eLogInfo,
"TunnelPool: inbound tunnel length has been adjusted to ",
size, " for explicit peers");
}
if (m_NumOutboundHops > size) {
m_NumOutboundHops = size;
LogPrint(eLogInfo,
"TunnelPool: outbound tunnel length has been adjusted to ",
size, " for explicit peers");
}
m_NumInboundTunnels = 1;
m_NumOutboundTunnels = 1;
}
}
void TunnelPool::DetachTunnels() {
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels)
it->SetTunnelPool(nullptr);
m_InboundTunnels.clear();
}
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
it->SetTunnelPool(nullptr);
m_OutboundTunnels.clear();
}
m_Tests.clear();
}
void TunnelPool::TunnelCreated(
std::shared_ptr<InboundTunnel> createdTunnel) {
if (!m_IsActive)
return;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.insert(createdTunnel);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated();
}
void TunnelPool::TunnelExpired(
std::shared_ptr<InboundTunnel> expiredTunnel) {
if (expiredTunnel) {
expiredTunnel->SetTunnelPool(nullptr);
for (auto it : m_Tests)
if (it.second.second == expiredTunnel)
it.second.second = nullptr;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase(expiredTunnel);
}
}
void TunnelPool::TunnelCreated(
std::shared_ptr<OutboundTunnel> createdTunnel) {
if (!m_IsActive)
return;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.insert(createdTunnel);
}
// CreatePairedInboundTunnel (createdTunnel);
// TODO(unassigned): ^ ???
}
void TunnelPool::TunnelExpired(
std::shared_ptr<OutboundTunnel> expiredTunnel) {
if (expiredTunnel) {
expiredTunnel->SetTunnelPool(nullptr);
for (auto it : m_Tests)
if (it.second.first == expiredTunnel)
it.second.first = nullptr;
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase(expiredTunnel);
}
}
std::vector<std::shared_ptr<InboundTunnel> > TunnelPool::GetInboundTunnels(
int num) const {
std::vector<std::shared_ptr<InboundTunnel> > v;
int i = 0;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels) {
if (i >= num) break;
if (it->IsEstablished()) {
v.push_back(it);
i++;
}
}
return v;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNextOutboundTunnel(
std::shared_ptr<OutboundTunnel> excluded) const {
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
return GetNextTunnel(m_OutboundTunnels, excluded);
}
std::shared_ptr<InboundTunnel> TunnelPool::GetNextInboundTunnel(
std::shared_ptr<InboundTunnel> excluded) const {
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
return GetNextTunnel(m_InboundTunnels, excluded);
}
template<class TTunnels>
typename TTunnels::value_type TunnelPool::GetNextTunnel(
TTunnels& tunnels,
typename TTunnels::value_type excluded) const {
if (tunnels.empty ())
return nullptr;
uint32_t ind = i2p::crypto::RandInRange<uint32_t>(0, tunnels.size() / 2);
uint32_t i = 0;
typename TTunnels::value_type tunnel = nullptr;
for (auto it : tunnels) {
if (it->IsEstablished() && it != excluded) {
tunnel = it;
i++;
}
if (i > ind && tunnel)
break;
}
if (!tunnel && excluded && excluded->IsEstablished())
tunnel = excluded;
return tunnel;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNewOutboundTunnel(
std::shared_ptr<OutboundTunnel> old) const {
if (old && old->IsEstablished())
return old;
std::shared_ptr<OutboundTunnel> tunnel;
if (old) {
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
if (it->IsEstablished() &&
old->GetEndpointRouter()->GetIdentHash() ==
it->GetEndpointRouter()->GetIdentHash()) {
tunnel = it;
break;
}
}
if (!tunnel)
tunnel = GetNextOutboundTunnel();
return tunnel;
}
void TunnelPool::CreateTunnels() {
int num = 0;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels)
if (it->IsEstablished())
num++;
}
for (int i = num; i < m_NumInboundTunnels; i++)
CreateInboundTunnel();
num = 0;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
if (it->IsEstablished())
num++;
}
for (int i = num; i < m_NumOutboundTunnels; i++)
CreateOutboundTunnel();
}
void TunnelPool::TestTunnels() {
for (auto it : m_Tests) {
LogPrint(eLogWarn,
"TunnelPool: tunnel test ", static_cast<int>(it.first), " failed");
// if test failed again with another tunnel we consider it failed
if (it.second.first) {
if (it.second.first->GetState() == e_TunnelStateTestFailed) {
it.second.first->SetState(e_TunnelStateFailed);
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase(it.second.first);
} else {
it.second.first->SetState(e_TunnelStateTestFailed);
}
}
if (it.second.second) {
if (it.second.second->GetState() == e_TunnelStateTestFailed) {
it.second.second->SetState(e_TunnelStateFailed);
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase(it.second.second);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated();
} else {
it.second.second->SetState(e_TunnelStateTestFailed);
}
}
}
m_Tests.clear();
// new tests
auto it1 = m_OutboundTunnels.begin();
auto it2 = m_InboundTunnels.begin();
while (it1 != m_OutboundTunnels.end() && it2 != m_InboundTunnels.end()) {
bool failed = false;
if ((*it1)->IsFailed()) {
failed = true;
it1++;
}
if ((*it2)->IsFailed()) {
failed = true;
it2++;
}
if (!failed) {
uint32_t msgID = i2p::crypto::Rand<uint32_t>();
m_Tests[msgID] = std::make_pair(*it1, *it2);
(*it1)->SendTunnelDataMsg(
(*it2)->GetNextIdentHash(),
(*it2)->GetNextTunnelID(),
CreateDeliveryStatusMsg(msgID));
it1++;
it2++;
}
}
}
void TunnelPool::ProcessGarlicMessage(
std::shared_ptr<I2NPMessage> msg) {
if (m_LocalDestination)
m_LocalDestination->ProcessGarlicMessage(msg);
else
LogPrint(eLogWarn,
"TunnelPool: local destination doesn't exist, dropped");
}
void TunnelPool::ProcessDeliveryStatus(
std::shared_ptr<I2NPMessage> msg) {
const uint8_t* buf = msg->GetPayload();
uint32_t msgID = bufbe32toh(buf);
buf += 4;
uint64_t timestamp = bufbe64toh(buf);
auto it = m_Tests.find(msgID);
if (it != m_Tests.end()) {
// restore from test failed state if any
if (it->second.first->GetState() == e_TunnelStateTestFailed)
it->second.first->SetState(e_TunnelStateEstablished);
if (it->second.second->GetState() == e_TunnelStateTestFailed)
it->second.second->SetState(e_TunnelStateEstablished);
LogPrint(eLogInfo,
"TunnelPool: tunnel test ", it->first,
" successful: ", i2p::util::GetMillisecondsSinceEpoch() - timestamp,
" milliseconds");
m_Tests.erase(it);
} else {
if (m_LocalDestination)
m_LocalDestination->ProcessDeliveryStatusMessage(msg);
else
LogPrint(eLogWarn, "TunnelPool: local destination doesn't exist, dropped");
}
}
std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop(
std::shared_ptr<const i2p::data::RouterInfo> prevHop) const {
// TODO(unassigned): implement it better
bool isExploratory = (m_LocalDestination == &i2p::context);
auto hop = isExploratory ?
i2p::data::netdb.GetRandomRouter(prevHop) :
i2p::data::netdb.GetHighBandwidthRandomRouter(prevHop);
if (!hop || hop->GetProfile ()->IsBad())
hop = i2p::data::netdb.GetRandomRouter();
return hop;
}
bool TunnelPool::SelectPeers(
std::vector<std::shared_ptr<const i2p::data::RouterInfo> >& hops,
bool isInbound) {
if (m_ExplicitPeers)
return SelectExplicitPeers(hops, isInbound);
auto prevHop = i2p::context.GetSharedRouterInfo();
int numHops = isInbound ?
m_NumInboundHops :
m_NumOutboundHops;
if (i2p::transport::transports.GetNumPeers() > 25) {
auto r = i2p::transport::transports.GetRandomPeer();
if (r && !r->GetProfile()->IsBad()) {
prevHop = r;
hops.push_back(r);
numHops--;
}
}
for (int i = 0; i < numHops; i++) {
auto hop = SelectNextHop(prevHop);
if (!hop) {
LogPrint(eLogError, "TunnelPool: can't select next hop");
return false;
}
prevHop = hop;
hops.push_back(hop);
}
return true;
}
bool TunnelPool::SelectExplicitPeers(
std::vector<std::shared_ptr<const i2p::data::RouterInfo> >& hops,
bool isInbound) {
int size = m_ExplicitPeers->size();
std::vector<int> peerIndicies;
for (int i = 0; i < size; i++)
peerIndicies.push_back(i);
std::random_shuffle(peerIndicies.begin(), peerIndicies.end());
int numHops = isInbound ? m_NumInboundHops : m_NumOutboundHops;
for (int i = 0; i < numHops; i++) {
auto& ident = (*m_ExplicitPeers)[peerIndicies[i]];
auto r = i2p::data::netdb.FindRouter(ident);
if (r) {
hops.push_back(r);
} else {
LogPrint(eLogInfo,
"TunnelPool: can't find router for ", ident.ToBase64());
i2p::data::netdb.RequestDestination(ident);
return false;
}
}
return true;
}
void TunnelPool::CreateInboundTunnel() {
auto outboundTunnel = GetNextOutboundTunnel();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel();
LogPrint(eLogInfo, "TunnelPool: creating destination inbound tunnel");
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
if (SelectPeers(hops, true)) {
std::reverse(hops.begin(), hops.end());
auto tunnel = tunnels.CreateTunnel<InboundTunnel> (
std::make_shared<TunnelConfig> (hops),
outboundTunnel);
tunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't create inbound tunnel, no peers available");
}
}
void TunnelPool::RecreateInboundTunnel(
std::shared_ptr<InboundTunnel> tunnel) {
auto outboundTunnel = GetNextOutboundTunnel();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel();
LogPrint(eLogInfo, "TunnelPool: re-creating destination inbound tunnel");
auto newTunnel =
tunnels.CreateTunnel<InboundTunnel> (
tunnel->GetTunnelConfig()->Clone(),
outboundTunnel);
newTunnel->SetTunnelPool(shared_from_this());
}
void TunnelPool::CreateOutboundTunnel() {
auto inboundTunnel = GetNextInboundTunnel();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel();
if (inboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: creating destination outbound tunnel");
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
if (SelectPeers(hops, false)) {
auto tunnel = tunnels.CreateTunnel<OutboundTunnel> (
std::make_shared<TunnelConfig> (
hops,
inboundTunnel->GetTunnelConfig()));
tunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't create outbound tunnel, no peers available");
}
} else {
LogPrint(eLogError,
"TunnelPool: can't create outbound tunnel, no inbound tunnels found");
}
}
void TunnelPool::RecreateOutboundTunnel(
std::shared_ptr<OutboundTunnel> tunnel) {
auto inboundTunnel = GetNextInboundTunnel();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel();
if (inboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: re-creating destination outbound tunnel");
auto newTunnel = tunnels.CreateTunnel<OutboundTunnel> (
tunnel->GetTunnelConfig()->Clone(
inboundTunnel->GetTunnelConfig()));
newTunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't re-create outbound tunnel, no inbound tunnels found");
}
}
void TunnelPool::CreatePairedInboundTunnel(
std::shared_ptr<OutboundTunnel> outboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: creating paired inbound tunnel");
auto tunnel = tunnels.CreateTunnel<InboundTunnel> (
outboundTunnel->GetTunnelConfig()->Invert(),
outboundTunnel);
tunnel->SetTunnelPool(shared_from_this());
}
} // namespace tunnel
} // namespace i2p
| 32.114583 | 90 | 0.684139 | moneromooo-monero |
6e3881616a89359c3390c471bce95a7a6ea66c36 | 5,950 | cpp | C++ | test/cedar_tests.cpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2017-03-04T13:04:49.000Z | 2021-12-03T06:58:20.000Z | test/cedar_tests.cpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 27 | 2016-01-22T18:31:37.000Z | 2021-11-27T10:50:40.000Z | test/cedar_tests.cpp | dominiKoeppl/tudocomp | b5512f85f6b3408fb88e19c08899ec4c2716c642 | [
"ECL-2.0",
"Apache-2.0"
] | 16 | 2017-03-14T12:46:51.000Z | 2021-06-25T18:19:50.000Z |
#include "test/util.hpp"
#include <gtest/gtest.h>
#include <tudocomp/CreateAlgorithm.hpp>
#include <tudocomp/Literal.hpp>
#include <tudocomp/compressors/LZ78Compressor.hpp>
#include <tudocomp/compressors/LZWCompressor.hpp>
#include <tudocomp/compressors/lz78/BinaryTrie.hpp>
#include <tudocomp/compressors/lz78/TernaryTrie.hpp>
#include <tudocomp/compressors/lz78/CedarTrie.hpp>
#include <tudocomp/coders/ASCIICoder.hpp>
#include <tudocomp/coders/BitCoder.hpp>
using namespace tdc;
struct InputOutput {
View in;
View out;
};
std::ostream& operator<<(std::ostream& os, const InputOutput& v) {
return os << v.in << " : " << v.out;
}
class NotCedarLz78Compress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(NotCedarLz78Compress, test) {
auto c = create_algo<LZ78Compressor<ASCIICoder, lz78::BinaryTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(
InputOutput, NotCedarLz78Compress, ::testing::Values(
InputOutput { "aababcabcdabcde"_v, "0:a1:b2:c3:d4:e\0"_v },
InputOutput { "aababcabcdabcdeabc"_v, "0:a1:b2:c3:d4:e2:c\0"_v },
InputOutput { "\0\0b\0bc\0bcd\0bcde"_v, "0:\0""1:b2:c3:d4:e\0"_v },
InputOutput { "\xfe\xfe""b\xfe""bc\xfe""bcd\xfe""bcde"_v, "0:\xfe""1:b2:c3:d4:e\0"_v },
InputOutput { "\xff\xff""b\xff""bc\xff""bcd\xff""bcde"_v, "0:\xff""1:b2:c3:d4:e\0"_v }
)
);
class CedarLz78Compress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(CedarLz78Compress, test) {
auto c = create_algo<LZ78Compressor<ASCIICoder, lz78::CedarTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(
InputOutput, CedarLz78Compress, ::testing::Values(
InputOutput { "aababcabcdabcde"_v, "0:a1:b2:c3:d4:e\0"_v },
InputOutput { "aababcabcdabcdeabc"_v, "0:a1:b2:c3:d4:e2:c\0"_v },
InputOutput { "\0\0b\0bc\0bcd\0bcde"_v, "0:\0""1:b2:c3:d4:e\0"_v },
InputOutput { "\xfe\xfe""b\xfe""bc\xfe""bcd\xfe""bcde"_v, "0:\xfe""1:b2:c3:d4:e\0"_v },
InputOutput { "\xff\xff""b\xff""bc\xff""bcd\xff""bcde"_v, "0:\xff""1:b2:c3:d4:e\0"_v }
)
);
class NotCedarLzwCompress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(NotCedarLzwCompress, test) {
auto c = create_algo<LZWCompressor<ASCIICoder, lz78::BinaryTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(InputOutput,
NotCedarLzwCompress,
::testing::Values(
InputOutput { "aaaaaa"_v, "97:256:257:\0"_v },
InputOutput { "aaaaaaa"_v, "97:256:257:97:\0"_v },
InputOutput { "a\0b"_v, "97:0:98:\0"_v },
InputOutput { "a\xfe""b"_v, "97:254:98:\0"_v },
InputOutput { "a\xff""b"_v, "97:255:98:\0"_v },
InputOutput { "\0\0\0"_v, "0:256:\0"_v },
InputOutput { "\xfe\xfe\xfe"_v, "254:256:\0"_v },
InputOutput { "\xff\xff\xff"_v, "255:256:\0"_v }
));
class CedarLzwCompress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(CedarLzwCompress, test) {
auto c = create_algo<LZWCompressor<ASCIICoder, lz78::CedarTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(InputOutput,
CedarLzwCompress,
::testing::Values(
InputOutput { "aaaaaa"_v, "97:256:257:\0"_v },
InputOutput { "aaaaaaa"_v, "97:256:257:97:\0"_v },
InputOutput { "a\0b"_v, "97:0:98:\0"_v },
InputOutput { "a\xfe""b"_v, "97:254:98:\0"_v },
InputOutput { "a\xff""b"_v, "97:255:98:\0"_v },
InputOutput { "\0\0\0"_v, "0:256:\0"_v },
InputOutput { "\xfe\xfe\xfe"_v, "254:256:\0"_v },
InputOutput { "\xff\xff\xff"_v, "255:256:\0"_v }
));
/*
TEST(zcedar, base) {
cedar::da<uint32_t> trie;
for (uint16_t j = 0; j < 256; j++) {
const char c = uint8_t(j);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto i = j;
//DLOG(INFO) << "i: " << i << ", from: " << from << ", pos: " << pos;
trie.update(letter, from, pos, 1, i);
DLOG(INFO) << "i: " << i << ", from: " << from << ", pos: " << pos;
}
for (uint16_t i = 0; i < 256; i++) {
const char c = uint8_t(i);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto r = trie.traverse(letter, from, pos, 1);
DLOG(INFO) << "r: " << r << ", from: " << from << ", pos: " << pos
<< ", NO_PATH: " << int(r == lz78::CEDAR_NO_PATH)
<< ", NO_VALUE: " << int(r == lz78::CEDAR_NO_VALUE);
}
for (uint16_t i = 0; i < 256; i++) {
const char c = uint8_t(i);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto r = trie.traverse(letter, from, pos, 1);
//if (r != lz78::CEDAR_NO_PATH && r != lz78::CEDAR_NO_VALUE)
{
const char c2 = 'a';
auto letter2 = &c2;
pos = 0;
trie.update(letter2, from, pos, 1);
}
DLOG(INFO) << " r: " << r << ", from: " << from << ", pos: " << pos
<< ", NO_PATH: " << int(r == lz78::CEDAR_NO_PATH)
<< ", NO_VALUE: " << int(r == lz78::CEDAR_NO_VALUE);
}
}
*/
| 36.956522 | 95 | 0.540168 | dominiKoeppl |
6e38cb0168023c5355f8e8a4f19f36e6fc814cc8 | 5,979 | hh | C++ | trick_source/er7_utils/integration/symplectic_euler/include/symplectic_euler_integrator_constructor.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 647 | 2015-05-07T16:08:16.000Z | 2022-03-30T02:33:21.000Z | trick_source/er7_utils/integration/symplectic_euler/include/symplectic_euler_integrator_constructor.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 995 | 2015-04-30T19:44:31.000Z | 2022-03-31T20:14:44.000Z | trick_source/er7_utils/integration/symplectic_euler/include/symplectic_euler_integrator_constructor.hh | gilbertguoze/trick | f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21 | [
"NASA-1.3"
] | 251 | 2015-05-15T09:24:34.000Z | 2022-03-22T20:39:05.000Z | /**
* @if Er7UtilsUseGroups
* @addtogroup Er7Utils
* @{
* @addtogroup Integration
* @{
* @endif
*/
/**
* @file
* Defines the class SymplecticEulerIntegratorConstructor, which constructs
* state integrators that use symplectic Euler integration.
*/
/*
Purpose: ()
*/
#ifndef ER7_UTILS_SYMPLECTIC_EULER_INTEGRATOR_CONSTRUCTOR_HH
#define ER7_UTILS_SYMPLECTIC_EULER_INTEGRATOR_CONSTRUCTOR_HH
// System includes
// Interface includes
#include "er7_utils/interface/include/er7_class.hh"
// Integration includes
#include "er7_utils/integration/core/include/integrator_constructor.hh"
namespace er7_utils {
/**
* Create controls and integrators and that propagate using symplectic Euler.
*/
class SymplecticEulerIntegratorConstructor : public IntegratorConstructor {
ER7_UTILS_MAKE_SIM_INTERFACES(SymplecticEulerIntegratorConstructor)
public:
// Static member functions.
/**
* Named constructor; create a SymplecticEulerIntegratorConstructor.
* The caller is responsible for deleting the returned object.
* @return Newly created SymplecticEulerIntegratorConstructor.
*/
static IntegratorConstructor* create_constructor (void);
// Constructors and destructor.
// Note: The copy constructor and assignment operator for this
// class are not declared. The C++ defaults suffice for this class.
/**
* SymplecticEulerIntegratorConstructor default constructor.
*/
SymplecticEulerIntegratorConstructor (void)
{ }
/**
* SymplecticEulerIntegratorConstructor destructor.
*/
virtual ~SymplecticEulerIntegratorConstructor (void)
{ }
// Member functions.
/**
* Return the class name.
*/
virtual const char * get_class_name (void) const
{ return "SymplecticEulerIntegratorConstructor"; }
/**
* Symplectic Euler is a second order technique; it provides but does not
* implement a first order ODE integrator.
*/
virtual bool implements (Integration::ODEProblemType problem_type) const
{
return problem_type != Integration::FirstOrderODE;
}
/**
* Create a duplicate of the constructor.
* The caller is responsible for deleting the returned object.
* @return Duplicated constructor.
*/
virtual IntegratorConstructor * create_copy (void) const;
/**
* Create an integration controls that guides the symplectic Euler
* integration process.
* The caller is responsible for deleting the created object.
* @return Integration controls object
*/
virtual IntegrationControls * create_integration_controls (void) const;
/**
* Create an Euler state integrator for a first order ODE.
* Note that this creates an Euler integrator as a surrogate.
* There is no such thing as a first order symplectic Euler integrator.
* The caller is responsible for deleting the created object.
* @return State integrator
* @param[in] size State size
* @param[in,out] controls Integration controls
*/
virtual FirstOrderODEIntegrator * create_first_order_ode_integrator (
unsigned int size,
IntegrationControls & controls) const;
/**
* Create a symplectic Euler state integrator for a simple second order ODE.
* The caller is responsible for deleting the created object.
* @return State integrator
* @param[in] size State size
* @param[in,out] controls Integration controls
*/
virtual SecondOrderODEIntegrator * create_second_order_ode_integrator (
unsigned int size,
IntegrationControls & controls) const;
/**
* Create a symplectic Euler state integrator for a generalized second order
* ODE where generalized position is advanced with the use of the derivatives
* function.
* The caller is responsible for deleting the created object.
* @return State integrator
* @param[in] position_size Size of the generalized position
* @param[in] velocity_size Size of the generalized velocity
* @param[in] deriv_funs Position derivative functions container
* @param[in,out] controls Integration controls
*/
virtual SecondOrderODEIntegrator *
create_generalized_deriv_second_order_ode_integrator (
unsigned int position_size,
unsigned int velocity_size,
const GeneralizedPositionDerivativeFunctions & deriv_funs,
IntegrationControls & controls) const;
/**
* Create a symplectic Euler state integrator for a generalized second order
* ODE where generalized position is advanced with the use of the step
* function.
* The caller is responsible for deleting the created object.
* @return State integrator
* @param[in] position_size Size of the generalized position
* @param[in] velocity_size Size of the generalized velocity
* @param[in] step_funs Position step functions container
* @param[in,out] controls Integration controls
*/
virtual SecondOrderODEIntegrator *
create_generalized_step_second_order_ode_integrator (
unsigned int position_size,
unsigned int velocity_size,
const GeneralizedPositionStepFunctions & step_funs,
IntegrationControls & controls) const;
/**
* Indicate whether the integration technique explicitly solves a second
* order ODE. Symplectic Euler is such a technique.
* @return Always returns true.
*/
virtual bool is_second_order_ode_technique (void) const
{ return true; }
/**
* Euler uses one step per cycle.
* @return Always returns 1.
*/
virtual unsigned int get_transition_table_size (void) const
{ return 1; }
};
}
#ifdef ER7_UTILS_NEED_AUX_INCLUDES
#include "er7_utils/integration/core/include/single_cycle_integration_controls.hh"
#include "er7_utils/integration/euler/include/euler_first_order_ode_integrator.hh"
#include "symplectic_euler_second_order_ode_integrator.hh"
#endif
#endif
/**
* @if Er7UtilsUseGroups
* @}
* @}
* @endif
*/
| 29.895 | 82 | 0.72487 | gilbertguoze |